@zonease/aiworker-cli 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/aiworker-bun.js +237 -227
  2. package/official-apps/aiworker-hr/dist/index.js +194 -79
  3. package/official-apps/aiworker-hr/dist/{host-mounted.js → mounted/host-mounted.js} +195 -80
  4. package/official-apps/aiworker-hr/dist/{standalone.js → standalone/standalone.js} +195 -80
  5. package/official-apps/aiworker-hr/engine-assets/workspace/AGENTS.md +38 -0
  6. package/official-apps/aiworker-hr/engine-assets/workspace/CLAUDE.md +1 -0
  7. package/official-apps/aiworker-hr/engine-assets/workspace/README.md +17 -0
  8. package/official-apps/aiworker-hr/engine-assets/workspace/evidence/README.md +3 -0
  9. package/official-apps/aiworker-hr/{src → host-adapter}/index.ts +2 -2
  10. package/official-apps/aiworker-hr/{src → host-adapter/mounted}/host-mounted.ts +1 -1
  11. package/official-apps/aiworker-hr/{src → host-adapter/standalone}/standalone.ts +1 -1
  12. package/official-apps/aiworker-hr/package.json +7 -7
  13. package/official-apps/aiworker-hr/soul-app.manifest.json +35 -23
  14. package/official-apps/aiworker-hr/tsconfig.json +2 -2
  15. package/official-apps/aiworker-qa/dist/index.js +194 -79
  16. package/official-apps/aiworker-qa/dist/{host-mounted.js → mounted/host-mounted.js} +195 -80
  17. package/official-apps/aiworker-qa/dist/{standalone.js → standalone/standalone.js} +195 -80
  18. package/official-apps/aiworker-qa/engine-assets/skills/.gitkeep +1 -0
  19. package/official-apps/aiworker-qa/engine-assets/workspace/AGENTS.md +38 -0
  20. package/official-apps/aiworker-qa/engine-assets/workspace/CLAUDE.md +1 -0
  21. package/official-apps/aiworker-qa/engine-assets/workspace/README.md +17 -0
  22. package/official-apps/aiworker-qa/engine-assets/workspace/evidence/README.md +3 -0
  23. package/official-apps/aiworker-qa/{src → host-adapter}/index.ts +2 -2
  24. package/official-apps/aiworker-qa/{src → host-adapter/mounted}/host-mounted.ts +1 -1
  25. package/official-apps/aiworker-qa/{src → host-adapter/standalone}/standalone.ts +1 -1
  26. package/official-apps/aiworker-qa/package.json +7 -7
  27. package/official-apps/aiworker-qa/soul-app.manifest.json +35 -23
  28. package/official-apps/aiworker-qa/tsconfig.json +2 -2
  29. package/package.json +1 -1
  30. /package/official-apps/aiworker-hr/{skills → engine-assets/skills}/candidate-profile/SKILL.md +0 -0
  31. /package/official-apps/aiworker-hr/{skills → engine-assets/skills}/evidence-screening/SKILL.md +0 -0
  32. /package/official-apps/aiworker-hr/{skills → engine-assets/skills}/hiring-risk-review/SKILL.md +0 -0
  33. /package/official-apps/aiworker-hr/{skills → engine-assets/skills}/interview-brief/SKILL.md +0 -0
  34. /package/official-apps/aiworker-hr/{skills → engine-assets/skills}/profile-update-proposal/SKILL.md +0 -0
  35. /package/official-apps/aiworker-hr/{src → host-adapter}/api.ts +0 -0
  36. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/artifact.ts +0 -0
  37. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/connectors.ts +0 -0
  38. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/lifecycle.ts +0 -0
  39. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/review.ts +0 -0
  40. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/runtime.ts +0 -0
  41. /package/official-apps/aiworker-hr/{src → host-adapter}/protocol/ui.ts +0 -0
  42. /package/official-apps/aiworker-hr/{schemas → product/artifacts/schemas}/candidate-screen.schema.json +0 -0
  43. /package/official-apps/aiworker-hr/{schemas → product/artifacts/schemas}/person-profile.schema.json +0 -0
  44. /package/official-apps/aiworker-hr/{packs → product/profiles}/hr-recruiting/SOUL.md +0 -0
  45. /package/official-apps/aiworker-hr/{review → product/reviews}/candidate-screen.md +0 -0
  46. /package/official-apps/aiworker-hr/{review → product/reviews}/person-profile.md +0 -0
  47. /package/official-apps/aiworker-hr/{src/ui → product/web/artifact-previews}/candidate-screen-preview.tsx +0 -0
  48. /package/official-apps/aiworker-hr/{src/ui → product/web/artifact-previews}/person-profile-preview.tsx +0 -0
  49. /package/official-apps/aiworker-hr/{src/ui → product/web/panels}/profile-panel.tsx +0 -0
  50. /package/official-apps/aiworker-hr/{src/ui → product/web/panels}/review-panel.tsx +0 -0
  51. /package/official-apps/aiworker-hr/{src/ui → product/web/routes}/hr-route.tsx +0 -0
  52. /package/official-apps/aiworker-hr/{src/ui → product/web/widgets}/people-widget.tsx +0 -0
  53. /package/official-apps/aiworker-hr/{capabilities → product/workflows}/candidate-screen/prompt.md +0 -0
  54. /package/official-apps/aiworker-hr/{capabilities → product/workflows}/candidate-screen/review.md +0 -0
  55. /package/official-apps/aiworker-hr/{capabilities → product/workflows}/person-profile/prompt.md +0 -0
  56. /package/official-apps/aiworker-hr/{capabilities → product/workflows}/person-profile/review.md +0 -0
  57. /package/official-apps/aiworker-qa/{src → host-adapter}/api.ts +0 -0
  58. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/artifact.ts +0 -0
  59. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/connectors.ts +0 -0
  60. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/lifecycle.ts +0 -0
  61. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/review.ts +0 -0
  62. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/runtime.ts +0 -0
  63. /package/official-apps/aiworker-qa/{src → host-adapter}/protocol/ui.ts +0 -0
  64. /package/official-apps/aiworker-qa/{schemas → product/artifacts/schemas}/regression-matrix.schema.json +0 -0
  65. /package/official-apps/aiworker-qa/{schemas → product/artifacts/schemas}/release-gate.schema.json +0 -0
  66. /package/official-apps/aiworker-qa/{packs → product/profiles}/qa-reviewer/SOUL.md +0 -0
  67. /package/official-apps/aiworker-qa/{review → product/reviews}/regression-matrix.md +0 -0
  68. /package/official-apps/aiworker-qa/{review → product/reviews}/release-gate.md +0 -0
  69. /package/official-apps/aiworker-qa/{src/ui → product/web/artifact-previews}/regression-matrix-preview.tsx +0 -0
  70. /package/official-apps/aiworker-qa/{src/ui → product/web/artifact-previews}/release-gate-preview.tsx +0 -0
  71. /package/official-apps/aiworker-qa/{src/ui → product/web/panels}/release-panel.tsx +0 -0
  72. /package/official-apps/aiworker-qa/{src/ui → product/web/panels}/release-review-panel.tsx +0 -0
  73. /package/official-apps/aiworker-qa/{src/ui → product/web/panels}/review-panel.tsx +0 -0
  74. /package/official-apps/aiworker-qa/{src/ui → product/web/routes}/qa-route.tsx +0 -0
  75. /package/official-apps/aiworker-qa/{src/ui → product/web/widgets}/release-widget.tsx +0 -0
  76. /package/official-apps/aiworker-qa/{capabilities → product/workflows}/regression-matrix/prompt.md +0 -0
  77. /package/official-apps/aiworker-qa/{capabilities → product/workflows}/regression-matrix/review.md +0 -0
  78. /package/official-apps/aiworker-qa/{capabilities → product/workflows}/release-gate/prompt.md +0 -0
  79. /package/official-apps/aiworker-qa/{capabilities → product/workflows}/release-gate/review.md +0 -0
package/aiworker-bun.js CHANGED
@@ -1,151 +1,151 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var MC=Object.defineProperty;var Q=(D,u)=>()=>(u||D((u={exports:{}}).exports,u),u.exports);var OC=(D)=>D;function PC(D,u){this[D]=OC.bind(null,u)}var dA=(D,u)=>{for(var r in u)MC(D,r,{get:u[r],enumerable:!0,configurable:!0,set:PC.bind(u,r)})};var W=(D,u)=>()=>(D&&(u=D(D=0)),u);var yA=import.meta.require;import{homedir as iC}from"os";import O3 from"path";import lA from"process";function P7(){return lA.env.HOME&&lA.env.HOME.length>0?lA.env.HOME:iC()}function i7(D){return D.startsWith("~")?O3.join(P7(),D.slice(1)):D}function O7(D){return O3.resolve(i7(D))}function VC(D){return O3.resolve(P7(),i7(D))}function P3(D={}){if(D.explicitHome&&D.explicitHome.length>0)return{scope:"explicit",home:O7(D.explicitHome),source:"cli-flag"};let u=lA.env[kC];if(u&&u.length>0)return{scope:"explicit",home:O7(u),source:"env"};let r=D.defaultHomeDir&&D.defaultHomeDir.length>0?D.defaultHomeDir:IC;return{scope:"user",home:VC(r),source:"user-default"}}function i3(D={}){return P3(D).home}var kC="AIWORKER_HOME",IC=".aiworker";var k3=()=>{};function Y(D,u){if(!D||typeof D!=="object")return!1;if(D instanceof u)return!0;if(!Object.prototype.hasOwnProperty.call(u,X))throw Error(`Class "${u.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(D).constructor;if(r)while(r){if(X in r&&r[X]===u[X])return!0;r=Object.getPrototypeOf(r)}return!1}var X;var l=W(()=>{X=Symbol.for("drizzle:entityKind")});var wD;var Ku=W(()=>{l();wD=class wD{constructor(D,u){this.table=D,this.config=u,this.name=u.name,this.keyAsName=u.keyAsName,this.notNull=u.notNull,this.default=u.default,this.defaultFn=u.defaultFn,this.onUpdateFn=u.onUpdateFn,this.hasDefault=u.hasDefault,this.primary=u.primaryKey,this.isUnique=u.isUnique,this.uniqueName=u.uniqueName,this.uniqueType=u.uniqueType,this.dataType=u.dataType,this.columnType=u.columnType,this.generated=u.generated,this.generatedIdentity=u.generatedIdentity}static[X]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(D){return D}mapToDriverValue(D){return D}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var I3;var V3=W(()=>{l();I3=class I3{static[X]="ColumnBuilder";config;constructor(D,u,r){this.config={name:D,keyAsName:D==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:u,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(D){return this.config.default=D,this.config.hasDefault=!0,this}$defaultFn(D){return this.config.defaultFn=D,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(D){return this.config.onUpdateFn=D,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(D){if(this.config.name!=="")return;this.config.name=D}}});var _u;var a2=W(()=>{_u=Symbol.for("drizzle:Name")});function k7(D,...u){return D(...u)}var I7=()=>{};function V7(D,u){return`${D[_u]}_${u.join("_")}_unique`}var K7=W(()=>{a2()});var e2,KC;var h7=W(()=>{Ku();l();K7();e2=class e2 extends wD{constructor(D,u){if(!u.uniqueName)u.uniqueName=V7(D,[u.name]);super(D,u);this.table=D}static[X]="PgColumn"};KC=class KC extends e2{static[X]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(D){return this.indexConfig.opClass=D,this}}});function Q7(D){return!!D&&typeof D==="function"&&N7 in D&&D[N7]===!0}var hC,N7,NC;var L7=W(()=>{l();h7();hC=class hC extends e2{static[X]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(D,u){super(D,u);this.enum=u.enum}getSQLType(){return this.enum.enumName}};N7=Symbol.for("drizzle:isPgEnum");NC=class NC extends e2{static[X]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(D,u){super(D,u);this.enum=u.enum}getSQLType(){return this.enum.enumName}}});var iD,D1;var hu=W(()=>{l();iD=class iD{static[X]="Subquery";constructor(D,u,r,A=!1,f=[]){this._={brand:"Subquery",sql:D,selectedFields:u,alias:r,isWith:A,usedTables:f}}};D1=class D1 extends iD{static[X]="WithSubquery"}});var q7="0.44.7";var b7=()=>{};var K3,h3,z7;var j7=W(()=>{I7();b7();z7={startActiveSpan(D,u){if(!K3)return u();if(!h3)h3=K3.trace.getTracer("drizzle-orm",q7);return k7((r,A)=>A.startActiveSpan(D,(f)=>{try{return u(f)}catch(w){throw f.setStatus({code:r.SpanStatusCode.ERROR,message:w instanceof Error?w.message:"Unknown error"}),w}finally{f.end()}}),K3,h3)}}});var nD;var kr=W(()=>{nD=Symbol.for("drizzle:ViewBaseConfig")});function dr(D){return D[_u]}function Y0(D){return`${D[cA]??"public"}.${D[_u]}`}var cA,tA,T7,N3,Q3,u1,v7,QC,V;var cD=W(()=>{l();a2();cA=Symbol.for("drizzle:Schema"),tA=Symbol.for("drizzle:Columns"),T7=Symbol.for("drizzle:ExtraConfigColumns"),N3=Symbol.for("drizzle:OriginalName"),Q3=Symbol.for("drizzle:BaseName"),u1=Symbol.for("drizzle:IsAlias"),v7=Symbol.for("drizzle:ExtraConfigBuilder"),QC=Symbol.for("drizzle:IsDrizzleTable");V=class V{static[X]="Table";static Symbol={Name:_u,Schema:cA,OriginalName:N3,Columns:tA,ExtraConfigColumns:T7,BaseName:Q3,IsAlias:u1,ExtraConfigBuilder:v7};[_u];[N3];[cA];[tA];[T7];[Q3];[u1]=!1;[QC]=!0;[v7]=void 0;constructor(D,u,r){this[_u]=this[N3]=D,this[cA]=u,this[Q3]=r}}});function L3(D){return D!==null&&D!==void 0&&typeof D.getSQL==="function"}function LC(D){let u={sql:"",params:[]};for(let r of D)if(u.sql+=r.sql,u.params.push(...r.params),r.typings?.length){if(!u.typings)u.typings=[];u.typings.push(...r.typings)}return u}function s7(D){return typeof D==="object"&&D!==null&&"mapToDriverValue"in D&&typeof D.mapToDriverValue==="function"}function C(D,...u){let r=[];if(u.length>0||D.length>0&&D[0]!=="")r.push(new VD(D[0]));for(let[A,f]of u.entries())r.push(f,new VD(D[A+1]));return new b(r)}function r1(D,u){return D.map((r)=>{if(Y(r,yr)){if(!(r.name in u))throw Error(`No value for placeholder "${r.name}" was provided`);return u[r.name]}if(Y(r,Ru)&&Y(r.value,yr)){if(!(r.value.name in u))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(u[r.value.name])}return r})}var VD,b,xA,Z7,o7,Uz,Ru,yr,qC,Gu;var oD=W(()=>{l();L7();hu();j7();kr();Ku();cD();VD=class VD{static[X]="StringChunk";value;constructor(D){this.value=Array.isArray(D)?D:[D]}getSQL(){return new b([this])}};b=class b{constructor(D){this.queryChunks=D;for(let u of D)if(Y(u,V)){let r=u[V.Symbol.Schema];this.usedTables.push(r===void 0?u[V.Symbol.Name]:r+"."+u[V.Symbol.Name])}}static[X]="SQL";decoder=Z7;shouldInlineParams=!1;usedTables=[];append(D){return this.queryChunks.push(...D.queryChunks),this}toQuery(D){return z7.startActiveSpan("drizzle.buildSQL",(u)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,D);return u?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(D,u){let r=Object.assign({},u,{inlineParams:u.inlineParams||this.shouldInlineParams,paramStartIndex:u.paramStartIndex||{value:0}}),{casing:A,escapeName:f,escapeParam:w,prepareTyping:F,inlineParams:E,paramStartIndex:$}=r;return LC(D.map((g)=>{if(Y(g,VD))return{sql:g.value.join(""),params:[]};if(Y(g,xA))return{sql:f(g.value),params:[]};if(g===void 0)return{sql:"",params:[]};if(Array.isArray(g)){let R=[new VD("(")];for(let[S,B]of g.entries())if(R.push(B),S<g.length-1)R.push(new VD(", "));return R.push(new VD(")")),this.buildQueryFromSourceParams(R,r)}if(Y(g,b))return this.buildQueryFromSourceParams(g.queryChunks,{...r,inlineParams:E||g.shouldInlineParams});if(Y(g,V)){let R=g[V.Symbol.Schema],S=g[V.Symbol.Name];return{sql:R===void 0||g[u1]?f(S):f(R)+"."+f(S),params:[]}}if(Y(g,wD)){let R=A.getColumnCasing(g);if(u.invokeSource==="indexes")return{sql:f(R),params:[]};let S=g.table[V.Symbol.Schema];return{sql:g.table[u1]||S===void 0?f(g.table[V.Symbol.Name])+"."+f(R):f(S)+"."+f(g.table[V.Symbol.Name])+"."+f(R),params:[]}}if(Y(g,Gu)){let R=g[nD].schema,S=g[nD].name;return{sql:R===void 0||g[nD].isAlias?f(S):f(R)+"."+f(S),params:[]}}if(Y(g,Ru)){if(Y(g.value,yr))return{sql:w($.value++,g),params:[g],typings:["none"]};let R=g.value===null?null:g.encoder.mapToDriverValue(g.value);if(Y(R,b))return this.buildQueryFromSourceParams([R],r);if(E)return{sql:this.mapInlineParam(R,r),params:[]};let S=["none"];if(F)S=[F(g.encoder)];return{sql:w($.value++,R),params:[R],typings:S}}if(Y(g,yr))return{sql:w($.value++,g),params:[g],typings:["none"]};if(Y(g,b.Aliased)&&g.fieldAlias!==void 0)return{sql:f(g.fieldAlias),params:[]};if(Y(g,iD)){if(g._.isWith)return{sql:f(g._.alias),params:[]};return this.buildQueryFromSourceParams([new VD("("),g._.sql,new VD(") "),new xA(g._.alias)],r)}if(Q7(g)){if(g.schema)return{sql:f(g.schema)+"."+f(g.enumName),params:[]};return{sql:f(g.enumName),params:[]}}if(L3(g)){if(g.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([g.getSQL()],r);return this.buildQueryFromSourceParams([new VD("("),g.getSQL(),new VD(")")],r)}if(E)return{sql:this.mapInlineParam(g,r),params:[]};return{sql:w($.value++,g),params:[g],typings:["none"]}}))}mapInlineParam(D,{escapeString:u}){if(D===null)return"null";if(typeof D==="number"||typeof D==="boolean")return D.toString();if(typeof D==="string")return u(D);if(typeof D==="object"){let r=D.toString();if(r==="[object Object]")return u(JSON.stringify(D));return u(r)}throw Error("Unexpected param value: "+D)}getSQL(){return this}as(D){if(D===void 0)return this;return new b.Aliased(this,D)}mapWith(D){return this.decoder=typeof D==="function"?{mapFromDriverValue:D}:D,this}inlineParams(){return this.shouldInlineParams=!0,this}if(D){return D?this:void 0}};xA=class xA{constructor(D){this.value=D}static[X]="Name";brand;getSQL(){return new b([this])}};Z7={mapFromDriverValue:(D)=>D},o7={mapToDriverValue:(D)=>D},Uz={...Z7,...o7};Ru=class Ru{constructor(D,u=o7){this.value=D,this.encoder=u}static[X]="Param";brand;getSQL(){return new b([this])}};((D)=>{function u(){return new b([])}D.empty=u;function r($){return new b($)}D.fromList=r;function A($){return new b([new VD($)])}D.raw=A;function f($,g){let R=[];for(let[S,B]of $.entries()){if(S>0&&g!==void 0)R.push(g);R.push(B)}return new b(R)}D.join=f;function w($){return new xA($)}D.identifier=w;function F($){return new yr($)}D.placeholder=F;function E($,g){return new Ru($,g)}D.param=E})(C||(C={}));((D)=>{class u{constructor(r,A){this.sql=r,this.fieldAlias=A}static[X]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new u(this.sql,this.fieldAlias)}}D.Aliased=u})(b||(b={}));yr=class yr{constructor(D){this.name=D}static[X]="Placeholder";getSQL(){return new b([this])}};qC=Symbol.for("drizzle:IsDrizzleView");Gu=class Gu{static[X]="View";[nD];[qC]=!0;constructor({name:D,schema:u,selectedFields:r,query:A}){this[nD]={name:D,originalName:D,schema:u,selectedFields:r,query:A,isExisting:!A,isAlias:!1}}getSQL(){return new b([this])}};wD.prototype.getSQL=function(){return new b([this])};V.prototype.getSQL=function(){return new b([this])};iD.prototype.getSQL=function(){return new b([this])}});function mA(D,u){return new Proxy(D,new A1(u,!1))}function Ar(D,u){return new Proxy(D,new t0(new Proxy(D.table,new A1(u,!1))))}function q3(D,u){return new b.Aliased(f1(D.sql,u),D.fieldAlias)}function f1(D,u){return C.join(D.queryChunks.map((r)=>{if(Y(r,wD))return Ar(r,u);if(Y(r,b))return f1(r,u);if(Y(r,b.Aliased))return q3(r,u);return r}))}var t0,A1;var pA=W(()=>{Ku();l();oD();cD();kr();t0=class t0{constructor(D){this.table=D}static[X]="ColumnAliasProxyHandler";get(D,u){if(u==="table")return this.table;return D[u]}};A1=class A1{constructor(D,u){this.alias=D,this.replaceOriginalName=u}static[X]="TableAliasProxyHandler";get(D,u){if(u===V.Symbol.IsAlias)return!0;if(u===V.Symbol.Name)return this.alias;if(this.replaceOriginalName&&u===V.Symbol.OriginalName)return this.alias;if(u===nD)return{...D[nD],name:this.alias,isAlias:!0};if(u===V.Symbol.Columns){let A=D[V.Symbol.Columns];if(!A)return A;let f={};return Object.keys(A).map((w)=>{f[w]=new Proxy(A[w],new t0(new Proxy(D,this)))}),f}let r=D[u];if(Y(r,wD))return new Proxy(r,new t0(new Proxy(D,this)));return r}}});var x0,Ir,b3;var aA=W(()=>{l();x0=class x0 extends Error{static[X]="DrizzleError";constructor({message:D,cause:u}){super(D);this.name="DrizzleError",this.cause=u}};Ir=class Ir extends Error{constructor(D,u,r){super(`Failed query: ${D}
4
- params: ${u}`);if(this.query=D,this.params=u,this.cause=r,Error.captureStackTrace(this,Ir),r)this.cause=r}};b3=class b3 extends x0{static[X]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var d7,z3,j3;var eA=W(()=>{l();d7=class d7{static[X]="ConsoleLogWriter";write(D){console.log(D)}};z3=class z3{static[X]="DefaultLogger";writer;constructor(D){this.writer=D?.writer??new d7}logQuery(D,u){let r=u.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),A=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${D}${A}`)}};j3=class j3{static[X]="NoopLogger";logQuery(){}}});var mD;var Vr=W(()=>{l();mD=class mD{static[X]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(D){return this.then(void 0,D)}finally(D){return this.then((u)=>{return D?.(),u},(u)=>{throw D?.(),u})}then(D,u){return this.execute().then(D,u)}}});function T3(D,u,r){let A={},f=D.reduce((w,{path:F,field:E},$)=>{let g;if(Y(E,wD))g=E;else if(Y(E,b))g=E.decoder;else g=E.sql.decoder;let R=w;for(let[S,B]of F.entries())if(S<F.length-1){if(!(B in R))R[B]={};R=R[B]}else{let J=u[$],H=R[B]=J===null?null:g.mapFromDriverValue(J);if(r&&Y(E,wD)&&F.length===2){let G=F[0];if(!(G in A))A[G]=H===null?dr(E.table):!1;else if(typeof A[G]==="string"&&A[G]!==dr(E.table))A[G]=!1}}return w},{});if(r&&Object.keys(A).length>0){for(let[w,F]of Object.entries(A))if(typeof F==="string"&&!r[F])f[w]=null}return f}function Cu(D,u){return Object.entries(D).reduce((r,[A,f])=>{if(typeof A!=="string")return r;let w=u?[...u,A]:[A];if(Y(f,wD)||Y(f,b)||Y(f,b.Aliased))r.push({path:w,field:f});else if(Y(f,V))r.push(...Cu(f[V.Symbol.Columns],w));else r.push(...Cu(f,w));return r},[])}function F1(D,u){let r=Object.keys(D),A=Object.keys(u);if(r.length!==A.length)return!1;for(let[f,w]of r.entries())if(w!==A[f])return!1;return!0}function D8(D,u){let r=Object.entries(u).filter(([,A])=>A!==void 0).map(([A,f])=>{if(Y(f,b)||Y(f,wD))return[A,f];else return[A,new Ru(f,D[V.Symbol.Columns][A])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function y7(D,u){for(let r of u)for(let A of Object.getOwnPropertyNames(r.prototype)){if(A==="constructor")continue;Object.defineProperty(D.prototype,A,Object.getOwnPropertyDescriptor(r.prototype,A)||Object.create(null))}}function l7(D){return D[V.Symbol.Columns]}function w1(D){return Y(D,iD)?D._.alias:Y(D,Gu)?D[nD].name:Y(D,b)?void 0:D[V.Symbol.IsAlias]?D[V.Symbol.Name]:D[V.Symbol.BaseName]}function fr(D,u){return{name:typeof D==="string"&&D.length>0?D:"",config:typeof D==="object"?D:u}}function c7(D){if(typeof D!=="object"||D===null)return!1;if(D.constructor.name!=="Object")return!1;if("logger"in D){let u=typeof D.logger;if(u!=="boolean"&&(u!=="object"||typeof D.logger.logQuery!=="function")&&u!=="undefined")return!1;return!0}if("schema"in D){let u=typeof D.schema;if(u!=="object"&&u!=="undefined")return!1;return!0}if("casing"in D){let u=typeof D.casing;if(u!=="string"&&u!=="undefined")return!1;return!0}if("mode"in D){if(D.mode!=="default"||D.mode!=="planetscale"||D.mode!==void 0)return!1;return!0}if("connection"in D){let u=typeof D.connection;if(u!=="string"&&u!=="object"&&u!=="undefined")return!1;return!0}if("client"in D){let u=typeof D.client;if(u!=="object"&&u!=="function"&&u!=="undefined")return!1;return!0}if(Object.keys(D).length===0)return!0;return!1}var v3;var uu=W(()=>{Ku();l();oD();hu();cD();kr();v3=typeof TextDecoder>"u"?null:new TextDecoder});var t7,x7,s3;var m7=W(()=>{l();cD();t7=Symbol.for("drizzle:PgInlineForeignKeys"),x7=Symbol.for("drizzle:EnableRLS");s3=class s3 extends V{static[X]="PgTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:t7,EnableRLS:x7});[t7]=[];[x7]=!1;[V.Symbol.ExtraConfigBuilder]=void 0;[V.Symbol.ExtraConfigColumns]={}}});var Z3,p7;var a7=W(()=>{l();m7();Z3=class Z3{static[X]="PgPrimaryKeyBuilder";columns;name;constructor(D,u){this.columns=D,this.name=u}build(D){return new p7(D,this.columns,this.name)}};p7=class p7{constructor(D,u,r){this.table=D,this.columns=u,this.name=r}static[X]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[s3.Symbol.Name]}_${this.columns.map((D)=>D.name).join("_")}_pk`}}});function ru(D,u){if(s7(u)&&!L3(D)&&!Y(D,Ru)&&!Y(D,yr)&&!Y(D,wD)&&!Y(D,V)&&!Y(D,Gu))return new Ru(D,u);return D}function Kr(...D){let u=D.filter((r)=>r!==void 0);if(u.length===0)return;if(u.length===1)return new b(u);return new b([new VD("("),C.join(u,new VD(" and ")),new VD(")")])}function D5(...D){let u=D.filter((r)=>r!==void 0);if(u.length===0)return;if(u.length===1)return new b(u);return new b([new VD("("),C.join(u,new VD(" or ")),new VD(")")])}function u5(D){return C`not ${D}`}function w5(D,u){if(Array.isArray(u)){if(u.length===0)return C`false`;return C`${D} in ${u.map((r)=>ru(r,D))}`}return C`${D} in ${ru(u,D)}`}function $5(D,u){if(Array.isArray(u)){if(u.length===0)return C`true`;return C`${D} not in ${u.map((r)=>ru(r,D))}`}return C`${D} not in ${ru(u,D)}`}function E5(D){return C`${D} is null`}function g5(D){return C`${D} is not null`}function _5(D){return C`exists ${D}`}function R5(D){return C`not exists ${D}`}function S5(D,u,r){return C`${D} between ${ru(u,D)} and ${ru(r,D)}`}function B5(D,u,r){return C`${D} not between ${ru(u,D)} and ${ru(r,D)}`}function J5(D,u){return C`${D} like ${u}`}function W5(D,u){return C`${D} not like ${u}`}function G5(D,u){return C`${D} ilike ${u}`}function C5(D,u){return C`${D} not ilike ${u}`}var d=(D,u)=>{return C`${D} = ${ru(u,D)}`},e7=(D,u)=>{return C`${D} <> ${ru(u,D)}`},r5=(D,u)=>{return C`${D} > ${ru(u,D)}`},A5=(D,u)=>{return C`${D} >= ${ru(u,D)}`},f5=(D,u)=>{return C`${D} < ${ru(u,D)}`},F5=(D,u)=>{return C`${D} <= ${ru(u,D)}`};var H5=W(()=>{Ku();l();cD();oD()});function n5(D){return C`${D} asc`}function GD(D){return C`${D} desc`}var U5=W(()=>{oD()});var o3=W(()=>{H5();U5()});function Y5(){return{and:Kr,between:S5,eq:d,exists:_5,gt:r5,gte:A5,ilike:G5,inArray:w5,isNull:E5,isNotNull:g5,like:J5,lt:f5,lte:F5,ne:e7,not:u5,notBetween:B5,notExists:R5,notLike:W5,notIlike:C5,notInArray:$5,or:D5,sql:C}}function M5(){return{sql:C,asc:n5,desc:GD}}function O5(D,u){if(Object.keys(D).length===1&&"default"in D&&!Y(D.default,V))D=D.default;let r={},A={},f={};for(let[w,F]of Object.entries(D))if(Y(F,V)){let E=Y0(F),$=A[E];r[E]=w,f[w]={tsName:w,dbName:F[V.Symbol.Name],schema:F[V.Symbol.Schema],columns:F[V.Symbol.Columns],relations:$?.relations??{},primaryKey:$?.primaryKey??[]};for(let R of Object.values(F[V.Symbol.Columns]))if(R.primary)f[w].primaryKey.push(R);let g=F[V.Symbol.ExtraConfigBuilder]?.(F[V.Symbol.ExtraConfigColumns]);if(g){for(let R of Object.values(g))if(Y(R,Z3))f[w].primaryKey.push(...R.columns)}}else if(Y(F,X5)){let E=Y0(F.table),$=r[E],g=F.config(u(F.table)),R;for(let[S,B]of Object.entries(g))if($){let J=f[$];if(J.relations[S]=B,R)J.primaryKey.push(...R)}else{if(!(E in A))A[E]={relations:{},primaryKey:R};A[E].relations[S]=B}}return{tables:f,tableNamesMap:r}}function bC(D){return function(r,A){return new lr(D,r,A,A?.fields.reduce((f,w)=>f&&w.notNull,!0)??!1)}}function zC(D){return function(r,A){return new $1(D,r,A)}}function P5(D,u,r){if(Y(r,lr)&&r.config)return{fields:r.config.fields,references:r.config.references};let A=u[Y0(r.referencedTable)];if(!A)throw Error(`Table "${r.referencedTable[V.Symbol.Name]}" not found in schema`);let f=D[A];if(!f)throw Error(`Table "${A}" not found in schema`);let w=r.sourceTable,F=u[Y0(w)];if(!F)throw Error(`Table "${w[V.Symbol.Name]}" not found in schema`);let E=[];for(let $ of Object.values(f.relations))if(r.relationName&&r!==$&&$.relationName===r.relationName||!r.relationName&&$.referencedTable===r.sourceTable)E.push($);if(E.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${A}"`):Error(`There are multiple relations between "${A}" and "${r.sourceTable[V.Symbol.Name]}". Please specify relation name`);if(E[0]&&Y(E[0],lr)&&E[0].config)return{fields:E[0].config.references,references:E[0].config.fields};throw Error(`There is not enough information to infer relation "${F}.${r.fieldName}"`)}function i5(D){return{one:bC(D),many:zC(D)}}function u8(D,u,r,A,f=(w)=>w){let w={};for(let[F,E]of A.entries())if(E.isJson){let $=u.relations[E.tsKey],g=r[F],R=typeof g==="string"?JSON.parse(g):g;w[E.tsKey]=Y($,lr)?R&&u8(D,D[E.relationTableTsKey],R,E.selection,f):R.map((S)=>u8(D,D[E.relationTableTsKey],S,E.selection,f))}else{let $=f(r[F]),g=E.field,R;if(Y(g,wD))R=g;else if(Y(g,b))R=g.decoder;else R=g.sql.decoder;w[E.tsKey]=$===null?null:R.mapFromDriverValue($)}return w}var d3,X5,lr,$1;var E1=W(()=>{cD();Ku();l();a7();o3();oD();d3=class d3{constructor(D,u,r){this.sourceTable=D,this.referencedTable=u,this.relationName=r,this.referencedTableName=u[V.Symbol.Name]}static[X]="Relation";referencedTableName;fieldName};X5=class X5{constructor(D,u){this.table=D,this.config=u}static[X]="Relations"};lr=class lr extends d3{constructor(D,u,r,A){super(D,u,r?.relationName);this.config=r,this.isNullable=A}static[X]="One";withFieldName(D){let u=new lr(this.sourceTable,this.referencedTable,this.config,this.isNullable);return u.fieldName=D,u}};$1=class $1 extends d3{constructor(D,u,r){super(D,u,r?.relationName);this.config=r}static[X]="Many";withFieldName(D){let u=new $1(this.sourceTable,this.referencedTable,this.config);return u.fieldName=D,u}}});var k5=()=>{};var I5=()=>{};var V5=W(()=>{k5();I5()});var y3=W(()=>{o3();V5();oD()});var K5=W(()=>{pA();V3();Ku();l();aA();eA();Vr();E1();y3();hu();cD();uu();kr()});var kD;var m0=W(()=>{pA();Ku();l();oD();hu();kr();kD=class kD{static[X]="SelectionProxyHandler";config;constructor(D){this.config={...D}}get(D,u){if(u==="_")return{...D._,selectedFields:new Proxy(D._.selectedFields,this)};if(u===nD)return{...D[nD],selectedFields:new Proxy(D[nD].selectedFields,this)};if(typeof u==="symbol")return D[u];let A=(Y(D,iD)?D._.selectedFields:Y(D,Gu)?D[nD].selectedFields:D)[u];if(Y(A,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!A.isSelectionField)return A.sql;let f=A.clone();return f.isSelectionField=!0,f}if(Y(A,b)){if(this.config.sqlBehavior==="sql")return A;throw Error(`You tried to reference "${u}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(Y(A,wD)){if(this.config.alias)return new Proxy(A,new t0(new Proxy(A.table,new A1(this.config.alias,this.config.replaceOriginalName??!1))));return A}if(typeof A!=="object"||A===null)return A;return new Proxy(A,new kD(this.config))}}});var l3,h5;var c3=W(()=>{l();a2();l3=class l3{static[X]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(D,u){if(this.reference=()=>{let{name:r,columns:A,foreignColumns:f}=D();return{name:r,columns:A,foreignTable:f[0].table,foreignColumns:f}},u)this._onUpdate=u.onUpdate,this._onDelete=u.onDelete}onUpdate(D){return this._onUpdate=D,this}onDelete(D){return this._onDelete=D,this}build(D){return new h5(D,this)}};h5=class h5{constructor(D,u){this.table=D,this.reference=u.reference,this.onUpdate=u._onUpdate,this.onDelete=u._onDelete}static[X]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:D,columns:u,foreignColumns:r}=this.reference(),A=u.map((F)=>F.name),f=r.map((F)=>F.name),w=[this.table[_u],...A,r[0].table[_u],...f];return D??`${w.join("_")}_fk`}}});function N5(D,u){return`${D[_u]}_${u.join("_")}_unique`}var t3=W(()=>{a2()});var LD,XD;var cr=W(()=>{V3();Ku();l();c3();t3();LD=class LD extends I3{static[X]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(D,u={}){return this.foreignKeyConfigs.push({ref:D,actions:u}),this}unique(D){return this.config.isUnique=!0,this.config.uniqueName=D,this}generatedAlwaysAs(D,u){return this.config.generated={as:D,type:"always",mode:u?.mode??"virtual"},this}buildForeignKeys(D,u){return this.foreignKeyConfigs.map(({ref:r,actions:A})=>{return((f,w)=>{let F=new l3(()=>{let E=f();return{columns:[D],foreignColumns:[E]}});if(w.onUpdate)F.onUpdate(w.onUpdate);if(w.onDelete)F.onDelete(w.onDelete);return F.build(u)})(r,A)})}};XD=class XD extends wD{constructor(D,u){if(!u.uniqueName)u.uniqueName=N5(D,[u.name]);super(D,u);this.table=D}static[X]="SQLiteColumn"}});function T5(D,u){let{name:r,config:A}=fr(D,u);if(A?.mode==="json")return new q5(r);if(A?.mode==="bigint")return new Q5(r);return new z5(r)}var Q5,L5,q5,b5,z5,j5;var x3=W(()=>{l();uu();cr();Q5=class Q5 extends LD{static[X]="SQLiteBigIntBuilder";constructor(D){super(D,"bigint","SQLiteBigInt")}build(D){return new L5(D,this.config)}};L5=class L5 extends XD{static[X]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(D){if(typeof Buffer<"u"&&Buffer.from){let u=Buffer.isBuffer(D)?D:D instanceof ArrayBuffer?Buffer.from(D):D.buffer?Buffer.from(D.buffer,D.byteOffset,D.byteLength):Buffer.from(D);return BigInt(u.toString("utf8"))}return BigInt(v3.decode(D))}mapToDriverValue(D){return Buffer.from(D.toString())}};q5=class q5 extends LD{static[X]="SQLiteBlobJsonBuilder";constructor(D){super(D,"json","SQLiteBlobJson")}build(D){return new b5(D,this.config)}};b5=class b5 extends XD{static[X]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(D){if(typeof Buffer<"u"&&Buffer.from){let u=Buffer.isBuffer(D)?D:D instanceof ArrayBuffer?Buffer.from(D):D.buffer?Buffer.from(D.buffer,D.byteOffset,D.byteLength):Buffer.from(D);return JSON.parse(u.toString("utf8"))}return JSON.parse(v3.decode(D))}mapToDriverValue(D){return Buffer.from(JSON.stringify(D))}};z5=class z5 extends LD{static[X]="SQLiteBlobBufferBuilder";constructor(D){super(D,"buffer","SQLiteBlobBuffer")}build(D){return new j5(D,this.config)}};j5=class j5 extends XD{static[X]="SQLiteBlobBuffer";mapFromDriverValue(D){if(Buffer.isBuffer(D))return D;return Buffer.from(D)}getSQLType(){return"blob"}}});function Z5(D){return(u,r)=>{let{name:A,config:f}=fr(u,r);return new v5(A,f,D)}}var v5,s5;var m3=W(()=>{l();uu();cr();v5=class v5 extends LD{static[X]="SQLiteCustomColumnBuilder";constructor(D,u,r){super(D,"custom","SQLiteCustomColumn");this.config.fieldConfig=u,this.config.customTypeParams=r}build(D){return new s5(D,this.config)}};s5=class s5 extends XD{static[X]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(D,u){super(D,u);this.sqlName=u.customTypeParams.dataType(u.fieldConfig),this.mapTo=u.customTypeParams.toDriver,this.mapFrom=u.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(D){return typeof this.mapFrom==="function"?this.mapFrom(D):D}mapToDriverValue(D){return typeof this.mapTo==="function"?this.mapTo(D):D}}});function Hu(D,u){let{name:r,config:A}=fr(D,u);if(A?.mode==="timestamp"||A?.mode==="timestamp_ms")return new y5(r,A.mode);if(A?.mode==="boolean")return new c5(r,A.mode);return new o5(r)}var r8,A8,o5,d5,y5,l5,c5,t5;var p3=W(()=>{l();oD();uu();cr();r8=class r8 extends LD{static[X]="SQLiteBaseIntegerBuilder";constructor(D,u,r){super(D,u,r);this.config.autoIncrement=!1}primaryKey(D){if(D?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};A8=class A8 extends XD{static[X]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};o5=class o5 extends r8{static[X]="SQLiteIntegerBuilder";constructor(D){super(D,"number","SQLiteInteger")}build(D){return new d5(D,this.config)}};d5=class d5 extends A8{static[X]="SQLiteInteger"};y5=class y5 extends r8{static[X]="SQLiteTimestampBuilder";constructor(D,u){super(D,"date","SQLiteTimestamp");this.config.mode=u}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(D){return new l5(D,this.config)}};l5=class l5 extends A8{static[X]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(D){if(this.config.mode==="timestamp")return new Date(D*1000);return new Date(D)}mapToDriverValue(D){let u=D.getTime();if(this.config.mode==="timestamp")return Math.floor(u/1000);return u}};c5=class c5 extends r8{static[X]="SQLiteBooleanBuilder";constructor(D,u){super(D,"boolean","SQLiteBoolean");this.config.mode=u}build(D){return new t5(D,this.config)}};t5=class t5 extends A8{static[X]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(D){return Number(D)===1}mapToDriverValue(D){return D?1:0}}});function u4(D,u){let{name:r,config:A}=fr(D,u),f=A?.mode;return f==="number"?new p5(r):f==="bigint"?new e5(r):new x5(r)}var x5,m5,p5,a5,e5,D4;var a3=W(()=>{l();uu();cr();x5=class x5 extends LD{static[X]="SQLiteNumericBuilder";constructor(D){super(D,"string","SQLiteNumeric")}build(D){return new m5(D,this.config)}};m5=class m5 extends XD{static[X]="SQLiteNumeric";mapFromDriverValue(D){if(typeof D==="string")return D;return String(D)}getSQLType(){return"numeric"}};p5=class p5 extends LD{static[X]="SQLiteNumericNumberBuilder";constructor(D){super(D,"number","SQLiteNumericNumber")}build(D){return new a5(D,this.config)}};a5=class a5 extends XD{static[X]="SQLiteNumericNumber";mapFromDriverValue(D){if(typeof D==="number")return D;return Number(D)}mapToDriverValue=String;getSQLType(){return"numeric"}};e5=class e5 extends LD{static[X]="SQLiteNumericBigIntBuilder";constructor(D){super(D,"bigint","SQLiteNumericBigInt")}build(D){return new D4(D,this.config)}};D4=class D4 extends XD{static[X]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function f4(D){return new r4(D??"")}var r4,A4;var e3=W(()=>{l();cr();r4=class r4 extends LD{static[X]="SQLiteRealBuilder";constructor(D){super(D,"number","SQLiteReal")}build(D){return new A4(D,this.config)}};A4=class A4 extends XD{static[X]="SQLiteReal";getSQLType(){return"real"}}});function n(D,u={}){let{name:r,config:A}=fr(D,u);if(A.mode==="json")return new $4(r);return new F4(r,A)}var F4,w4,$4,E4;var DF=W(()=>{l();uu();cr();F4=class F4 extends LD{static[X]="SQLiteTextBuilder";constructor(D,u){super(D,"string","SQLiteText");this.config.enumValues=u.enum,this.config.length=u.length}build(D){return new w4(D,this.config)}};w4=class w4 extends XD{static[X]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(D,u){super(D,u)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};$4=class $4 extends LD{static[X]="SQLiteTextJsonBuilder";constructor(D){super(D,"json","SQLiteTextJson")}build(D){return new E4(D,this.config)}};E4=class E4 extends XD{static[X]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(D){return JSON.parse(D)}mapToDriverValue(D){return JSON.stringify(D)}}});function g4(){return{blob:T5,customType:Z5,integer:Hu,numeric:u4,real:f4,text:n}}var _4=W(()=>{x3();m3();p3();a3();e3();DF()});function jC(D,u,r,A,f=D){let w=new qD(D,A,f),F=typeof u==="function"?u(g4()):u,E=Object.fromEntries(Object.entries(F).map(([g,R])=>{let S=R;S.setName(g);let B=S.build(w);return w[uF].push(...S.buildForeignKeys(B,w)),[g,B]})),$=Object.assign(w,E);if($[V.Symbol.Columns]=E,$[V.Symbol.ExtraConfigColumns]=E,r)$[qD.Symbol.ExtraConfigBuilder]=r;return $}var uF,qD,bD=(D,u,r)=>{return jC(D,u,r)};var M0=W(()=>{l();cD();_4();uF=Symbol.for("drizzle:SQLiteInlineForeignKeys");qD=class qD extends V{static[X]="SQLiteTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:uF});[V.Symbol.Columns];[uF]=[];[V.Symbol.ExtraConfigBuilder]=void 0}});var R4=()=>{};function uD(D){return new rF(D,!1)}function p0(D){return new rF(D,!0)}var rF,S4,B4;var J4=W(()=>{l();rF=class rF{constructor(D,u){this.name=D,this.unique=u}static[X]="SQLiteIndexBuilderOn";on(...D){return new S4(this.name,D,this.unique)}};S4=class S4{static[X]="SQLiteIndexBuilder";config;constructor(D,u,r){this.config={name:D,columns:u,unique:r,where:void 0}}where(D){return this.config.where=D,this}build(D){return new B4(this.config,D)}};B4=class B4{static[X]="SQLiteIndex";config;constructor(D,u){this.config={...D,table:u}}}});var W4=()=>{};function Nu(D){if(Y(D,qD))return[`${D[V.Symbol.BaseName]}`];if(Y(D,iD))return D._.usedTables??[];if(Y(D,b))return D.usedTables??[];return[]}var a0=W(()=>{l();oD();hu();cD();M0()});var f8;var G4=W(()=>{l();Vr();m0();M0();cD();uu();a0();f8=class f8 extends mD{constructor(D,u,r,A){super();this.table=D,this.session=u,this.dialect=r,this.config={table:D,withList:A}}static[X]="SQLiteDelete";config;where(D){return this.config.where=D,this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.table[V.Symbol.Columns],new kD({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];this.config.orderBy=r}else{let u=D;this.config.orderBy=u}return this}limit(D){return this.config.limit=D,this}returning(D=this.table[qD.Symbol.Columns]){return this.config.returning=Cu(D),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:Nu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(D){return this._prepare().execute(D)}$dynamic(){return this}}});function TC(D){return(D.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function vC(D){return(D.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,A,f)=>{let w=f===0?A.toLowerCase():`${A[0].toUpperCase()}${A.slice(1)}`;return r+w},"")}function sC(D){return D}var AF;var C4=W(()=>{l();cD();AF=class AF{static[X]="CasingCache";cache={};cachedTables={};convert;constructor(D){this.convert=D==="snake_case"?TC:D==="camelCase"?vC:sC}getColumnCasing(D){if(!D.keyAsName)return D.name;let u=D.table[V.Symbol.Schema]??"public",r=D.table[V.Symbol.OriginalName],A=`${u}.${r}.${D.name}`;if(!this.cache[A])this.cacheTable(D.table);return this.cache[A]}cacheTable(D){let u=D[V.Symbol.Schema]??"public",r=D[V.Symbol.OriginalName],A=`${u}.${r}`;if(!this.cachedTables[A]){for(let f of Object.values(D[V.Symbol.Columns])){let w=`${A}.${f.name}`;this.cache[w]=this.convert(f.name)}this.cachedTables[A]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var fF=W(()=>{x3();cr();m3();p3();a3();e3();DF()});var O0;var F8=W(()=>{l();oD();O0=class O0 extends Gu{static[X]="SQLiteViewBase"}});var g1,_1;var w8=W(()=>{pA();C4();Ku();l();aA();E1();y3();oD();fF();M0();hu();cD();uu();kr();F8();g1=class g1{static[X]="SQLiteDialect";casing;constructor(D){this.casing=new AF(D?.casing)}escapeName(D){return`"${D}"`}escapeParam(D){return"?"}escapeString(D){return`'${D.replace(/'/g,"''")}'`}buildWithCTE(D){if(!D?.length)return;let u=[C`with `];for(let[r,A]of D.entries())if(u.push(C`${C.identifier(A._.alias)} as (${A._.sql})`),r<D.length-1)u.push(C`, `);return u.push(C` `),C.join(u)}buildDeleteQuery({table:D,where:u,returning:r,withList:A,limit:f,orderBy:w}){let F=this.buildWithCTE(A),E=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,$=u?C` where ${u}`:void 0,g=this.buildOrderBy(w),R=this.buildLimit(f);return C`${F}delete from ${D}${$}${E}${g}${R}`}buildUpdateSet(D,u){let r=D[V.Symbol.Columns],A=Object.keys(r).filter((w)=>u[w]!==void 0||r[w]?.onUpdateFn!==void 0),f=A.length;return C.join(A.flatMap((w,F)=>{let E=r[w],$=u[w]??C.param(E.onUpdateFn(),E),g=C`${C.identifier(this.casing.getColumnCasing(E))} = ${$}`;if(F<f-1)return[g,C.raw(", ")];return[g]}))}buildUpdateQuery({table:D,set:u,where:r,returning:A,withList:f,joins:w,from:F,limit:E,orderBy:$}){let g=this.buildWithCTE(f),R=this.buildUpdateSet(D,u),S=F&&C.join([C.raw(" from "),this.buildFromTable(F)]),B=this.buildJoins(w),J=A?C` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,H=r?C` where ${r}`:void 0,G=this.buildOrderBy($),U=this.buildLimit(E);return C`${g}update ${D} set ${R}${S}${B}${H}${J}${G}${U}`}buildSelection(D,{isSingleTable:u=!1}={}){let r=D.length,A=D.flatMap(({field:f},w)=>{let F=[];if(Y(f,b.Aliased)&&f.isSelectionField)F.push(C.identifier(f.fieldAlias));else if(Y(f,b.Aliased)||Y(f,b)){let E=Y(f,b.Aliased)?f.sql:f;if(u)F.push(new b(E.queryChunks.map(($)=>{if(Y($,wD))return C.identifier(this.casing.getColumnCasing($));return $})));else F.push(E);if(Y(f,b.Aliased))F.push(C` as ${C.identifier(f.fieldAlias)}`)}else if(Y(f,wD)){let E=f.table[V.Symbol.Name];if(f.columnType==="SQLiteNumericBigInt")if(u)F.push(C`cast(${C.identifier(this.casing.getColumnCasing(f))} as text)`);else F.push(C`cast(${C.identifier(E)}.${C.identifier(this.casing.getColumnCasing(f))} as text)`);else if(u)F.push(C.identifier(this.casing.getColumnCasing(f)));else F.push(C`${C.identifier(E)}.${C.identifier(this.casing.getColumnCasing(f))}`)}if(w<r-1)F.push(C`, `);return F});return C.join(A)}buildJoins(D){if(!D||D.length===0)return;let u=[];if(D)for(let[r,A]of D.entries()){if(r===0)u.push(C` `);let f=A.table,w=A.on?C` on ${A.on}`:void 0;if(Y(f,qD)){let F=f[qD.Symbol.Name],E=f[qD.Symbol.Schema],$=f[qD.Symbol.OriginalName],g=F===$?void 0:A.alias;u.push(C`${C.raw(A.joinType)} join ${E?C`${C.identifier(E)}.`:void 0}${C.identifier($)}${g&&C` ${C.identifier(g)}`}${w}`)}else u.push(C`${C.raw(A.joinType)} join ${f}${w}`);if(r<D.length-1)u.push(C` `)}return C.join(u)}buildLimit(D){return typeof D==="object"||typeof D==="number"&&D>=0?C` limit ${D}`:void 0}buildOrderBy(D){let u=[];if(D){for(let[r,A]of D.entries())if(u.push(A),r<D.length-1)u.push(C`, `)}return u.length>0?C` order by ${C.join(u)}`:void 0}buildFromTable(D){if(Y(D,V)&&D[V.Symbol.IsAlias])return C`${C`${C.identifier(D[V.Symbol.Schema]??"")}.`.if(D[V.Symbol.Schema])}${C.identifier(D[V.Symbol.OriginalName])} ${C.identifier(D[V.Symbol.Name])}`;return D}buildSelectQuery({withList:D,fields:u,fieldsFlat:r,where:A,having:f,table:w,joins:F,orderBy:E,groupBy:$,limit:g,offset:R,distinct:S,setOperators:B}){let J=r??Cu(u);for(let e of J)if(Y(e.field,wD)&&dr(e.field.table)!==(Y(w,iD)?w._.alias:Y(w,O0)?w[nD].name:Y(w,b)?void 0:dr(w))&&!((QD)=>F?.some(({alias:rr})=>rr===(QD[V.Symbol.IsAlias]?dr(QD):QD[V.Symbol.BaseName])))(e.field.table)){let QD=dr(e.field.table);throw Error(`Your "${e.path.join("->")}" field references a column "${QD}"."${e.field.name}", but the table "${QD}" is not part of the query! Did you forget to join it?`)}let H=!F||F.length===0,G=this.buildWithCTE(D),U=S?C` distinct`:void 0,O=this.buildSelection(J,{isSingleTable:H}),i=this.buildFromTable(w),k=this.buildJoins(F),z=A?C` where ${A}`:void 0,q=f?C` having ${f}`:void 0,M=[];if($){for(let[e,QD]of $.entries())if(M.push(QD),e<$.length-1)M.push(C`, `)}let s=M.length>0?C` group by ${C.join(M)}`:void 0,h=this.buildOrderBy(E),rD=this.buildLimit(g),_D=R?C` offset ${R}`:void 0,WD=C`${G}select${U} ${O} from ${i}${k}${z}${s}${q}${h}${rD}${_D}`;if(B.length>0)return this.buildSetOperations(WD,B);return WD}buildSetOperations(D,u){let[r,...A]=u;if(!r)throw Error("Cannot pass undefined values to any set operator");if(A.length===0)return this.buildSetOperationQuery({leftSelect:D,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:D,setOperator:r}),A)}buildSetOperationQuery({leftSelect:D,setOperator:{type:u,isAll:r,rightSelect:A,limit:f,orderBy:w,offset:F}}){let E=C`${D.getSQL()} `,$=C`${A.getSQL()}`,g;if(w&&w.length>0){let J=[];for(let H of w)if(Y(H,XD))J.push(C.identifier(H.name));else if(Y(H,b)){for(let G=0;G<H.queryChunks.length;G++){let U=H.queryChunks[G];if(Y(U,XD))H.queryChunks[G]=C.identifier(this.casing.getColumnCasing(U))}J.push(C`${H}`)}else J.push(C`${H}`);g=C` order by ${C.join(J,C`, `)}`}let R=typeof f==="object"||typeof f==="number"&&f>=0?C` limit ${f}`:void 0,S=C.raw(`${u} ${r?"all ":""}`),B=F?C` offset ${F}`:void 0;return C`${E}${S}${$}${g}${R}${B}`}buildInsertQuery({table:D,values:u,onConflict:r,returning:A,withList:f,select:w}){let F=[],E=D[V.Symbol.Columns],$=Object.entries(E).filter(([H,G])=>!G.shouldDisableInsert()),g=$.map(([,H])=>C.identifier(this.casing.getColumnCasing(H)));if(w){let H=u;if(Y(H,b))F.push(H);else F.push(H.getSQL())}else{let H=u;F.push(C.raw("values "));for(let[G,U]of H.entries()){let O=[];for(let[i,k]of $){let z=U[i];if(z===void 0||Y(z,Ru)&&z.value===void 0){let q;if(k.default!==null&&k.default!==void 0)q=Y(k.default,b)?k.default:C.param(k.default,k);else if(k.defaultFn!==void 0){let M=k.defaultFn();q=Y(M,b)?M:C.param(M,k)}else if(!k.default&&k.onUpdateFn!==void 0){let M=k.onUpdateFn();q=Y(M,b)?M:C.param(M,k)}else q=C`null`;O.push(q)}else O.push(z)}if(F.push(O),G<H.length-1)F.push(C`, `)}}let R=this.buildWithCTE(f),S=C.join(F),B=A?C` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,J=r?.length?C.join(r):void 0;return C`${R}insert into ${D} ${g} ${S}${J}${B}`}sqlToQuery(D,u){return D.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:u})}buildRelationalQuery({fullSchema:D,schema:u,tableNamesMap:r,table:A,tableConfig:f,queryConfig:w,tableAlias:F,nestedQueryRelation:E,joinOn:$}){let g=[],R,S,B=[],J,H=[];if(w===!0)g=Object.entries(f.columns).map(([O,i])=>({dbKey:i.name,tsKey:O,field:Ar(i,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let U=Object.fromEntries(Object.entries(f.columns).map(([M,s])=>[M,Ar(s,F)]));if(w.where){let M=typeof w.where==="function"?w.where(U,Y5()):w.where;J=M&&f1(M,F)}let O=[],i=[];if(w.columns){let M=!1;for(let[s,h]of Object.entries(w.columns)){if(h===void 0)continue;if(s in f.columns){if(!M&&h===!0)M=!0;i.push(s)}}if(i.length>0)i=M?i.filter((s)=>w.columns?.[s]===!0):Object.keys(f.columns).filter((s)=>!i.includes(s))}else i=Object.keys(f.columns);for(let M of i){let s=f.columns[M];O.push({tsKey:M,value:s})}let k=[];if(w.with)k=Object.entries(w.with).filter((M)=>!!M[1]).map(([M,s])=>({tsKey:M,queryConfig:s,relation:f.relations[M]}));let z;if(w.extras){z=typeof w.extras==="function"?w.extras(U,{sql:C}):w.extras;for(let[M,s]of Object.entries(z))O.push({tsKey:M,value:q3(s,F)})}for(let{tsKey:M,value:s}of O)g.push({dbKey:Y(s,b.Aliased)?s.fieldAlias:f.columns[M].name,tsKey:M,field:Y(s,wD)?Ar(s,F):s,relationTableTsKey:void 0,isJson:!1,selection:[]});let q=typeof w.orderBy==="function"?w.orderBy(U,M5()):w.orderBy??[];if(!Array.isArray(q))q=[q];B=q.map((M)=>{if(Y(M,wD))return Ar(M,F);return f1(M,F)}),R=w.limit,S=w.offset;for(let{tsKey:M,queryConfig:s,relation:h}of k){let rD=P5(u,r,h),_D=Y0(h.referencedTable),WD=r[_D],e=`${F}_${M}`,QD=Kr(...rD.fields.map((XC,YC)=>d(Ar(rD.references[YC],e),Ar(XC,F)))),rr=this.buildRelationalQuery({fullSchema:D,schema:u,tableNamesMap:r,table:D[WD],tableConfig:u[WD],queryConfig:Y(h,lr)?s===!0?{limit:1}:{...s,limit:1}:s,tableAlias:e,joinOn:QD,nestedQueryRelation:h}),UC=C`(${rr.sql})`.as(M);g.push({dbKey:M,tsKey:M,field:UC,relationTableTsKey:WD,isJson:!0,selection:rr.selection})}}if(g.length===0)throw new x0({message:`No fields selected for table "${f.tsName}" ("${F}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let G;if(J=Kr($,J),E){let U=C`json_array(${C.join(g.map(({field:k})=>Y(k,XD)?C.identifier(this.casing.getColumnCasing(k)):Y(k,b.Aliased)?k.sql:k),C`, `)})`;if(Y(E,$1))U=C`coalesce(json_group_array(${U}), json_array())`;let O=[{dbKey:"data",tsKey:"data",field:U.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:g}];if(R!==void 0||S!==void 0||B.length>0)G=this.buildSelectQuery({table:mA(A,F),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:J,limit:R,offset:S,orderBy:B,setOperators:[]}),J=void 0,R=void 0,S=void 0,B=void 0;else G=mA(A,F);G=this.buildSelectQuery({table:Y(G,qD)?G:new iD(G,{},F),fields:{},fieldsFlat:O.map(({field:k})=>({path:[],field:Y(k,wD)?Ar(k,F):k})),joins:H,where:J,limit:R,offset:S,orderBy:B,setOperators:[]})}else G=this.buildSelectQuery({table:mA(A,F),fields:{},fieldsFlat:g.map(({field:U})=>({path:[],field:Y(U,wD)?Ar(U,F):U})),joins:H,where:J,limit:R,offset:S,orderBy:B,setOperators:[]});return{tableTsKey:f.tsName,sql:G,selection:g}}};_1=class _1 extends g1{static[X]="SQLiteSyncDialect";migrate(D,u,r){let A=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",f=C`
5
- CREATE TABLE IF NOT EXISTS ${C.identifier(A)} (
3
+ var yG=Object.defineProperty;var L=(D,u)=>()=>(u||D((u={exports:{}}).exports,u),u.exports);var cG=(D)=>D;function tG(D,u){this[D]=cG.bind(null,u)}var t1=(D,u)=>{for(var r in u)yG(D,r,{get:u[r],enumerable:!0,configurable:!0,set:tG.bind(u,r)})};var W=(D,u)=>()=>(D&&(u=D(D=0)),u);var p1=import.meta.require;import{homedir as pG}from"os";import K3 from"path";import x1 from"process";function Z7(){return x1.env.HOME&&x1.env.HOME.length>0?x1.env.HOME:pG()}function o7(D){return D.startsWith("~")?K3.join(Z7(),D.slice(1)):D}function v7(D){return K3.resolve(o7(D))}function aG(D){return K3.resolve(Z7(),o7(D))}function h3(D={}){if(D.explicitHome&&D.explicitHome.length>0)return{scope:"explicit",home:v7(D.explicitHome),source:"cli-flag"};let u=x1.env[xG];if(u&&u.length>0)return{scope:"explicit",home:v7(u),source:"env"};let r=D.defaultHomeDir&&D.defaultHomeDir.length>0?D.defaultHomeDir:mG;return{scope:"user",home:aG(r),source:"user-default"}}function N3(D={}){return h3(D).home}var xG="AIWORKER_HOME",mG=".aiworker";var Q3=()=>{};function U(D,u){if(!D||typeof D!=="object")return!1;if(D instanceof u)return!0;if(!Object.prototype.hasOwnProperty.call(u,i))throw Error(`Class "${u.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(D).constructor;if(r)while(r){if(i in r&&r[i]===u[i])return!0;r=Object.getPrototypeOf(r)}return!1}var i;var y=W(()=>{i=Symbol.for("drizzle:entityKind")});var wD;var Nu=W(()=>{y();wD=class wD{constructor(D,u){this.table=D,this.config=u,this.name=u.name,this.keyAsName=u.keyAsName,this.notNull=u.notNull,this.default=u.default,this.defaultFn=u.defaultFn,this.onUpdateFn=u.onUpdateFn,this.hasDefault=u.hasDefault,this.primary=u.primaryKey,this.isUnique=u.isUnique,this.uniqueName=u.uniqueName,this.uniqueType=u.uniqueType,this.dataType=u.dataType,this.columnType=u.columnType,this.generated=u.generated,this.generatedIdentity=u.generatedIdentity}static[i]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(D){return D}mapToDriverValue(D){return D}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var L3;var q3=W(()=>{y();L3=class L3{static[i]="ColumnBuilder";config;constructor(D,u,r){this.config={name:D,keyAsName:D==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:u,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(D){return this.config.default=D,this.config.hasDefault=!0,this}$defaultFn(D){return this.config.defaultFn=D,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(D){return this.config.onUpdateFn=D,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(D){if(this.config.name!=="")return;this.config.name=D}}});var Ru;var a2=W(()=>{Ru=Symbol.for("drizzle:Name")});function d7(D,...u){return D(...u)}var l7=()=>{};function y7(D,u){return`${D[Ru]}_${u.join("_")}_unique`}var c7=W(()=>{a2()});var e2,eG;var t7=W(()=>{Nu();y();c7();e2=class e2 extends wD{constructor(D,u){if(!u.uniqueName)u.uniqueName=y7(D,[u.name]);super(D,u);this.table=D}static[i]="PgColumn"};eG=class eG extends e2{static[i]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(D){return this.indexConfig.opClass=D,this}}});function x7(D){return!!D&&typeof D==="function"&&p7 in D&&D[p7]===!0}var DC,p7,uC;var m7=W(()=>{y();t7();DC=class DC extends e2{static[i]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(D,u){super(D,u);this.enum=u.enum}getSQLType(){return this.enum.enumName}};p7=Symbol.for("drizzle:isPgEnum");uC=class uC extends e2{static[i]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(D,u){super(D,u);this.enum=u.enum}getSQLType(){return this.enum.enumName}}});var kD,DA;var Qu=W(()=>{y();kD=class kD{static[i]="Subquery";constructor(D,u,r,A=!1,f=[]){this._={brand:"Subquery",sql:D,selectedFields:u,alias:r,isWith:A,usedTables:f}}};DA=class DA extends kD{static[i]="WithSubquery"}});var a7="0.44.7";var e7=()=>{};var b3,s3,D4;var u4=W(()=>{l7();e7();D4={startActiveSpan(D,u){if(!b3)return u();if(!s3)s3=b3.trace.getTracer("drizzle-orm",a7);return d7((r,A)=>A.startActiveSpan(D,(f)=>{try{return u(f)}catch(w){throw f.setStatus({code:r.SpanStatusCode.ERROR,message:w instanceof Error?w.message:"Unknown error"}),w}finally{f.end()}}),b3,s3)}}});var HD;var Ir=W(()=>{HD=Symbol.for("drizzle:ViewBaseConfig")});function dr(D){return D[Ru]}function U0(D){return`${D[m1]??"public"}.${D[Ru]}`}var m1,a1,r4,z3,j3,uA,A4,rC,V;var pD=W(()=>{y();a2();m1=Symbol.for("drizzle:Schema"),a1=Symbol.for("drizzle:Columns"),r4=Symbol.for("drizzle:ExtraConfigColumns"),z3=Symbol.for("drizzle:OriginalName"),j3=Symbol.for("drizzle:BaseName"),uA=Symbol.for("drizzle:IsAlias"),A4=Symbol.for("drizzle:ExtraConfigBuilder"),rC=Symbol.for("drizzle:IsDrizzleTable");V=class V{static[i]="Table";static Symbol={Name:Ru,Schema:m1,OriginalName:z3,Columns:a1,ExtraConfigColumns:r4,BaseName:j3,IsAlias:uA,ExtraConfigBuilder:A4};[Ru];[z3];[m1];[a1];[r4];[j3];[uA]=!1;[rC]=!0;[A4]=void 0;constructor(D,u,r){this[Ru]=this[z3]=D,this[m1]=u,this[j3]=r}}});function T3(D){return D!==null&&D!==void 0&&typeof D.getSQL==="function"}function AC(D){let u={sql:"",params:[]};for(let r of D)if(u.sql+=r.sql,u.params.push(...r.params),r.typings?.length){if(!u.typings)u.typings=[];u.typings.push(...r.typings)}return u}function f4(D){return typeof D==="object"&&D!==null&&"mapToDriverValue"in D&&typeof D.mapToDriverValue==="function"}function G(D,...u){let r=[];if(u.length>0||D.length>0&&D[0]!=="")r.push(new hD(D[0]));for(let[A,f]of u.entries())r.push(f,new hD(D[A+1]));return new b(r)}function rA(D,u){return D.map((r)=>{if(U(r,lr)){if(!(r.name in u))throw Error(`No value for placeholder "${r.name}" was provided`);return u[r.name]}if(U(r,nu)&&U(r.value,lr)){if(!(r.value.name in u))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(u[r.value.name])}return r})}var hD,b,e1,F4,w4,uz,nu,lr,fC,Gu;var dD=W(()=>{y();m7();Qu();u4();Ir();Nu();pD();hD=class hD{static[i]="StringChunk";value;constructor(D){this.value=Array.isArray(D)?D:[D]}getSQL(){return new b([this])}};b=class b{constructor(D){this.queryChunks=D;for(let u of D)if(U(u,V)){let r=u[V.Symbol.Schema];this.usedTables.push(r===void 0?u[V.Symbol.Name]:r+"."+u[V.Symbol.Name])}}static[i]="SQL";decoder=F4;shouldInlineParams=!1;usedTables=[];append(D){return this.queryChunks.push(...D.queryChunks),this}toQuery(D){return D4.startActiveSpan("drizzle.buildSQL",(u)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,D);return u?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(D,u){let r=Object.assign({},u,{inlineParams:u.inlineParams||this.shouldInlineParams,paramStartIndex:u.paramStartIndex||{value:0}}),{casing:A,escapeName:f,escapeParam:w,prepareTyping:F,inlineParams:E,paramStartIndex:$}=r;return AC(D.map((g)=>{if(U(g,hD))return{sql:g.value.join(""),params:[]};if(U(g,e1))return{sql:f(g.value),params:[]};if(g===void 0)return{sql:"",params:[]};if(Array.isArray(g)){let _=[new hD("(")];for(let[R,n]of g.entries())if(_.push(n),R<g.length-1)_.push(new hD(", "));return _.push(new hD(")")),this.buildQueryFromSourceParams(_,r)}if(U(g,b))return this.buildQueryFromSourceParams(g.queryChunks,{...r,inlineParams:E||g.shouldInlineParams});if(U(g,V)){let _=g[V.Symbol.Schema],R=g[V.Symbol.Name];return{sql:_===void 0||g[uA]?f(R):f(_)+"."+f(R),params:[]}}if(U(g,wD)){let _=A.getColumnCasing(g);if(u.invokeSource==="indexes")return{sql:f(_),params:[]};let R=g.table[V.Symbol.Schema];return{sql:g.table[uA]||R===void 0?f(g.table[V.Symbol.Name])+"."+f(_):f(R)+"."+f(g.table[V.Symbol.Name])+"."+f(_),params:[]}}if(U(g,Gu)){let _=g[HD].schema,R=g[HD].name;return{sql:_===void 0||g[HD].isAlias?f(R):f(_)+"."+f(R),params:[]}}if(U(g,nu)){if(U(g.value,lr))return{sql:w($.value++,g),params:[g],typings:["none"]};let _=g.value===null?null:g.encoder.mapToDriverValue(g.value);if(U(_,b))return this.buildQueryFromSourceParams([_],r);if(E)return{sql:this.mapInlineParam(_,r),params:[]};let R=["none"];if(F)R=[F(g.encoder)];return{sql:w($.value++,_),params:[_],typings:R}}if(U(g,lr))return{sql:w($.value++,g),params:[g],typings:["none"]};if(U(g,b.Aliased)&&g.fieldAlias!==void 0)return{sql:f(g.fieldAlias),params:[]};if(U(g,kD)){if(g._.isWith)return{sql:f(g._.alias),params:[]};return this.buildQueryFromSourceParams([new hD("("),g._.sql,new hD(") "),new e1(g._.alias)],r)}if(x7(g)){if(g.schema)return{sql:f(g.schema)+"."+f(g.enumName),params:[]};return{sql:f(g.enumName),params:[]}}if(T3(g)){if(g.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([g.getSQL()],r);return this.buildQueryFromSourceParams([new hD("("),g.getSQL(),new hD(")")],r)}if(E)return{sql:this.mapInlineParam(g,r),params:[]};return{sql:w($.value++,g),params:[g],typings:["none"]}}))}mapInlineParam(D,{escapeString:u}){if(D===null)return"null";if(typeof D==="number"||typeof D==="boolean")return D.toString();if(typeof D==="string")return u(D);if(typeof D==="object"){let r=D.toString();if(r==="[object Object]")return u(JSON.stringify(D));return u(r)}throw Error("Unexpected param value: "+D)}getSQL(){return this}as(D){if(D===void 0)return this;return new b.Aliased(this,D)}mapWith(D){return this.decoder=typeof D==="function"?{mapFromDriverValue:D}:D,this}inlineParams(){return this.shouldInlineParams=!0,this}if(D){return D?this:void 0}};e1=class e1{constructor(D){this.value=D}static[i]="Name";brand;getSQL(){return new b([this])}};F4={mapFromDriverValue:(D)=>D},w4={mapToDriverValue:(D)=>D},uz={...F4,...w4};nu=class nu{constructor(D,u=w4){this.value=D,this.encoder=u}static[i]="Param";brand;getSQL(){return new b([this])}};((D)=>{function u(){return new b([])}D.empty=u;function r($){return new b($)}D.fromList=r;function A($){return new b([new hD($)])}D.raw=A;function f($,g){let _=[];for(let[R,n]of $.entries()){if(R>0&&g!==void 0)_.push(g);_.push(n)}return new b(_)}D.join=f;function w($){return new e1($)}D.identifier=w;function F($){return new lr($)}D.placeholder=F;function E($,g){return new nu($,g)}D.param=E})(G||(G={}));((D)=>{class u{constructor(r,A){this.sql=r,this.fieldAlias=A}static[i]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new u(this.sql,this.fieldAlias)}}D.Aliased=u})(b||(b={}));lr=class lr{constructor(D){this.name=D}static[i]="Placeholder";getSQL(){return new b([this])}};fC=Symbol.for("drizzle:IsDrizzleView");Gu=class Gu{static[i]="View";[HD];[fC]=!0;constructor({name:D,schema:u,selectedFields:r,query:A}){this[HD]={name:D,originalName:D,schema:u,selectedFields:r,query:A,isExisting:!A,isAlias:!1}}getSQL(){return new b([this])}};wD.prototype.getSQL=function(){return new b([this])};V.prototype.getSQL=function(){return new b([this])};kD.prototype.getSQL=function(){return new b([this])}});function D8(D,u){return new Proxy(D,new AA(u,!1))}function fr(D,u){return new Proxy(D,new p0(new Proxy(D.table,new AA(u,!1))))}function v3(D,u){return new b.Aliased(fA(D.sql,u),D.fieldAlias)}function fA(D,u){return G.join(D.queryChunks.map((r)=>{if(U(r,wD))return fr(r,u);if(U(r,b))return fA(r,u);if(U(r,b.Aliased))return v3(r,u);return r}))}var p0,AA;var u8=W(()=>{Nu();y();dD();pD();Ir();p0=class p0{constructor(D){this.table=D}static[i]="ColumnAliasProxyHandler";get(D,u){if(u==="table")return this.table;return D[u]}};AA=class AA{constructor(D,u){this.alias=D,this.replaceOriginalName=u}static[i]="TableAliasProxyHandler";get(D,u){if(u===V.Symbol.IsAlias)return!0;if(u===V.Symbol.Name)return this.alias;if(this.replaceOriginalName&&u===V.Symbol.OriginalName)return this.alias;if(u===HD)return{...D[HD],name:this.alias,isAlias:!0};if(u===V.Symbol.Columns){let A=D[V.Symbol.Columns];if(!A)return A;let f={};return Object.keys(A).map((w)=>{f[w]=new Proxy(A[w],new p0(new Proxy(D,this)))}),f}let r=D[u];if(U(r,wD))return new Proxy(r,new p0(new Proxy(D,this)));return r}}});var x0,Vr,Z3;var r8=W(()=>{y();x0=class x0 extends Error{static[i]="DrizzleError";constructor({message:D,cause:u}){super(D);this.name="DrizzleError",this.cause=u}};Vr=class Vr extends Error{constructor(D,u,r){super(`Failed query: ${D}
4
+ params: ${u}`);if(this.query=D,this.params=u,this.cause=r,Error.captureStackTrace(this,Vr),r)this.cause=r}};Z3=class Z3 extends x0{static[i]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var $4,o3,d3;var A8=W(()=>{y();$4=class $4{static[i]="ConsoleLogWriter";write(D){console.log(D)}};o3=class o3{static[i]="DefaultLogger";writer;constructor(D){this.writer=D?.writer??new $4}logQuery(D,u){let r=u.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),A=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${D}${A}`)}};d3=class d3{static[i]="NoopLogger";logQuery(){}}});var eD;var Kr=W(()=>{y();eD=class eD{static[i]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(D){return this.then(void 0,D)}finally(D){return this.then((u)=>{return D?.(),u},(u)=>{throw D?.(),u})}then(D,u){return this.execute().then(D,u)}}});function l3(D,u,r){let A={},f=D.reduce((w,{path:F,field:E},$)=>{let g;if(U(E,wD))g=E;else if(U(E,b))g=E.decoder;else g=E.sql.decoder;let _=w;for(let[R,n]of F.entries())if(R<F.length-1){if(!(n in _))_[n]={};_=_[n]}else{let B=u[$],C=_[n]=B===null?null:g.mapFromDriverValue(B);if(r&&U(E,wD)&&F.length===2){let J=F[0];if(!(J in A))A[J]=C===null?dr(E.table):!1;else if(typeof A[J]==="string"&&A[J]!==dr(E.table))A[J]=!1}}return w},{});if(r&&Object.keys(A).length>0){for(let[w,F]of Object.entries(A))if(typeof F==="string"&&!r[F])f[w]=null}return f}function Cu(D,u){return Object.entries(D).reduce((r,[A,f])=>{if(typeof A!=="string")return r;let w=u?[...u,A]:[A];if(U(f,wD)||U(f,b)||U(f,b.Aliased))r.push({path:w,field:f});else if(U(f,V))r.push(...Cu(f[V.Symbol.Columns],w));else r.push(...Cu(f,w));return r},[])}function FA(D,u){let r=Object.keys(D),A=Object.keys(u);if(r.length!==A.length)return!1;for(let[f,w]of r.entries())if(w!==A[f])return!1;return!0}function f8(D,u){let r=Object.entries(u).filter(([,A])=>A!==void 0).map(([A,f])=>{if(U(f,b)||U(f,wD))return[A,f];else return[A,new nu(f,D[V.Symbol.Columns][A])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function E4(D,u){for(let r of u)for(let A of Object.getOwnPropertyNames(r.prototype)){if(A==="constructor")continue;Object.defineProperty(D.prototype,A,Object.getOwnPropertyDescriptor(r.prototype,A)||Object.create(null))}}function g4(D){return D[V.Symbol.Columns]}function wA(D){return U(D,kD)?D._.alias:U(D,Gu)?D[HD].name:U(D,b)?void 0:D[V.Symbol.IsAlias]?D[V.Symbol.Name]:D[V.Symbol.BaseName]}function Fr(D,u){return{name:typeof D==="string"&&D.length>0?D:"",config:typeof D==="object"?D:u}}function S4(D){if(typeof D!=="object"||D===null)return!1;if(D.constructor.name!=="Object")return!1;if("logger"in D){let u=typeof D.logger;if(u!=="boolean"&&(u!=="object"||typeof D.logger.logQuery!=="function")&&u!=="undefined")return!1;return!0}if("schema"in D){let u=typeof D.schema;if(u!=="object"&&u!=="undefined")return!1;return!0}if("casing"in D){let u=typeof D.casing;if(u!=="string"&&u!=="undefined")return!1;return!0}if("mode"in D){if(D.mode!=="default"||D.mode!=="planetscale"||D.mode!==void 0)return!1;return!0}if("connection"in D){let u=typeof D.connection;if(u!=="string"&&u!=="object"&&u!=="undefined")return!1;return!0}if("client"in D){let u=typeof D.client;if(u!=="object"&&u!=="function"&&u!=="undefined")return!1;return!0}if(Object.keys(D).length===0)return!0;return!1}var y3;var Au=W(()=>{Nu();y();dD();Qu();pD();Ir();y3=typeof TextDecoder>"u"?null:new TextDecoder});var _4,R4,c3;var n4=W(()=>{y();pD();_4=Symbol.for("drizzle:PgInlineForeignKeys"),R4=Symbol.for("drizzle:EnableRLS");c3=class c3 extends V{static[i]="PgTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:_4,EnableRLS:R4});[_4]=[];[R4]=!1;[V.Symbol.ExtraConfigBuilder]=void 0;[V.Symbol.ExtraConfigColumns]={}}});var t3,B4;var W4=W(()=>{y();n4();t3=class t3{static[i]="PgPrimaryKeyBuilder";columns;name;constructor(D,u){this.columns=D,this.name=u}build(D){return new B4(D,this.columns,this.name)}};B4=class B4{constructor(D,u,r){this.table=D,this.columns=u,this.name=r}static[i]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[c3.Symbol.Name]}_${this.columns.map((D)=>D.name).join("_")}_pk`}}});function fu(D,u){if(f4(u)&&!T3(D)&&!U(D,nu)&&!U(D,lr)&&!U(D,wD)&&!U(D,V)&&!U(D,Gu))return new nu(D,u);return D}function hr(...D){let u=D.filter((r)=>r!==void 0);if(u.length===0)return;if(u.length===1)return new b(u);return new b([new hD("("),G.join(u,new hD(" and ")),new hD(")")])}function G4(...D){let u=D.filter((r)=>r!==void 0);if(u.length===0)return;if(u.length===1)return new b(u);return new b([new hD("("),G.join(u,new hD(" or ")),new hD(")")])}function C4(D){return G`not ${D}`}function Y4(D,u){if(Array.isArray(u)){if(u.length===0)return G`false`;return G`${D} in ${u.map((r)=>fu(r,D))}`}return G`${D} in ${fu(u,D)}`}function M4(D,u){if(Array.isArray(u)){if(u.length===0)return G`true`;return G`${D} not in ${u.map((r)=>fu(r,D))}`}return G`${D} not in ${fu(u,D)}`}function O4(D){return G`${D} is null`}function P4(D){return G`${D} is not null`}function k4(D){return G`exists ${D}`}function I4(D){return G`not exists ${D}`}function V4(D,u,r){return G`${D} between ${fu(u,D)} and ${fu(r,D)}`}function K4(D,u,r){return G`${D} not between ${fu(u,D)} and ${fu(r,D)}`}function h4(D,u){return G`${D} like ${u}`}function N4(D,u){return G`${D} not like ${u}`}function Q4(D,u){return G`${D} ilike ${u}`}function L4(D,u){return G`${D} not ilike ${u}`}var d=(D,u)=>{return G`${D} = ${fu(u,D)}`},J4=(D,u)=>{return G`${D} <> ${fu(u,D)}`},H4=(D,u)=>{return G`${D} > ${fu(u,D)}`},X4=(D,u)=>{return G`${D} >= ${fu(u,D)}`},i4=(D,u)=>{return G`${D} < ${fu(u,D)}`},U4=(D,u)=>{return G`${D} <= ${fu(u,D)}`};var q4=W(()=>{Nu();y();pD();dD()});function b4(D){return G`${D} asc`}function JD(D){return G`${D} desc`}var s4=W(()=>{dD()});var p3=W(()=>{q4();s4()});function j4(){return{and:hr,between:V4,eq:d,exists:k4,gt:H4,gte:X4,ilike:Q4,inArray:Y4,isNull:O4,isNotNull:P4,like:h4,lt:i4,lte:U4,ne:J4,not:C4,notBetween:K4,notExists:I4,notLike:N4,notIlike:L4,notInArray:M4,or:G4,sql:G}}function T4(){return{sql:G,asc:b4,desc:JD}}function v4(D,u){if(Object.keys(D).length===1&&"default"in D&&!U(D.default,V))D=D.default;let r={},A={},f={};for(let[w,F]of Object.entries(D))if(U(F,V)){let E=U0(F),$=A[E];r[E]=w,f[w]={tsName:w,dbName:F[V.Symbol.Name],schema:F[V.Symbol.Schema],columns:F[V.Symbol.Columns],relations:$?.relations??{},primaryKey:$?.primaryKey??[]};for(let _ of Object.values(F[V.Symbol.Columns]))if(_.primary)f[w].primaryKey.push(_);let g=F[V.Symbol.ExtraConfigBuilder]?.(F[V.Symbol.ExtraConfigColumns]);if(g){for(let _ of Object.values(g))if(U(_,t3))f[w].primaryKey.push(..._.columns)}}else if(U(F,z4)){let E=U0(F.table),$=r[E],g=F.config(u(F.table)),_;for(let[R,n]of Object.entries(g))if($){let B=f[$];if(B.relations[R]=n,_)B.primaryKey.push(..._)}else{if(!(E in A))A[E]={relations:{},primaryKey:_};A[E].relations[R]=n}}return{tables:f,tableNamesMap:r}}function FC(D){return function(r,A){return new yr(D,r,A,A?.fields.reduce((f,w)=>f&&w.notNull,!0)??!1)}}function wC(D){return function(r,A){return new $A(D,r,A)}}function Z4(D,u,r){if(U(r,yr)&&r.config)return{fields:r.config.fields,references:r.config.references};let A=u[U0(r.referencedTable)];if(!A)throw Error(`Table "${r.referencedTable[V.Symbol.Name]}" not found in schema`);let f=D[A];if(!f)throw Error(`Table "${A}" not found in schema`);let w=r.sourceTable,F=u[U0(w)];if(!F)throw Error(`Table "${w[V.Symbol.Name]}" not found in schema`);let E=[];for(let $ of Object.values(f.relations))if(r.relationName&&r!==$&&$.relationName===r.relationName||!r.relationName&&$.referencedTable===r.sourceTable)E.push($);if(E.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${A}"`):Error(`There are multiple relations between "${A}" and "${r.sourceTable[V.Symbol.Name]}". Please specify relation name`);if(E[0]&&U(E[0],yr)&&E[0].config)return{fields:E[0].config.references,references:E[0].config.fields};throw Error(`There is not enough information to infer relation "${F}.${r.fieldName}"`)}function o4(D){return{one:FC(D),many:wC(D)}}function F8(D,u,r,A,f=(w)=>w){let w={};for(let[F,E]of A.entries())if(E.isJson){let $=u.relations[E.tsKey],g=r[F],_=typeof g==="string"?JSON.parse(g):g;w[E.tsKey]=U($,yr)?_&&F8(D,D[E.relationTableTsKey],_,E.selection,f):_.map((R)=>F8(D,D[E.relationTableTsKey],R,E.selection,f))}else{let $=f(r[F]),g=E.field,_;if(U(g,wD))_=g;else if(U(g,b))_=g.decoder;else _=g.sql.decoder;w[E.tsKey]=$===null?null:_.mapFromDriverValue($)}return w}var x3,z4,yr,$A;var EA=W(()=>{pD();Nu();y();W4();p3();dD();x3=class x3{constructor(D,u,r){this.sourceTable=D,this.referencedTable=u,this.relationName=r,this.referencedTableName=u[V.Symbol.Name]}static[i]="Relation";referencedTableName;fieldName};z4=class z4{constructor(D,u){this.table=D,this.config=u}static[i]="Relations"};yr=class yr extends x3{constructor(D,u,r,A){super(D,u,r?.relationName);this.config=r,this.isNullable=A}static[i]="One";withFieldName(D){let u=new yr(this.sourceTable,this.referencedTable,this.config,this.isNullable);return u.fieldName=D,u}};$A=class $A extends x3{constructor(D,u,r){super(D,u,r?.relationName);this.config=r}static[i]="Many";withFieldName(D){let u=new $A(this.sourceTable,this.referencedTable,this.config);return u.fieldName=D,u}}});var d4=()=>{};var l4=()=>{};var y4=W(()=>{d4();l4()});var m3=W(()=>{p3();y4();dD()});var c4=W(()=>{u8();q3();Nu();y();r8();A8();Kr();EA();m3();Qu();pD();Au();Ir()});var ID;var m0=W(()=>{u8();Nu();y();dD();Qu();Ir();ID=class ID{static[i]="SelectionProxyHandler";config;constructor(D){this.config={...D}}get(D,u){if(u==="_")return{...D._,selectedFields:new Proxy(D._.selectedFields,this)};if(u===HD)return{...D[HD],selectedFields:new Proxy(D[HD].selectedFields,this)};if(typeof u==="symbol")return D[u];let A=(U(D,kD)?D._.selectedFields:U(D,Gu)?D[HD].selectedFields:D)[u];if(U(A,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!A.isSelectionField)return A.sql;let f=A.clone();return f.isSelectionField=!0,f}if(U(A,b)){if(this.config.sqlBehavior==="sql")return A;throw Error(`You tried to reference "${u}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(U(A,wD)){if(this.config.alias)return new Proxy(A,new p0(new Proxy(A.table,new AA(this.config.alias,this.config.replaceOriginalName??!1))));return A}if(typeof A!=="object"||A===null)return A;return new Proxy(A,new ID(this.config))}}});var a3,t4;var e3=W(()=>{y();a2();a3=class a3{static[i]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(D,u){if(this.reference=()=>{let{name:r,columns:A,foreignColumns:f}=D();return{name:r,columns:A,foreignTable:f[0].table,foreignColumns:f}},u)this._onUpdate=u.onUpdate,this._onDelete=u.onDelete}onUpdate(D){return this._onUpdate=D,this}onDelete(D){return this._onDelete=D,this}build(D){return new t4(D,this)}};t4=class t4{constructor(D,u){this.table=D,this.reference=u.reference,this.onUpdate=u._onUpdate,this.onDelete=u._onDelete}static[i]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:D,columns:u,foreignColumns:r}=this.reference(),A=u.map((F)=>F.name),f=r.map((F)=>F.name),w=[this.table[Ru],...A,r[0].table[Ru],...f];return D??`${w.join("_")}_fk`}}});function p4(D,u){return`${D[Ru]}_${u.join("_")}_unique`}var DF=W(()=>{a2()});var bD,UD;var cr=W(()=>{q3();Nu();y();e3();DF();bD=class bD extends L3{static[i]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(D,u={}){return this.foreignKeyConfigs.push({ref:D,actions:u}),this}unique(D){return this.config.isUnique=!0,this.config.uniqueName=D,this}generatedAlwaysAs(D,u){return this.config.generated={as:D,type:"always",mode:u?.mode??"virtual"},this}buildForeignKeys(D,u){return this.foreignKeyConfigs.map(({ref:r,actions:A})=>{return((f,w)=>{let F=new a3(()=>{let E=f();return{columns:[D],foreignColumns:[E]}});if(w.onUpdate)F.onUpdate(w.onUpdate);if(w.onDelete)F.onDelete(w.onDelete);return F.build(u)})(r,A)})}};UD=class UD extends wD{constructor(D,u){if(!u.uniqueName)u.uniqueName=p4(D,[u.name]);super(D,u);this.table=D}static[i]="SQLiteColumn"}});function r5(D,u){let{name:r,config:A}=Fr(D,u);if(A?.mode==="json")return new a4(r);if(A?.mode==="bigint")return new x4(r);return new D5(r)}var x4,m4,a4,e4,D5,u5;var uF=W(()=>{y();Au();cr();x4=class x4 extends bD{static[i]="SQLiteBigIntBuilder";constructor(D){super(D,"bigint","SQLiteBigInt")}build(D){return new m4(D,this.config)}};m4=class m4 extends UD{static[i]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(D){if(typeof Buffer<"u"&&Buffer.from){let u=Buffer.isBuffer(D)?D:D instanceof ArrayBuffer?Buffer.from(D):D.buffer?Buffer.from(D.buffer,D.byteOffset,D.byteLength):Buffer.from(D);return BigInt(u.toString("utf8"))}return BigInt(y3.decode(D))}mapToDriverValue(D){return Buffer.from(D.toString())}};a4=class a4 extends bD{static[i]="SQLiteBlobJsonBuilder";constructor(D){super(D,"json","SQLiteBlobJson")}build(D){return new e4(D,this.config)}};e4=class e4 extends UD{static[i]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(D){if(typeof Buffer<"u"&&Buffer.from){let u=Buffer.isBuffer(D)?D:D instanceof ArrayBuffer?Buffer.from(D):D.buffer?Buffer.from(D.buffer,D.byteOffset,D.byteLength):Buffer.from(D);return JSON.parse(u.toString("utf8"))}return JSON.parse(y3.decode(D))}mapToDriverValue(D){return Buffer.from(JSON.stringify(D))}};D5=class D5 extends bD{static[i]="SQLiteBlobBufferBuilder";constructor(D){super(D,"buffer","SQLiteBlobBuffer")}build(D){return new u5(D,this.config)}};u5=class u5 extends UD{static[i]="SQLiteBlobBuffer";mapFromDriverValue(D){if(Buffer.isBuffer(D))return D;return Buffer.from(D)}getSQLType(){return"blob"}}});function F5(D){return(u,r)=>{let{name:A,config:f}=Fr(u,r);return new A5(A,f,D)}}var A5,f5;var rF=W(()=>{y();Au();cr();A5=class A5 extends bD{static[i]="SQLiteCustomColumnBuilder";constructor(D,u,r){super(D,"custom","SQLiteCustomColumn");this.config.fieldConfig=u,this.config.customTypeParams=r}build(D){return new f5(D,this.config)}};f5=class f5 extends UD{static[i]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(D,u){super(D,u);this.sqlName=u.customTypeParams.dataType(u.fieldConfig),this.mapTo=u.customTypeParams.toDriver,this.mapFrom=u.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(D){return typeof this.mapFrom==="function"?this.mapFrom(D):D}mapToDriverValue(D){return typeof this.mapTo==="function"?this.mapTo(D):D}}});function Hu(D,u){let{name:r,config:A}=Fr(D,u);if(A?.mode==="timestamp"||A?.mode==="timestamp_ms")return new E5(r,A.mode);if(A?.mode==="boolean")return new S5(r,A.mode);return new w5(r)}var w8,$8,w5,$5,E5,g5,S5,_5;var AF=W(()=>{y();dD();Au();cr();w8=class w8 extends bD{static[i]="SQLiteBaseIntegerBuilder";constructor(D,u,r){super(D,u,r);this.config.autoIncrement=!1}primaryKey(D){if(D?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};$8=class $8 extends UD{static[i]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};w5=class w5 extends w8{static[i]="SQLiteIntegerBuilder";constructor(D){super(D,"number","SQLiteInteger")}build(D){return new $5(D,this.config)}};$5=class $5 extends $8{static[i]="SQLiteInteger"};E5=class E5 extends w8{static[i]="SQLiteTimestampBuilder";constructor(D,u){super(D,"date","SQLiteTimestamp");this.config.mode=u}defaultNow(){return this.default(G`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(D){return new g5(D,this.config)}};g5=class g5 extends $8{static[i]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(D){if(this.config.mode==="timestamp")return new Date(D*1000);return new Date(D)}mapToDriverValue(D){let u=D.getTime();if(this.config.mode==="timestamp")return Math.floor(u/1000);return u}};S5=class S5 extends w8{static[i]="SQLiteBooleanBuilder";constructor(D,u){super(D,"boolean","SQLiteBoolean");this.config.mode=u}build(D){return new _5(D,this.config)}};_5=class _5 extends $8{static[i]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(D){return Number(D)===1}mapToDriverValue(D){return D?1:0}}});function C5(D,u){let{name:r,config:A}=Fr(D,u),f=A?.mode;return f==="number"?new B5(r):f==="bigint"?new J5(r):new R5(r)}var R5,n5,B5,W5,J5,G5;var fF=W(()=>{y();Au();cr();R5=class R5 extends bD{static[i]="SQLiteNumericBuilder";constructor(D){super(D,"string","SQLiteNumeric")}build(D){return new n5(D,this.config)}};n5=class n5 extends UD{static[i]="SQLiteNumeric";mapFromDriverValue(D){if(typeof D==="string")return D;return String(D)}getSQLType(){return"numeric"}};B5=class B5 extends bD{static[i]="SQLiteNumericNumberBuilder";constructor(D){super(D,"number","SQLiteNumericNumber")}build(D){return new W5(D,this.config)}};W5=class W5 extends UD{static[i]="SQLiteNumericNumber";mapFromDriverValue(D){if(typeof D==="number")return D;return Number(D)}mapToDriverValue=String;getSQLType(){return"numeric"}};J5=class J5 extends bD{static[i]="SQLiteNumericBigIntBuilder";constructor(D){super(D,"bigint","SQLiteNumericBigInt")}build(D){return new G5(D,this.config)}};G5=class G5 extends UD{static[i]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function i5(D){return new H5(D??"")}var H5,X5;var FF=W(()=>{y();cr();H5=class H5 extends bD{static[i]="SQLiteRealBuilder";constructor(D){super(D,"number","SQLiteReal")}build(D){return new X5(D,this.config)}};X5=class X5 extends UD{static[i]="SQLiteReal";getSQLType(){return"real"}}});function H(D,u={}){let{name:r,config:A}=Fr(D,u);if(A.mode==="json")return new M5(r);return new U5(r,A)}var U5,Y5,M5,O5;var wF=W(()=>{y();Au();cr();U5=class U5 extends bD{static[i]="SQLiteTextBuilder";constructor(D,u){super(D,"string","SQLiteText");this.config.enumValues=u.enum,this.config.length=u.length}build(D){return new Y5(D,this.config)}};Y5=class Y5 extends UD{static[i]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(D,u){super(D,u)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};M5=class M5 extends bD{static[i]="SQLiteTextJsonBuilder";constructor(D){super(D,"json","SQLiteTextJson")}build(D){return new O5(D,this.config)}};O5=class O5 extends UD{static[i]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(D){return JSON.parse(D)}mapToDriverValue(D){return JSON.stringify(D)}}});function P5(){return{blob:r5,customType:F5,integer:Hu,numeric:C5,real:i5,text:H}}var k5=W(()=>{uF();rF();AF();fF();FF();wF()});function $C(D,u,r,A,f=D){let w=new sD(D,A,f),F=typeof u==="function"?u(P5()):u,E=Object.fromEntries(Object.entries(F).map(([g,_])=>{let R=_;R.setName(g);let n=R.build(w);return w[$F].push(...R.buildForeignKeys(n,w)),[g,n]})),$=Object.assign(w,E);if($[V.Symbol.Columns]=E,$[V.Symbol.ExtraConfigColumns]=E,r)$[sD.Symbol.ExtraConfigBuilder]=r;return $}var $F,sD,zD=(D,u,r)=>{return $C(D,u,r)};var Y0=W(()=>{y();pD();k5();$F=Symbol.for("drizzle:SQLiteInlineForeignKeys");sD=class sD extends V{static[i]="SQLiteTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:$F});[V.Symbol.Columns];[$F]=[];[V.Symbol.ExtraConfigBuilder]=void 0}});var I5=()=>{};function uD(D){return new EF(D,!1)}function a0(D){return new EF(D,!0)}var EF,V5,K5;var h5=W(()=>{y();EF=class EF{constructor(D,u){this.name=D,this.unique=u}static[i]="SQLiteIndexBuilderOn";on(...D){return new V5(this.name,D,this.unique)}};V5=class V5{static[i]="SQLiteIndexBuilder";config;constructor(D,u,r){this.config={name:D,columns:u,unique:r,where:void 0}}where(D){return this.config.where=D,this}build(D){return new K5(this.config,D)}};K5=class K5{static[i]="SQLiteIndex";config;constructor(D,u){this.config={...D,table:u}}}});var N5=()=>{};function Lu(D){if(U(D,sD))return[`${D[V.Symbol.BaseName]}`];if(U(D,kD))return D._.usedTables??[];if(U(D,b))return D.usedTables??[];return[]}var e0=W(()=>{y();dD();Qu();pD();Y0()});var E8;var Q5=W(()=>{y();Kr();m0();Y0();pD();Au();e0();E8=class E8 extends eD{constructor(D,u,r,A){super();this.table=D,this.session=u,this.dialect=r,this.config={table:D,withList:A}}static[i]="SQLiteDelete";config;where(D){return this.config.where=D,this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.table[V.Symbol.Columns],new ID({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];this.config.orderBy=r}else{let u=D;this.config.orderBy=u}return this}limit(D){return this.config.limit=D,this}returning(D=this.table[sD.Symbol.Columns]){return this.config.returning=Cu(D),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:Lu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(D){return this._prepare().execute(D)}$dynamic(){return this}}});function EC(D){return(D.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function gC(D){return(D.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,A,f)=>{let w=f===0?A.toLowerCase():`${A[0].toUpperCase()}${A.slice(1)}`;return r+w},"")}function SC(D){return D}var gF;var L5=W(()=>{y();pD();gF=class gF{static[i]="CasingCache";cache={};cachedTables={};convert;constructor(D){this.convert=D==="snake_case"?EC:D==="camelCase"?gC:SC}getColumnCasing(D){if(!D.keyAsName)return D.name;let u=D.table[V.Symbol.Schema]??"public",r=D.table[V.Symbol.OriginalName],A=`${u}.${r}.${D.name}`;if(!this.cache[A])this.cacheTable(D.table);return this.cache[A]}cacheTable(D){let u=D[V.Symbol.Schema]??"public",r=D[V.Symbol.OriginalName],A=`${u}.${r}`;if(!this.cachedTables[A]){for(let f of Object.values(D[V.Symbol.Columns])){let w=`${A}.${f.name}`;this.cache[w]=this.convert(f.name)}this.cachedTables[A]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var SF=W(()=>{uF();cr();rF();AF();fF();FF();wF()});var M0;var g8=W(()=>{y();dD();M0=class M0 extends Gu{static[i]="SQLiteViewBase"}});var gA,SA;var S8=W(()=>{u8();L5();Nu();y();r8();EA();m3();dD();SF();Y0();Qu();pD();Au();Ir();g8();gA=class gA{static[i]="SQLiteDialect";casing;constructor(D){this.casing=new gF(D?.casing)}escapeName(D){return`"${D}"`}escapeParam(D){return"?"}escapeString(D){return`'${D.replace(/'/g,"''")}'`}buildWithCTE(D){if(!D?.length)return;let u=[G`with `];for(let[r,A]of D.entries())if(u.push(G`${G.identifier(A._.alias)} as (${A._.sql})`),r<D.length-1)u.push(G`, `);return u.push(G` `),G.join(u)}buildDeleteQuery({table:D,where:u,returning:r,withList:A,limit:f,orderBy:w}){let F=this.buildWithCTE(A),E=r?G` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,$=u?G` where ${u}`:void 0,g=this.buildOrderBy(w),_=this.buildLimit(f);return G`${F}delete from ${D}${$}${E}${g}${_}`}buildUpdateSet(D,u){let r=D[V.Symbol.Columns],A=Object.keys(r).filter((w)=>u[w]!==void 0||r[w]?.onUpdateFn!==void 0),f=A.length;return G.join(A.flatMap((w,F)=>{let E=r[w],$=u[w]??G.param(E.onUpdateFn(),E),g=G`${G.identifier(this.casing.getColumnCasing(E))} = ${$}`;if(F<f-1)return[g,G.raw(", ")];return[g]}))}buildUpdateQuery({table:D,set:u,where:r,returning:A,withList:f,joins:w,from:F,limit:E,orderBy:$}){let g=this.buildWithCTE(f),_=this.buildUpdateSet(D,u),R=F&&G.join([G.raw(" from "),this.buildFromTable(F)]),n=this.buildJoins(w),B=A?G` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,C=r?G` where ${r}`:void 0,J=this.buildOrderBy($),X=this.buildLimit(E);return G`${g}update ${D} set ${_}${R}${n}${C}${B}${J}${X}`}buildSelection(D,{isSingleTable:u=!1}={}){let r=D.length,A=D.flatMap(({field:f},w)=>{let F=[];if(U(f,b.Aliased)&&f.isSelectionField)F.push(G.identifier(f.fieldAlias));else if(U(f,b.Aliased)||U(f,b)){let E=U(f,b.Aliased)?f.sql:f;if(u)F.push(new b(E.queryChunks.map(($)=>{if(U($,wD))return G.identifier(this.casing.getColumnCasing($));return $})));else F.push(E);if(U(f,b.Aliased))F.push(G` as ${G.identifier(f.fieldAlias)}`)}else if(U(f,wD)){let E=f.table[V.Symbol.Name];if(f.columnType==="SQLiteNumericBigInt")if(u)F.push(G`cast(${G.identifier(this.casing.getColumnCasing(f))} as text)`);else F.push(G`cast(${G.identifier(E)}.${G.identifier(this.casing.getColumnCasing(f))} as text)`);else if(u)F.push(G.identifier(this.casing.getColumnCasing(f)));else F.push(G`${G.identifier(E)}.${G.identifier(this.casing.getColumnCasing(f))}`)}if(w<r-1)F.push(G`, `);return F});return G.join(A)}buildJoins(D){if(!D||D.length===0)return;let u=[];if(D)for(let[r,A]of D.entries()){if(r===0)u.push(G` `);let f=A.table,w=A.on?G` on ${A.on}`:void 0;if(U(f,sD)){let F=f[sD.Symbol.Name],E=f[sD.Symbol.Schema],$=f[sD.Symbol.OriginalName],g=F===$?void 0:A.alias;u.push(G`${G.raw(A.joinType)} join ${E?G`${G.identifier(E)}.`:void 0}${G.identifier($)}${g&&G` ${G.identifier(g)}`}${w}`)}else u.push(G`${G.raw(A.joinType)} join ${f}${w}`);if(r<D.length-1)u.push(G` `)}return G.join(u)}buildLimit(D){return typeof D==="object"||typeof D==="number"&&D>=0?G` limit ${D}`:void 0}buildOrderBy(D){let u=[];if(D){for(let[r,A]of D.entries())if(u.push(A),r<D.length-1)u.push(G`, `)}return u.length>0?G` order by ${G.join(u)}`:void 0}buildFromTable(D){if(U(D,V)&&D[V.Symbol.IsAlias])return G`${G`${G.identifier(D[V.Symbol.Schema]??"")}.`.if(D[V.Symbol.Schema])}${G.identifier(D[V.Symbol.OriginalName])} ${G.identifier(D[V.Symbol.Name])}`;return D}buildSelectQuery({withList:D,fields:u,fieldsFlat:r,where:A,having:f,table:w,joins:F,orderBy:E,groupBy:$,limit:g,offset:_,distinct:R,setOperators:n}){let B=r??Cu(u);for(let e of B)if(U(e.field,wD)&&dr(e.field.table)!==(U(w,kD)?w._.alias:U(w,M0)?w[HD].name:U(w,b)?void 0:dr(w))&&!((qD)=>F?.some(({alias:Ar})=>Ar===(qD[V.Symbol.IsAlias]?dr(qD):qD[V.Symbol.BaseName])))(e.field.table)){let qD=dr(e.field.table);throw Error(`Your "${e.path.join("->")}" field references a column "${qD}"."${e.field.name}", but the table "${qD}" is not part of the query! Did you forget to join it?`)}let C=!F||F.length===0,J=this.buildWithCTE(D),X=R?G` distinct`:void 0,M=this.buildSelection(B,{isSingleTable:C}),P=this.buildFromTable(w),k=this.buildJoins(F),s=A?G` where ${A}`:void 0,q=f?G` having ${f}`:void 0,Y=[];if($){for(let[e,qD]of $.entries())if(Y.push(qD),e<$.length-1)Y.push(G`, `)}let v=Y.length>0?G` group by ${G.join(Y)}`:void 0,N=this.buildOrderBy(E),rD=this.buildLimit(g),_D=_?G` offset ${_}`:void 0,WD=G`${J}select${X} ${M} from ${P}${k}${s}${v}${q}${N}${rD}${_D}`;if(n.length>0)return this.buildSetOperations(WD,n);return WD}buildSetOperations(D,u){let[r,...A]=u;if(!r)throw Error("Cannot pass undefined values to any set operator");if(A.length===0)return this.buildSetOperationQuery({leftSelect:D,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:D,setOperator:r}),A)}buildSetOperationQuery({leftSelect:D,setOperator:{type:u,isAll:r,rightSelect:A,limit:f,orderBy:w,offset:F}}){let E=G`${D.getSQL()} `,$=G`${A.getSQL()}`,g;if(w&&w.length>0){let B=[];for(let C of w)if(U(C,UD))B.push(G.identifier(C.name));else if(U(C,b)){for(let J=0;J<C.queryChunks.length;J++){let X=C.queryChunks[J];if(U(X,UD))C.queryChunks[J]=G.identifier(this.casing.getColumnCasing(X))}B.push(G`${C}`)}else B.push(G`${C}`);g=G` order by ${G.join(B,G`, `)}`}let _=typeof f==="object"||typeof f==="number"&&f>=0?G` limit ${f}`:void 0,R=G.raw(`${u} ${r?"all ":""}`),n=F?G` offset ${F}`:void 0;return G`${E}${R}${$}${g}${_}${n}`}buildInsertQuery({table:D,values:u,onConflict:r,returning:A,withList:f,select:w}){let F=[],E=D[V.Symbol.Columns],$=Object.entries(E).filter(([C,J])=>!J.shouldDisableInsert()),g=$.map(([,C])=>G.identifier(this.casing.getColumnCasing(C)));if(w){let C=u;if(U(C,b))F.push(C);else F.push(C.getSQL())}else{let C=u;F.push(G.raw("values "));for(let[J,X]of C.entries()){let M=[];for(let[P,k]of $){let s=X[P];if(s===void 0||U(s,nu)&&s.value===void 0){let q;if(k.default!==null&&k.default!==void 0)q=U(k.default,b)?k.default:G.param(k.default,k);else if(k.defaultFn!==void 0){let Y=k.defaultFn();q=U(Y,b)?Y:G.param(Y,k)}else if(!k.default&&k.onUpdateFn!==void 0){let Y=k.onUpdateFn();q=U(Y,b)?Y:G.param(Y,k)}else q=G`null`;M.push(q)}else M.push(s)}if(F.push(M),J<C.length-1)F.push(G`, `)}}let _=this.buildWithCTE(f),R=G.join(F),n=A?G` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,B=r?.length?G.join(r):void 0;return G`${_}insert into ${D} ${g} ${R}${B}${n}`}sqlToQuery(D,u){return D.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:u})}buildRelationalQuery({fullSchema:D,schema:u,tableNamesMap:r,table:A,tableConfig:f,queryConfig:w,tableAlias:F,nestedQueryRelation:E,joinOn:$}){let g=[],_,R,n=[],B,C=[];if(w===!0)g=Object.entries(f.columns).map(([M,P])=>({dbKey:P.name,tsKey:M,field:fr(P,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let X=Object.fromEntries(Object.entries(f.columns).map(([Y,v])=>[Y,fr(v,F)]));if(w.where){let Y=typeof w.where==="function"?w.where(X,j4()):w.where;B=Y&&fA(Y,F)}let M=[],P=[];if(w.columns){let Y=!1;for(let[v,N]of Object.entries(w.columns)){if(N===void 0)continue;if(v in f.columns){if(!Y&&N===!0)Y=!0;P.push(v)}}if(P.length>0)P=Y?P.filter((v)=>w.columns?.[v]===!0):Object.keys(f.columns).filter((v)=>!P.includes(v))}else P=Object.keys(f.columns);for(let Y of P){let v=f.columns[Y];M.push({tsKey:Y,value:v})}let k=[];if(w.with)k=Object.entries(w.with).filter((Y)=>!!Y[1]).map(([Y,v])=>({tsKey:Y,queryConfig:v,relation:f.relations[Y]}));let s;if(w.extras){s=typeof w.extras==="function"?w.extras(X,{sql:G}):w.extras;for(let[Y,v]of Object.entries(s))M.push({tsKey:Y,value:v3(v,F)})}for(let{tsKey:Y,value:v}of M)g.push({dbKey:U(v,b.Aliased)?v.fieldAlias:f.columns[Y].name,tsKey:Y,field:U(v,wD)?fr(v,F):v,relationTableTsKey:void 0,isJson:!1,selection:[]});let q=typeof w.orderBy==="function"?w.orderBy(X,T4()):w.orderBy??[];if(!Array.isArray(q))q=[q];n=q.map((Y)=>{if(U(Y,wD))return fr(Y,F);return fA(Y,F)}),_=w.limit,R=w.offset;for(let{tsKey:Y,queryConfig:v,relation:N}of k){let rD=Z4(u,r,N),_D=U0(N.referencedTable),WD=r[_D],e=`${F}_${Y}`,qD=hr(...rD.fields.map((dG,lG)=>d(fr(rD.references[lG],e),fr(dG,F)))),Ar=this.buildRelationalQuery({fullSchema:D,schema:u,tableNamesMap:r,table:D[WD],tableConfig:u[WD],queryConfig:U(N,yr)?v===!0?{limit:1}:{...v,limit:1}:v,tableAlias:e,joinOn:qD,nestedQueryRelation:N}),oG=G`(${Ar.sql})`.as(Y);g.push({dbKey:Y,tsKey:Y,field:oG,relationTableTsKey:WD,isJson:!0,selection:Ar.selection})}}if(g.length===0)throw new x0({message:`No fields selected for table "${f.tsName}" ("${F}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let J;if(B=hr($,B),E){let X=G`json_array(${G.join(g.map(({field:k})=>U(k,UD)?G.identifier(this.casing.getColumnCasing(k)):U(k,b.Aliased)?k.sql:k),G`, `)})`;if(U(E,$A))X=G`coalesce(json_group_array(${X}), json_array())`;let M=[{dbKey:"data",tsKey:"data",field:X.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:g}];if(_!==void 0||R!==void 0||n.length>0)J=this.buildSelectQuery({table:D8(A,F),fields:{},fieldsFlat:[{path:[],field:G.raw("*")}],where:B,limit:_,offset:R,orderBy:n,setOperators:[]}),B=void 0,_=void 0,R=void 0,n=void 0;else J=D8(A,F);J=this.buildSelectQuery({table:U(J,sD)?J:new kD(J,{},F),fields:{},fieldsFlat:M.map(({field:k})=>({path:[],field:U(k,wD)?fr(k,F):k})),joins:C,where:B,limit:_,offset:R,orderBy:n,setOperators:[]})}else J=this.buildSelectQuery({table:D8(A,F),fields:{},fieldsFlat:g.map(({field:X})=>({path:[],field:U(X,wD)?fr(X,F):X})),joins:C,where:B,limit:_,offset:R,orderBy:n,setOperators:[]});return{tableTsKey:f.tsName,sql:J,selection:g}}};SA=class SA extends gA{static[i]="SQLiteSyncDialect";migrate(D,u,r){let A=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",f=G`
5
+ CREATE TABLE IF NOT EXISTS ${G.identifier(A)} (
6
6
  id SERIAL PRIMARY KEY,
7
7
  hash text NOT NULL,
8
8
  created_at numeric
9
9
  )
10
- `;u.run(f);let F=u.values(C`SELECT id, hash, created_at FROM ${C.identifier(A)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;u.run(C`BEGIN`);try{for(let E of D)if(!F||Number(F[2])<E.folderMillis){for(let $ of E.sql)u.run(C.raw($));u.run(C`INSERT INTO ${C.identifier(A)} ("hash", "created_at") VALUES(${E.hash}, ${E.folderMillis})`)}u.run(C`COMMIT`)}catch(E){throw u.run(C`ROLLBACK`),E}}}});var FF;var H4=W(()=>{l();FF=class FF{static[X]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function $8(D,u){return(r,A,...f)=>{let w=[A,...f].map((F)=>({type:D,isAll:u,rightSelect:F}));for(let F of w)if(!F1(r.getSelectedFields(),F.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(w)}}var Qu,n4,wF,ZC=()=>({union:oC,unionAll:dC,intersect:yC,except:lC}),oC,dC,yC,lC;var $F=W(()=>{l();H4();Vr();m0();oD();hu();cD();uu();kr();a0();F8();Qu=class Qu{static[X]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(D){this.fields=D.fields,this.session=D.session,this.dialect=D.dialect,this.withList=D.withList,this.distinct=D.distinct}from(D){let u=!!this.fields,r;if(this.fields)r=this.fields;else if(Y(D,iD))r=Object.fromEntries(Object.keys(D._.selectedFields).map((A)=>[A,D[A]]));else if(Y(D,O0))r=D[nD].selectedFields;else if(Y(D,b))r={};else r=l7(D);return new wF({table:D,fields:r,isPartialSelect:u,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};n4=class n4 extends FF{static[X]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:D,fields:u,isPartialSelect:r,session:A,dialect:f,withList:w,distinct:F}){super();this.config={withList:w,table:D,fields:{...u},distinct:F,setOperators:[]},this.isPartialSelect=r,this.session=A,this.dialect=f,this._={selectedFields:u,config:this.config},this.tableName=w1(D),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let E of Nu(D))this.usedTables.add(E)}getUsedTables(){return[...this.usedTables]}createJoin(D){return(u,r)=>{let A=this.tableName,f=w1(u);for(let w of Nu(u))this.usedTables.add(w);if(typeof f==="string"&&this.config.joins?.some((w)=>w.alias===f))throw Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof A==="string")this.config.fields={[A]:this.config.fields};if(typeof f==="string"&&!Y(u,b)){let w=Y(u,iD)?u._.selectedFields:Y(u,Gu)?u[nD].selectedFields:u[V.Symbol.Columns];this.config.fields[f]=w}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new kD({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:u,joinType:D,alias:f}),typeof f==="string")switch(D){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([w])=>[w,!1])),this.joinsNotNullableMap[f]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([w])=>[w,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(D,u){return(r)=>{let A=typeof r==="function"?r(ZC()):r;if(!F1(this.getSelectedFields(),A.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:D,isAll:u,rightSelect:A}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(D){return this.config.setOperators.push(...D),this}where(D){if(typeof D==="function")D=D(new Proxy(this.config.fields,new kD({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=D,this}having(D){if(typeof D==="function")D=D(new Proxy(this.config.fields,new kD({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=D,this}groupBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.fields,new kD({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(u)?u:[u]}else this.config.groupBy=D;return this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.fields,new kD({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let u=D;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=u;else this.config.orderBy=u}return this}limit(D){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=D;else this.config.limit=D;return this}offset(D){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=D;else this.config.offset=D;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}as(D){let u=[];if(u.push(...Nu(this.config.table)),this.config.joins)for(let r of this.config.joins)u.push(...Nu(r.table));return new Proxy(new iD(this.getSQL(),this.config.fields,D,!1,[...new Set(u)]),new kD({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new kD({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};wF=class wF extends n4{static[X]="SQLiteSelect";_prepare(D=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let u=Cu(this.config.fields),r=this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),u,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(D){return this.cacheConfig=D===void 0?{config:{},enable:!0,autoInvalidate:!0}:D===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...D},this}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.all()}};y7(wF,[mD]);oC=$8("union",!1),dC=$8("union",!0),yC=$8("intersect",!1),lC=$8("except",!1)});var R1;var EF=W(()=>{l();m0();w8();hu();$F();R1=class R1{static[X]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(D){this.dialect=Y(D,g1)?D:void 0,this.dialectConfig=Y(D,g1)?void 0:D}$with=(D,u)=>{let r=this;return{as:(f)=>{if(typeof f==="function")f=f(r);return new Proxy(new D1(f.getSQL(),u??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),D,!0),new kD({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...D){let u=this;function r(f){return new Qu({fields:f??void 0,session:void 0,dialect:u.getDialect(),withList:D})}function A(f){return new Qu({fields:f??void 0,session:void 0,dialect:u.getDialect(),withList:D,distinct:!0})}return{select:r,selectDistinct:A}}select(D){return new Qu({fields:D??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(D){return new Qu({fields:D??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new _1(this.dialectConfig);return this.dialect}}});var E8,gF;var U4=W(()=>{l();Vr();oD();M0();cD();uu();a0();EF();E8=class E8{constructor(D,u,r,A){this.table=D,this.session=u,this.dialect=r,this.withList=A}static[X]="SQLiteInsertBuilder";values(D){if(D=Array.isArray(D)?D:[D],D.length===0)throw Error("values() must be called with at least one value");let u=D.map((r)=>{let A={},f=this.table[V.Symbol.Columns];for(let w of Object.keys(r)){let F=r[w];A[w]=Y(F,b)?F:new Ru(F,f[w])}return A});return new gF(this.table,u,this.session,this.dialect,this.withList)}select(D){let u=typeof D==="function"?D(new R1):D;if(!Y(u,b)&&!F1(this.table[tA],u._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new gF(this.table,u,this.session,this.dialect,this.withList,!0)}};gF=class gF extends mD{constructor(D,u,r,A,f,w){super();this.session=r,this.dialect=A,this.config={table:D,values:u,withList:f,select:w}}static[X]="SQLiteInsert";config;returning(D=this.config.table[qD.Symbol.Columns]){return this.config.returning=Cu(D),this}onConflictDoNothing(D={}){if(!this.config.onConflict)this.config.onConflict=[];if(D.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let u=Array.isArray(D.target)?C`${D.target}`:C`${[D.target]}`,r=D.where?C` where ${D.where}`:C``;this.config.onConflict.push(C` on conflict ${u} do nothing${r}`)}return this}onConflictDoUpdate(D){if(D.where&&(D.targetWhere||D.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let u=D.where?C` where ${D.where}`:void 0,r=D.targetWhere?C` where ${D.targetWhere}`:void 0,A=D.setWhere?C` where ${D.setWhere}`:void 0,f=Array.isArray(D.target)?C`${D.target}`:C`${[D.target]}`,w=this.dialect.buildUpdateSet(this.config.table,D8(this.config.table,D.set));return this.config.onConflict.push(C` on conflict ${f}${r} do update set ${w}${u}${A}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Nu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var g8,X4;var Y4=W(()=>{l();Vr();m0();M0();hu();cD();uu();kr();a0();F8();g8=class g8{constructor(D,u,r,A){this.table=D,this.session=u,this.dialect=r,this.withList=A}static[X]="SQLiteUpdateBuilder";set(D){return new X4(this.table,D8(this.table,D),this.session,this.dialect,this.withList)}};X4=class X4 extends mD{constructor(D,u,r,A,f){super();this.session=r,this.dialect=A,this.config={set:u,table:D,withList:f,joins:[]}}static[X]="SQLiteUpdate";config;from(D){return this.config.from=D,this}createJoin(D){return(u,r)=>{let A=w1(u);if(typeof A==="string"&&this.config.joins.some((f)=>f.alias===A))throw Error(`Alias "${A}" is already used in this query`);if(typeof r==="function"){let f=this.config.from?Y(u,qD)?u[V.Symbol.Columns]:Y(u,iD)?u._.selectedFields:Y(u,O0)?u[nD].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[V.Symbol.Columns],new kD({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),f&&new Proxy(f,new kD({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:u,joinType:D,alias:A}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(D){return this.config.where=D,this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.table[V.Symbol.Columns],new kD({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];this.config.orderBy=r}else{let u=D;this.config.orderBy=u}return this}limit(D){return this.config.limit=D,this}returning(D=this.config.table[qD.Symbol.Columns]){return this.config.returning=Cu(D),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Nu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var _F=W(()=>{G4();U4();EF();$F();Y4()});var S1;var M4=W(()=>{l();oD();S1=class S1 extends b{constructor(D){super(S1.buildEmbeddedCount(D.source,D.filters).queryChunks);this.params=D,this.session=D.session,this.sql=S1.buildCount(D.source,D.filters)}sql;static[X]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(D,u){return C`(select count(*) from ${D}${C.raw(" where ").if(u)}${u})`}static buildCount(D,u){return C`select count(*) from ${D}${C.raw(" where ").if(u)}${u}`}then(D,u){return Promise.resolve(this.session.count(this.sql)).then(D,u)}catch(D){return this.then(void 0,D)}finally(D){return this.then((u)=>{return D?.(),u},(u)=>{throw D?.(),u})}}});var SF,_8,RF;var O4=W(()=>{l();Vr();E1();SF=class SF{constructor(D,u,r,A,f,w,F,E){this.mode=D,this.fullSchema=u,this.schema=r,this.tableNamesMap=A,this.table=f,this.tableConfig=w,this.dialect=F,this.session=E}static[X]="SQLiteAsyncRelationalQueryBuilder";findMany(D){return this.mode==="sync"?new RF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?D:{},"many"):new _8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?D:{},"many")}findFirst(D){return this.mode==="sync"?new RF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?{...D,limit:1}:{limit:1},"first"):new _8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?{...D,limit:1}:{limit:1},"first")}};_8=class _8 extends mD{constructor(D,u,r,A,f,w,F,E,$){super();this.fullSchema=D,this.schema=u,this.tableNamesMap=r,this.table=A,this.tableConfig=f,this.dialect=w,this.session=F,this.config=E,this.mode=$}static[X]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(D=!1){let{query:u,builtQuery:r}=this._toSQL();return this.session[D?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(A,f)=>{let w=A.map((F)=>u8(this.schema,this.tableConfig,F,u.selection,f));if(this.mode==="first")return w[0];return w})}prepare(){return this._prepare(!1)}_toSQL(){let D=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),u=this.dialect.sqlToQuery(D.sql);return{query:D,builtQuery:u}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};RF=class RF extends _8{static[X]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var e0;var P4=W(()=>{l();Vr();e0=class e0 extends mD{constructor(D,u,r,A,f){super();this.execute=D,this.getSQL=u,this.dialect=A,this.mapBatchResult=f,this.config={action:r}}static[X]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(D,u){return u?this.mapBatchResult(D):D}_prepare(){return this}isResponseInArrayMode(){return!1}}});var B1;var R8=W(()=>{l();m0();oD();_F();hu();M4();O4();P4();B1=class B1{constructor(D,u,r,A){this.resultKind=D,this.dialect=u,this.session=r,this._=A?{schema:A.schema,fullSchema:A.fullSchema,tableNamesMap:A.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let f=this.query;if(this._.schema)for(let[w,F]of Object.entries(this._.schema))f[w]=new SF(D,A.fullSchema,this._.schema,this._.tableNamesMap,A.fullSchema[w],F,u,r);this.$cache={invalidate:async(w)=>{}}}static[X]="BaseSQLiteDatabase";query;$with=(D,u)=>{let r=this;return{as:(f)=>{if(typeof f==="function")f=f(new R1(r.dialect));return new Proxy(new D1(f.getSQL(),u??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),D,!0),new kD({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(D,u){return new S1({source:D,filters:u,session:this.session})}with(...D){let u=this;function r(E){return new Qu({fields:E??void 0,session:u.session,dialect:u.dialect,withList:D})}function A(E){return new Qu({fields:E??void 0,session:u.session,dialect:u.dialect,withList:D,distinct:!0})}function f(E){return new g8(E,u.session,u.dialect,D)}function w(E){return new E8(E,u.session,u.dialect,D)}function F(E){return new f8(E,u.session,u.dialect,D)}return{select:r,selectDistinct:A,update:f,insert:w,delete:F}}select(D){return new Qu({fields:D??void 0,session:this.session,dialect:this.dialect})}selectDistinct(D){return new Qu({fields:D??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(D){return new g8(D,this.session,this.dialect)}$cache;insert(D){return new E8(D,this.session,this.dialect)}delete(D){return new f8(D,this.session,this.dialect)}run(D){let u=typeof D==="string"?C.raw(D):D.getSQL();if(this.resultKind==="async")return new e0(async()=>this.session.run(u),()=>u,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(u)}all(D){let u=typeof D==="string"?C.raw(D):D.getSQL();if(this.resultKind==="async")return new e0(async()=>this.session.all(u),()=>u,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(u)}get(D){let u=typeof D==="string"?C.raw(D):D.getSQL();if(this.resultKind==="async")return new e0(async()=>this.session.get(u),()=>u,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(u)}values(D){let u=typeof D==="string"?C.raw(D):D.getSQL();if(this.resultKind==="async")return new e0(async()=>this.session.values(u),()=>u,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(u)}transaction(D,u){return this.session.transaction(D,u)}}});var i4=()=>{};async function JF(D,u){let r=`${D}-${JSON.stringify(u)}`,f=new TextEncoder().encode(r),w=await crypto.subtle.digest("SHA-256",f);return[...new Uint8Array(w)].map(($)=>$.toString(16).padStart(2,"0")).join("")}var k4,BF;var I4=W(()=>{l();k4=class k4{static[X]="Cache"};BF=class BF extends k4{strategy(){return"all"}static[X]="NoopCache";async get(D){return}async put(D,u,r,A){}async onMutate(D){}}});var V4,WF,GF,CF;var HF=W(()=>{I4();l();aA();Vr();R8();V4=class V4 extends mD{constructor(D){super();this.resultCb=D}static[X]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};WF=class WF{constructor(D,u,r,A,f,w){if(this.mode=D,this.executeMethod=u,this.query=r,this.cache=A,this.queryMetadata=f,this.cacheConfig=w,A&&A.strategy()==="all"&&w===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[X]="PreparedQuery";joinsNotNullableMap;async queryWithCache(D,u,r){if(this.cache===void 0||Y(this.cache,BF)||this.queryMetadata===void 0)try{return await r()}catch(A){throw new Ir(D,u,A)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(A){throw new Ir(D,u,A)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[A]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return A}catch(A){throw new Ir(D,u,A)}if(!this.cacheConfig)try{return await r()}catch(A){throw new Ir(D,u,A)}if(this.queryMetadata.type==="select"){let A=await this.cache.get(this.cacheConfig.tag??await JF(D,u),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(A===void 0){let f;try{f=await r()}catch(w){throw new Ir(D,u,w)}return await this.cache.put(this.cacheConfig.tag??await JF(D,u),f,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),f}return A}try{return await r()}catch(A){throw new Ir(D,u,A)}}getQuery(){return this.query}mapRunResult(D,u){return D}mapAllResult(D,u){throw Error("Not implemented")}mapGetResult(D,u){throw Error("Not implemented")}execute(D){if(this.mode==="async")return this[this.executeMethod](D);return new V4(()=>this[this.executeMethod](D))}mapResult(D,u){switch(this.executeMethod){case"run":return this.mapRunResult(D,u);case"all":return this.mapAllResult(D,u);case"get":return this.mapGetResult(D,u)}}};GF=class GF{constructor(D){this.dialect=D}static[X]="SQLiteSession";prepareOneTimeQuery(D,u,r,A,f,w,F){return this.prepareQuery(D,u,r,A,f,w,F)}run(D){let u=this.dialect.sqlToQuery(D);try{return this.prepareOneTimeQuery(u,void 0,"run",!1).run()}catch(r){throw new x0({cause:r,message:`Failed to run the query '${u.sql}'`})}}extractRawRunValueFromBatchResult(D){return D}all(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(D){throw Error("Not implemented")}get(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(D){throw Error("Not implemented")}values(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).values()}async count(D){return(await this.values(D))[0][0]}extractRawValuesValueFromBatchResult(D){throw Error("Not implemented")}};CF=class CF extends B1{constructor(D,u,r,A,f=0){super(D,u,r,A);this.schema=A,this.nestedIndex=f}static[X]="SQLiteTransaction";rollback(){throw new b3}}});var K4=()=>{};var nF=W(()=>{i4();R4();fF();R8();w8();c3();J4();W4();_F();HF();M0();t3();a0();K4()});var UF,XF,h4;var YF=W(()=>{l();eA();oD();nF();HF();uu();UF=class UF extends GF{constructor(D,u,r,A={}){super(u);this.client=D,this.schema=r,this.logger=A.logger??new j3}static[X]="SQLiteBunSession";logger;exec(D){this.client.exec(D)}prepareQuery(D,u,r,A,f){let w=this.client.prepare(D.sql);return new h4(w,D,this.logger,u,r,A,f)}transaction(D,u={}){let r=new XF("sync",this.dialect,this,this.schema),A;return this.client.transaction(()=>{A=D(r)})[u.behavior??"deferred"](),A}};XF=class XF extends CF{static[X]="SQLiteBunTransaction";transaction(D){let u=`sp${this.nestedIndex}`,r=new XF("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(C.raw(`savepoint ${u}`));try{let A=D(r);return this.session.run(C.raw(`release savepoint ${u}`)),A}catch(A){throw this.session.run(C.raw(`rollback to savepoint ${u}`)),A}}};h4=class h4 extends WF{constructor(D,u,r,A,f,w,F){super("sync",f,u);this.stmt=D,this.logger=r,this.fields=A,this._isResponseInArrayMode=w,this.customResultMapper=F}static[X]="SQLiteBunPreparedQuery";run(D){let u=r1(this.query.params,D??{});return this.logger.logQuery(this.query.sql,u),this.stmt.run(...u)}all(D){let{fields:u,query:r,logger:A,joinsNotNullableMap:f,stmt:w,customResultMapper:F}=this;if(!u&&!F){let $=r1(r.params,D??{});return A.logQuery(r.sql,$),w.all(...$)}let E=this.values(D);if(F)return F(E);return E.map(($)=>T3(u,$,f))}get(D){let u=r1(this.query.params,D??{});this.logger.logQuery(this.query.sql,u);let r=this.stmt.values(...u)[0];if(!r)return;let{fields:A,joinsNotNullableMap:f,customResultMapper:w}=this;if(!A&&!w)return r;if(w)return w([r]);return T3(A,r,f)}values(D){let u=r1(this.query.params,D??{});return this.logger.logQuery(this.query.sql,u),this.stmt.values(...u)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as S8}from"bun:sqlite";function D2(D,u={}){let r=new _1({casing:u.casing}),A;if(u.logger===!0)A=new z3;else if(u.logger!==!1)A=u.logger;let f;if(u.schema){let E=O5(u.schema,i5);f={fullSchema:u.schema,schema:E.tables,tableNamesMap:E.tableNamesMap}}let w=new UF(D,r,f,{logger:A}),F=new N4("sync",r,w,f);return F.$client=D,F}function B8(...D){if(D[0]===void 0||typeof D[0]==="string"){let u=D[0]===void 0?new S8:new S8(D[0]);return D2(u,D[1])}if(c7(D[0])){let{connection:u,client:r,...A}=D[0];if(r)return D2(r,A);if(typeof u==="object"){let{source:w,...F}=u,E=Object.values(F).filter((g)=>g!==void 0).length?F:void 0,$=new S8(w,E);return D2($,A)}let f=new S8(u);return D2(f,A)}return D2(D[0],D[1])}var N4;var Q4=W(()=>{l();eA();E1();R8();w8();uu();YF();N4=class N4 extends B1{static[X]="BunSQLiteDatabase"};((D)=>{function u(r){return D2({},r)}D.mock=u})(B8||(B8={}))});var L4=W(()=>{Q4();YF()});import cC from"crypto";import MF from"fs";function q4(D){let u=D.migrationsFolder,r=[],A=`${u}/meta/_journal.json`;if(!MF.existsSync(A))throw Error("Can't find meta/_journal.json file");let f=MF.readFileSync(`${u}/meta/_journal.json`).toString(),w=JSON.parse(f);for(let F of w.entries){let E=`${u}/${F.tag}.sql`;try{let $=MF.readFileSync(`${u}/${F.tag}.sql`).toString(),g=$.split("--> statement-breakpoint").map((R)=>{return R});r.push({sql:g,bps:F.breakpoints,folderMillis:F.when,hash:cC.createHash("sha256").update($).digest("hex")})}catch{throw Error(`No file ${E} found in ${u} folder`)}}return r}var b4=()=>{};function z4(D,u){let r=q4(u);D.dialect.migrate(r,D.session,u)}var j4=W(()=>{b4()});var OF={};dA(OF,{workspaces:()=>jD,workers:()=>zD,workerSecrets:()=>mC,workerIdentity:()=>tC,workerConfig:()=>xC,turns:()=>OD,soulApps:()=>Su,soulAppStorageRecords:()=>qu,soulAppAuditEvents:()=>$r,settings:()=>hr,sessions:()=>TD,sessionEvents:()=>tD,reviews:()=>wr,lessons:()=>Lu,files:()=>Au,engineInvocations:()=>KD,artifacts:()=>Fr});var $D=()=>new Date().toISOString(),zD,jD,TD,OD,KD,tD,Au,Fr,wr,Lu,Su,qu,$r,hr,tC,xC,mC;var PF=W(()=>{nF();zD=bD("workers",{id:n("id").primaryKey(),soulId:n("soul_id").notNull(),name:n("name").notNull(),status:n("status",{enum:["active","paused","disabled"]}).notNull().default("active"),defaultEngineId:n("default_engine_id"),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({soulIdx:uD("workers_soul_idx").on(D.soulId),statusUpdatedAtIdx:uD("workers_status_updated_at_idx").on(D.status,D.updatedAt)})),jD=bD("workspaces",{id:n("id").primaryKey(),workerId:n("worker_id").notNull().references(()=>zD.id,{onDelete:"cascade"}),name:n("name").notNull(),rootPath:n("root_path").notNull(),type:n("type").notNull().default("workspace"),status:n("status",{enum:["active","archived"]}).notNull().default("active"),sourcePointersJson:n("source_pointers_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({rootPathIdx:p0("workspaces_root_path_idx").on(D.rootPath),statusUpdatedAtIdx:uD("workspaces_status_updated_at_idx").on(D.status,D.updatedAt),workerUpdatedAtIdx:uD("workspaces_worker_updated_at_idx").on(D.workerId,D.updatedAt)})),TD=bD("sessions",{id:n("id").primaryKey(),workerId:n("worker_id").notNull().references(()=>zD.id,{onDelete:"cascade"}),workspaceId:n("workspace_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),capabilityTemplateId:n("capability_template_id").notNull(),title:n("title").notNull(),context:n("context").notNull().default(""),status:n("status",{enum:["active","completed","failed","cancelled"]}).notNull().default("active"),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),startedAt:n("started_at"),endedAt:n("ended_at"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({capabilityUpdatedAtIdx:uD("sessions_capability_updated_at_idx").on(D.capabilityTemplateId,D.updatedAt),statusUpdatedAtIdx:uD("sessions_status_updated_at_idx").on(D.status,D.updatedAt),workerUpdatedAtIdx:uD("sessions_worker_updated_at_idx").on(D.workerId,D.updatedAt),workspaceUpdatedAtIdx:uD("sessions_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),OD=bD("turns",{id:n("id").primaryKey(),sessionId:n("session_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),seq:Hu("seq").notNull(),input:n("input").notNull(),response:n("response"),status:n("status",{enum:["queued","running","succeeded","failed","cancelled"]}).notNull().default("queued"),error:n("error"),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({sessionSeqIdx:uD("turns_session_seq_idx").on(D.sessionId,D.seq),sessionSeqUniqueIdx:p0("turns_session_seq_unique_idx").on(D.sessionId,D.seq),statusUpdatedAtIdx:uD("turns_status_updated_at_idx").on(D.status,D.updatedAt)})),KD=bD("engine_invocations",{id:n("id").primaryKey(),sessionId:n("session_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),turnId:n("turn_id").notNull().references(()=>OD.id,{onDelete:"cascade"}),seq:Hu("seq").notNull(),engineId:n("engine_id").notNull(),engineCommand:n("engine_command"),status:n("status",{enum:["queued","running","succeeded","failed","cancelled"]}).notNull().default("queued"),prompt:n("prompt").notNull(),summary:n("summary"),error:n("error"),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),startedAt:n("started_at"),finishedAt:n("finished_at"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({engineUpdatedAtIdx:uD("engine_invocations_engine_updated_at_idx").on(D.engineId,D.updatedAt),sessionSeqIdx:uD("engine_invocations_session_seq_idx").on(D.sessionId,D.seq),statusUpdatedAtIdx:uD("engine_invocations_status_updated_at_idx").on(D.status,D.updatedAt),turnIdx:uD("engine_invocations_turn_idx").on(D.turnId)})),tD=bD("session_events",{id:Hu("id").primaryKey({autoIncrement:!0}),sessionId:n("session_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),turnId:n("turn_id").references(()=>OD.id,{onDelete:"set null"}),invocationId:n("invocation_id").references(()=>KD.id,{onDelete:"set null"}),seq:Hu("seq").notNull(),type:n("type",{enum:["status","assistant_delta","tool","file_change","artifact","review","lesson","error","log"]}).notNull(),payloadJson:n("payload_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D)},(D)=>({sessionCreatedAtIdx:uD("session_events_session_created_at_idx").on(D.sessionId,D.createdAt),sessionSeqIdx:uD("session_events_session_seq_idx").on(D.sessionId,D.seq),sessionSeqUniqueIdx:p0("session_events_session_seq_unique_idx").on(D.sessionId,D.seq)})),Au=bD("files",{id:n("id").primaryKey(),workspaceId:n("workspace_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),path:n("path").notNull(),kind:n("kind",{enum:["file","directory","generated","uploaded"]}).notNull().default("file"),size:Hu("size"),mtime:Hu("mtime"),hash:n("hash"),source:n("source",{enum:["user","session","system"]}).notNull().default("user"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({kindIdx:uD("files_kind_idx").on(D.kind),pathUniqueIdx:p0("files_workspace_path_idx").on(D.workspaceId,D.path),workspaceUpdatedAtIdx:uD("files_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),Fr=bD("artifacts",{id:n("id").primaryKey(),workspaceId:n("workspace_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),sessionId:n("session_id").references(()=>TD.id,{onDelete:"set null"}),turnId:n("turn_id").references(()=>OD.id,{onDelete:"set null"}),invocationId:n("invocation_id").references(()=>KD.id,{onDelete:"set null"}),path:n("path").notNull(),kind:n("kind").notNull().default("file"),title:n("title").notNull(),status:n("status",{enum:["available","missing","archived"]}).notNull().default("available"),metadataJson:n("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({sessionUpdatedAtIdx:uD("artifacts_session_updated_at_idx").on(D.sessionId,D.updatedAt),statusUpdatedAtIdx:uD("artifacts_status_updated_at_idx").on(D.status,D.updatedAt),workspaceUpdatedAtIdx:uD("artifacts_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),wr=bD("reviews",{id:n("id").primaryKey(),workspaceId:n("workspace_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),sessionId:n("session_id").references(()=>TD.id,{onDelete:"set null"}),turnId:n("turn_id").references(()=>OD.id,{onDelete:"set null"}),artifactId:n("artifact_id").references(()=>Fr.id,{onDelete:"set null"}),verdict:n("verdict",{enum:["pass","warn","fail","needs_review"]}).notNull().default("needs_review"),findingsJson:n("findings_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),risksJson:n("risks_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),createdAt:n("created_at").notNull().$defaultFn($D)},(D)=>({artifactCreatedAtIdx:uD("reviews_artifact_created_at_idx").on(D.artifactId,D.createdAt),sessionCreatedAtIdx:uD("reviews_session_created_at_idx").on(D.sessionId,D.createdAt),workspaceCreatedAtIdx:uD("reviews_workspace_created_at_idx").on(D.workspaceId,D.createdAt)})),Lu=bD("lessons",{id:n("id").primaryKey(),workspaceId:n("workspace_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),sourceReviewId:n("source_review_id").references(()=>wr.id,{onDelete:"set null"}),statement:n("statement").notNull(),evidenceJson:n("evidence_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),status:n("status",{enum:["proposed","accepted","rejected"]}).notNull().default("proposed"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({statusUpdatedAtIdx:uD("lessons_status_updated_at_idx").on(D.status,D.updatedAt),workspaceUpdatedAtIdx:uD("lessons_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),Su=bD("soul_apps",{id:n("id").primaryKey(),name:n("name").notNull(),version:n("version").notNull(),protocol:n("protocol").notNull(),soulId:n("soul_id").notNull(),status:n("status",{enum:["installed","enabled","disabled","error"]}).$type().notNull().default("installed"),sourceKind:n("source_kind",{enum:["manifest-path","inline"]}).$type().notNull(),sourceRef:n("source_ref").notNull(),manifestDigest:n("manifest_digest").notNull(),manifestJson:n("manifest_json",{mode:"json"}).$type().notNull(),validationIssuesJson:n("validation_issues_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),healthStatus:n("health_status",{enum:["unknown","pass","warn","fail"]}).$type().notNull().default("unknown"),healthMessage:n("health_message"),installedAt:n("installed_at").notNull().$defaultFn($D),enabledAt:n("enabled_at"),disabledAt:n("disabled_at"),lastHealthcheckAt:n("last_healthcheck_at"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({digestIdx:uD("soul_apps_manifest_digest_idx").on(D.manifestDigest),soulIdx:uD("soul_apps_soul_idx").on(D.soulId),statusUpdatedAtIdx:uD("soul_apps_status_updated_at_idx").on(D.status,D.updatedAt)})),qu=bD("soul_app_storage_records",{id:n("id").primaryKey(),appId:n("app_id").notNull().references(()=>Su.id,{onDelete:"cascade"}),namespace:n("namespace").notNull(),key:n("key").notNull(),valueJson:n("value_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),workerId:n("worker_id").references(()=>zD.id,{onDelete:"set null"}),workspaceId:n("workspace_id").references(()=>jD.id,{onDelete:"set null"}),sessionId:n("session_id").references(()=>TD.id,{onDelete:"set null"}),operatorId:n("operator_id"),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)},(D)=>({appKeyIdx:p0("soul_app_storage_app_key_idx").on(D.appId,D.key),appUpdatedAtIdx:uD("soul_app_storage_app_updated_at_idx").on(D.appId,D.updatedAt),namespaceIdx:uD("soul_app_storage_namespace_idx").on(D.namespace),workspaceIdx:uD("soul_app_storage_workspace_idx").on(D.workspaceId)})),$r=bD("soul_app_audit_events",{id:Hu("id").primaryKey({autoIncrement:!0}),appId:n("app_id").notNull().references(()=>Su.id,{onDelete:"cascade"}),action:n("action").notNull(),targetKind:n("target_kind").notNull(),target:n("target").notNull(),decision:n("decision",{enum:["allowed","denied"]}).notNull(),reason:n("reason").notNull(),workerId:n("worker_id").references(()=>zD.id,{onDelete:"set null"}),workspaceId:n("workspace_id").references(()=>jD.id,{onDelete:"set null"}),sessionId:n("session_id").references(()=>TD.id,{onDelete:"set null"}),operatorId:n("operator_id"),requestJson:n("request_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:n("created_at").notNull().$defaultFn($D)},(D)=>({appCreatedAtIdx:uD("soul_app_audit_app_created_at_idx").on(D.appId,D.createdAt),contextIdx:uD("soul_app_audit_context_idx").on(D.workspaceId,D.sessionId),targetIdx:uD("soul_app_audit_target_idx").on(D.targetKind,D.target)})),hr=bD("settings",{key:n("key").primaryKey(),valueJson:n("value_json",{mode:"json"}).$type().notNull(),updatedAt:n("updated_at").notNull().$defaultFn($D)}),tC=bD("worker_identity",{pk:n("pk").primaryKey().default("default"),workerId:n("worker_id").notNull().unique(),apiTokenEnc:n("api_token_enc").notNull(),nonce:n("nonce").notNull(),authTag:n("auth_tag").notNull(),bootstrapShownAt:n("bootstrap_shown_at").notNull().$defaultFn($D),createdAt:n("created_at").notNull().$defaultFn($D),rotatedAt:n("rotated_at")}),xC=bD("worker_config",{pk:n("pk").primaryKey().default("default"),configJson:n("config_json",{mode:"json"}).$type().notNull(),version:Hu("version").notNull().default(1),updatedAt:n("updated_at").notNull().$defaultFn($D),updatedBy:n("updated_by",{enum:["bootstrap","api","cli"]})}),mC=bD("worker_secrets",{id:Hu("id").primaryKey({autoIncrement:!0}),key:n("key").notNull().unique(),valueEnc:n("value_enc").notNull(),nonce:n("nonce").notNull(),authTag:n("auth_tag").notNull(),createdAt:n("created_at").notNull().$defaultFn($D),updatedAt:n("updated_at").notNull().$defaultFn($D)})});import{existsSync as T4}from"fs";import iF from"path";import{fileURLToPath as pC}from"url";import{Database as aC}from"bun:sqlite";function eC(D){let u=iF.resolve(v4,"../../drizzle",D);if(T4(u))return u;let r=iF.resolve(v4,"drizzle",D);if(T4(r))return r;return u}function DH(D){let u=new aC(D,{create:!0});return u.exec("PRAGMA journal_mode = WAL"),u.exec("PRAGMA foreign_keys = ON"),B8(u,{schema:OF})}function W1(D){return J1=DH(D),J1}function j(){if(!J1)throw Error("Worker database not initialized. Call initWorkerDb() first.");return J1}function u2(){J1=null}function G1(D=KF){z4(j(),{migrationsFolder:D}),uH()}function uH(){let u=j().all(C.raw('PRAGMA index_list("workers")')).find((r)=>r.name==="workers_soul_idx");if(u?.unique===1)j().run(C.raw("DROP INDEX IF EXISTS workers_soul_idx"));if(!u||u.unique===1)j().run(C.raw("CREATE INDEX IF NOT EXISTS workers_soul_idx ON workers (soul_id)"))}function r2(D){let u=D.at??new Date().toISOString(),r=PD(D.id);if(!r)j().insert(zD).values({id:D.id,soulId:D.soulId,name:D.name,status:D.status??"active",defaultEngineId:D.defaultEngineId??null,metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run();else j().update(zD).set({defaultEngineId:D.defaultEngineId??r.defaultEngineId,metadataJson:D.metadataJson??r.metadataJson,name:D.name,soulId:D.soulId,status:D.status??r.status,updatedAt:u}).where(d(zD.id,D.id)).run();return PD(D.id)}function PD(D){return j().select().from(zD).where(d(zD.id,D)).get()??null}function Er(D=100){return j().select().from(zD).orderBy(zD.id).limit(D).all()}function Z4(D){let u=D.at??new Date().toISOString();return j().insert(jD).values({id:D.id,workerId:D.workerId,name:D.name,rootPath:D.rootPath,type:D.type??"workspace",status:D.status??"active",sourcePointersJson:D.sourcePointersJson??[],metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),pD(D.id)}function pD(D){return j().select().from(jD).where(d(jD.id,D)).get()??null}function hF(D){let u=pD(D.id);if(!u)throw Error(`Workspace not found: ${D.id}`);return j().update(jD).set({metadataJson:D.metadataJson??u.metadataJson,name:D.name??u.name,sourcePointersJson:D.sourcePointersJson??u.sourcePointersJson,status:D.status??u.status,updatedAt:D.at??new Date().toISOString()}).where(d(jD.id,D.id)).run(),pD(D.id)}function nu(D,u=200){let r=j().select().from(jD);if(D)return r.where(d(jD.workerId,D)).orderBy(GD(jD.updatedAt)).limit(u).all();return r.orderBy(GD(jD.updatedAt)).limit(u).all()}function o4(D){let u=D.at??new Date().toISOString();return j().insert(TD).values({id:D.id,workerId:D.workerId,workspaceId:D.workspaceId,capabilityTemplateId:D.capabilityTemplateId,title:D.title,context:D.context??"",status:D.status??"active",metadataJson:D.metadataJson??{},startedAt:D.startedAt??u,endedAt:D.endedAt??null,createdAt:u,updatedAt:u}).run(),fu(D.id)}function fu(D){return j().select().from(TD).where(d(TD.id,D)).get()??null}function NF(D){let u=fu(D.id);if(!u)throw Error(`Session not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return j().update(TD).set({context:D.context??u.context,endedAt:r("endedAt")?D.endedAt??null:u.endedAt,metadataJson:D.metadataJson??u.metadataJson,startedAt:r("startedAt")?D.startedAt??null:u.startedAt,status:D.status??u.status,title:D.title??u.title,updatedAt:D.at??new Date().toISOString()}).where(d(TD.id,D.id)).run(),fu(D.id)}function tr(D,u=200){let r=j().select().from(TD);if(D)return r.where(d(TD.workspaceId,D)).orderBy(GD(TD.updatedAt)).limit(u).all();return r.orderBy(GD(TD.updatedAt)).limit(u).all()}function d4(D){let u=[...new Set(D.soulIds)].sort(),r=0;for(let A of u){let f=j().select({id:zD.id}).from(zD).where(d(zD.soulId,A)).all();if(f.length===0)continue;j().delete(zD).where(d(zD.soulId,A)).run(),r+=f.length}return{legacySoulIds:u,workersDeleted:r}}function y4(D){let u=D.at??new Date().toISOString();return j().insert(OD).values({id:D.id,sessionId:D.sessionId,seq:D.seq,input:D.input,response:D.response??null,status:D.status??"queued",error:D.error??null,metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),kF(D.id)}function kF(D){return j().select().from(OD).where(d(OD.id,D)).get()??null}function QF(D){let u=kF(D.id);if(!u)throw Error(`Turn not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return j().update(OD).set({error:r("error")?D.error??null:u.error,metadataJson:D.metadataJson??u.metadataJson,response:r("response")?D.response??null:u.response,status:D.status??u.status,updatedAt:D.at??new Date().toISOString()}).where(d(OD.id,D.id)).run(),kF(D.id)}function gr(D,u=200){let r=j().select().from(OD);if(D)return r.where(d(OD.sessionId,D)).orderBy(OD.seq).limit(u).all();return r.orderBy(GD(OD.updatedAt)).limit(u).all()}function l4(D){return(j().select({seq:OD.seq}).from(OD).where(d(OD.sessionId,D)).orderBy(GD(OD.seq)).limit(1).get()?.seq??0)+1}function c4(D){let u=D.at??new Date().toISOString();return j().insert(KD).values({id:D.id,sessionId:D.sessionId,turnId:D.turnId,seq:D.seq,engineId:D.engineId,engineCommand:D.engineCommand??null,status:D.status??"queued",prompt:D.prompt,summary:D.summary??null,error:D.error??null,metadataJson:D.metadataJson??{},startedAt:D.startedAt??null,finishedAt:D.finishedAt??null,createdAt:u,updatedAt:u}).run(),IF(D.id)}function IF(D){return j().select().from(KD).where(d(KD.id,D)).get()??null}function LF(D){let u=IF(D.id);if(!u)throw Error(`Engine invocation not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return j().update(KD).set({error:r("error")?D.error??null:u.error,finishedAt:r("finishedAt")?D.finishedAt??null:u.finishedAt,metadataJson:D.metadataJson??u.metadataJson,startedAt:r("startedAt")?D.startedAt??null:u.startedAt,status:D.status??u.status,summary:r("summary")?D.summary??null:u.summary,updatedAt:D.at??new Date().toISOString()}).where(d(KD.id,D.id)).run(),IF(D.id)}function t4(D,u=200){let r=j().select().from(KD);if(D)return r.where(d(KD.sessionId,D)).orderBy(GD(KD.updatedAt)).limit(u).all();return r.orderBy(GD(KD.updatedAt)).limit(u).all()}function x4(D){return(j().select({seq:KD.seq}).from(KD).where(d(KD.sessionId,D)).orderBy(GD(KD.seq)).limit(1).get()?.seq??0)+1}function m4(D){return j().insert(tD).values({sessionId:D.sessionId,turnId:D.turnId??null,invocationId:D.invocationId??null,seq:D.seq,type:D.type,payloadJson:D.payloadJson??{},createdAt:D.at??new Date().toISOString()}).run(),j().select().from(tD).where(Kr(d(tD.sessionId,D.sessionId),d(tD.seq,D.seq))).get()}function p4(D){return(j().select({seq:tD.seq}).from(tD).where(d(tD.sessionId,D)).orderBy(GD(tD.seq)).limit(1).get()?.seq??0)+1}function _r(D,u=500){let r=j().select().from(tD);if(D)return r.where(d(tD.sessionId,D)).orderBy(tD.seq).limit(u).all();return r.orderBy(GD(tD.createdAt)).limit(u).all()}function C1(D){let u=D.at??new Date().toISOString(),r=j().select().from(Au).where(Kr(d(Au.workspaceId,D.workspaceId),d(Au.path,D.path))).get();if(!r)j().insert(Au).values({id:D.id,workspaceId:D.workspaceId,path:D.path,kind:D.kind??"file",size:D.size??null,mtime:D.mtime??null,hash:D.hash??null,source:D.source??"user",createdAt:u,updatedAt:u}).run();else j().update(Au).set({kind:D.kind??r.kind,size:D.size??r.size,mtime:D.mtime??r.mtime,hash:D.hash??r.hash,source:D.source??r.source,updatedAt:u}).where(d(Au.id,r.id)).run();return j().select().from(Au).where(d(Au.id,r?.id??D.id)).get()}function bu(D,u=500){let r=j().select().from(Au);if(D)return r.where(d(Au.workspaceId,D)).orderBy(GD(Au.updatedAt)).limit(u).all();return r.orderBy(GD(Au.updatedAt)).limit(u).all()}function a4(D){let u=D.at??new Date().toISOString();return j().insert(Fr).values({id:D.id,workspaceId:D.workspaceId,sessionId:D.sessionId??null,turnId:D.turnId??null,invocationId:D.invocationId??null,path:D.path,kind:D.kind??"file",title:D.title,status:D.status??"available",metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),xr(D.id)}function xr(D){return j().select().from(Fr).where(d(Fr.id,D)).get()??null}function Rr(D,u=200){let r=j().select().from(Fr);if(D)return r.where(d(Fr.workspaceId,D)).orderBy(GD(Fr.updatedAt)).limit(u).all();return r.orderBy(GD(Fr.updatedAt)).limit(u).all()}function i0(D){return j().insert(wr).values({id:D.id,workspaceId:D.workspaceId,sessionId:D.sessionId??null,turnId:D.turnId??null,artifactId:D.artifactId??null,verdict:D.verdict??"needs_review",findingsJson:D.findingsJson??[],risksJson:D.risksJson??[],createdAt:D.at??new Date().toISOString()}).run(),H1(D.id)}function H1(D){return j().select().from(wr).where(d(wr.id,D)).get()??null}function A2(D,u=200){let r=j().select().from(wr);if(D)return r.where(d(wr.workspaceId,D)).orderBy(GD(wr.createdAt)).limit(u).all();return r.orderBy(GD(wr.createdAt)).limit(u).all()}function mr(D){let u=D.at??new Date().toISOString();return j().insert(Lu).values({id:D.id,workspaceId:D.workspaceId,sourceReviewId:D.sourceReviewId??null,statement:D.statement,evidenceJson:D.evidenceJson??[],status:D.status??"proposed",createdAt:u,updatedAt:u}).run(),VF(D.id)}function VF(D){return j().select().from(Lu).where(d(Lu.id,D)).get()??null}function n1(D,u,r=new Date().toISOString()){if(!VF(D))throw Error(`Lesson not found: ${D}`);return j().update(Lu).set({status:u,updatedAt:r}).where(d(Lu.id,D)).run(),VF(D)}function f2(D,u=200){let r=j().select().from(Lu);if(D)return r.where(d(Lu.workspaceId,D)).orderBy(GD(Lu.updatedAt)).limit(u).all();return r.orderBy(GD(Lu.updatedAt)).limit(u).all()}function e4(D){let u=D.at??new Date().toISOString(),r=P0(D.id),A=D.status??r?.status??"installed",f=D.enabledAt??(A==="enabled"?r?.enabledAt??u:r?.enabledAt??null),w=D.disabledAt??(A==="disabled"?u:r?.disabledAt??null);if(!r)j().insert(Su).values({id:D.id,name:D.name,version:D.version,protocol:D.protocol,soulId:D.soulId,status:A,sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:D.manifestDigest,manifestJson:D.manifestJson,validationIssuesJson:D.validationIssuesJson??[],healthStatus:D.healthStatus??"unknown",healthMessage:D.healthMessage??null,installedAt:D.installedAt??u,enabledAt:f,disabledAt:w,lastHealthcheckAt:D.lastHealthcheckAt??null,createdAt:u,updatedAt:u}).run();else j().update(Su).set({name:D.name,version:D.version,protocol:D.protocol,soulId:D.soulId,status:A,sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:D.manifestDigest,manifestJson:D.manifestJson,validationIssuesJson:D.validationIssuesJson??r.validationIssuesJson,healthStatus:D.healthStatus??r.healthStatus,healthMessage:Object.hasOwn(D,"healthMessage")?D.healthMessage??null:r.healthMessage,installedAt:D.installedAt??r.installedAt,enabledAt:f,disabledAt:w,lastHealthcheckAt:D.lastHealthcheckAt??r.lastHealthcheckAt,updatedAt:u}).where(d(Su.id,D.id)).run();return P0(D.id)}function P0(D){return j().select().from(Su).where(d(Su.id,D)).get()??null}function qF(D=200){return j().select().from(Su).orderBy(Su.id).limit(D).all()}function F2(D){let u=P0(D.id);if(!u)throw Error(`Soul App not found: ${D.id}`);let r=D.at??new Date().toISOString();return j().update(Su).set({disabledAt:D.status==="disabled"?r:u.disabledAt,enabledAt:D.status==="enabled"?r:u.enabledAt,healthMessage:Object.hasOwn(D,"healthMessage")?D.healthMessage??null:u.healthMessage,healthStatus:D.healthStatus??u.healthStatus,lastHealthcheckAt:D.lastHealthcheckAt??u.lastHealthcheckAt,status:D.status,updatedAt:r,validationIssuesJson:D.validationIssuesJson??u.validationIssuesJson}).where(d(Su.id,D.id)).run(),P0(D.id)}function DE(D){let u=D.at??new Date().toISOString(),r=J8(D.appId,D.key);if(!r)j().insert(qu).values({appId:D.appId,createdAt:u,id:rH(D.appId,D.key),key:D.key,namespace:D.namespace,operatorId:D.operatorId??null,sessionId:D.sessionId??null,updatedAt:u,valueJson:D.valueJson,workerId:D.workerId??null,workspaceId:D.workspaceId??null}).run();else j().update(qu).set({namespace:D.namespace,operatorId:D.operatorId??r.operatorId,sessionId:D.sessionId??r.sessionId,updatedAt:u,valueJson:D.valueJson,workerId:D.workerId??r.workerId,workspaceId:D.workspaceId??r.workspaceId}).where(d(qu.id,r.id)).run();return J8(D.appId,D.key)}function J8(D,u){return j().select().from(qu).where(Kr(d(qu.appId,D),d(qu.key,u))).get()??null}function uE(D,u=200){return j().select().from(qu).where(d(qu.appId,D)).orderBy(GD(qu.updatedAt)).limit(u).all()}function rE(D){return j().insert($r).values({action:D.action,appId:D.appId,createdAt:D.at??new Date().toISOString(),decision:D.decision,operatorId:D.operatorId??null,reason:D.reason,requestJson:D.requestJson??{},sessionId:D.sessionId??null,target:D.target,targetKind:D.targetKind,workerId:D.workerId??null,workspaceId:D.workspaceId??null}).run(),j().select().from($r).where(d($r.appId,D.appId)).orderBy(GD($r.id)).limit(1).get()}function AE(D,u=500){let r=j().select().from($r);if(D)return r.where(d($r.appId,D)).orderBy($r.id).limit(u).all();return r.orderBy($r.id).limit(u).all()}function rH(D,u){return`${D}:${u}`}function s4(D){return j().select().from(hr).where(d(hr.key,D)).get()??null}function pr(){return j().select().from(hr).orderBy(hr.key).all()}function k0(D,u,r=new Date().toISOString()){if(!s4(D))j().insert(hr).values({key:D,valueJson:u,updatedAt:r}).run();else j().update(hr).set({valueJson:u,updatedAt:r}).where(d(hr.key,D)).run();return s4(D)}var v4,KF,J1=null;var Sr=W(()=>{K5();L4();j4();PF();PF();v4=iF.dirname(pC(import.meta.url));KF=eC("worker")});var DD,bF,K,Br=(D)=>{switch(typeof D){case"undefined":return K.undefined;case"string":return K.string;case"number":return Number.isNaN(D)?K.nan:K.number;case"boolean":return K.boolean;case"function":return K.function;case"bigint":return K.bigint;case"symbol":return K.symbol;case"object":if(Array.isArray(D))return K.array;if(D===null)return K.null;if(D.then&&typeof D.then==="function"&&D.catch&&typeof D.catch==="function")return K.promise;if(typeof Map<"u"&&D instanceof Map)return K.map;if(typeof Set<"u"&&D instanceof Set)return K.set;if(typeof Date<"u"&&D instanceof Date)return K.date;return K.object;default:return K.unknown}};var U1=W(()=>{(function(D){D.assertEqual=(f)=>{};function u(f){}D.assertIs=u;function r(f){throw Error()}D.assertNever=r,D.arrayToEnum=(f)=>{let w={};for(let F of f)w[F]=F;return w},D.getValidEnumValues=(f)=>{let w=D.objectKeys(f).filter((E)=>typeof f[f[E]]!=="number"),F={};for(let E of w)F[E]=f[E];return D.objectValues(F)},D.objectValues=(f)=>{return D.objectKeys(f).map(function(w){return f[w]})},D.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{let w=[];for(let F in f)if(Object.prototype.hasOwnProperty.call(f,F))w.push(F);return w},D.find=(f,w)=>{for(let F of f)if(w(F))return F;return},D.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&Number.isFinite(f)&&Math.floor(f)===f;function A(f,w=" | "){return f.map((F)=>typeof F==="string"?`'${F}'`:F).join(w)}D.joinValues=A,D.jsonStringifyReplacer=(f,w)=>{if(typeof w==="bigint")return w.toString();return w}})(DD||(DD={}));(function(D){D.mergeShapes=(u,r)=>{return{...u,...r}}})(bF||(bF={}));K=DD.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var P,AH=(D)=>{return JSON.stringify(D,null,2).replace(/"([^"]+)":/g,"$1:")},Fu;var W8=W(()=>{U1();P=DD.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);Fu=class Fu extends Error{get errors(){return this.issues}constructor(D){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let u=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,u);else this.__proto__=u;this.name="ZodError",this.issues=D}format(D){let u=D||function(f){return f.message},r={_errors:[]},A=(f)=>{for(let w of f.issues)if(w.code==="invalid_union")w.unionErrors.map(A);else if(w.code==="invalid_return_type")A(w.returnTypeError);else if(w.code==="invalid_arguments")A(w.argumentsError);else if(w.path.length===0)r._errors.push(u(w));else{let F=r,E=0;while(E<w.path.length){let $=w.path[E];if(E!==w.path.length-1)F[$]=F[$]||{_errors:[]};else F[$]=F[$]||{_errors:[]},F[$]._errors.push(u(w));F=F[$],E++}}};return A(this),r}static assert(D){if(!(D instanceof Fu))throw Error(`Not a ZodError: ${D}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,DD.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(D=(u)=>u.message){let u={},r=[];for(let A of this.issues)if(A.path.length>0){let f=A.path[0];u[f]=u[f]||[],u[f].push(D(A))}else r.push(D(A));return{formErrors:r,fieldErrors:u}}get formErrors(){return this.flatten()}};Fu.create=(D)=>{return new Fu(D)}});var fH=(D,u)=>{let r;switch(D.code){case P.invalid_type:if(D.received===K.undefined)r="Required";else r=`Expected ${D.expected}, received ${D.received}`;break;case P.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(D.expected,DD.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:r=`Unrecognized key(s) in object: ${DD.joinValues(D.keys,", ")}`;break;case P.invalid_union:r="Invalid input";break;case P.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${DD.joinValues(D.options)}`;break;case P.invalid_enum_value:r=`Invalid enum value. Expected ${DD.joinValues(D.options)}, received '${D.received}'`;break;case P.invalid_arguments:r="Invalid function arguments";break;case P.invalid_return_type:r="Invalid function return type";break;case P.invalid_date:r="Invalid date";break;case P.invalid_string:if(typeof D.validation==="object")if("includes"in D.validation){if(r=`Invalid input: must include "${D.validation.includes}"`,typeof D.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${D.validation.position}`}else if("startsWith"in D.validation)r=`Invalid input: must start with "${D.validation.startsWith}"`;else if("endsWith"in D.validation)r=`Invalid input: must end with "${D.validation.endsWith}"`;else DD.assertNever(D.validation);else if(D.validation!=="regex")r=`Invalid ${D.validation}`;else r="Invalid";break;case P.too_small:if(D.type==="array")r=`Array must contain ${D.exact?"exactly":D.inclusive?"at least":"more than"} ${D.minimum} element(s)`;else if(D.type==="string")r=`String must contain ${D.exact?"exactly":D.inclusive?"at least":"over"} ${D.minimum} character(s)`;else if(D.type==="number")r=`Number must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${D.minimum}`;else if(D.type==="bigint")r=`Number must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${D.minimum}`;else if(D.type==="date")r=`Date must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(D.minimum))}`;else r="Invalid input";break;case P.too_big:if(D.type==="array")r=`Array must contain ${D.exact?"exactly":D.inclusive?"at most":"less than"} ${D.maximum} element(s)`;else if(D.type==="string")r=`String must contain ${D.exact?"exactly":D.inclusive?"at most":"under"} ${D.maximum} character(s)`;else if(D.type==="number")r=`Number must be ${D.exact?"exactly":D.inclusive?"less than or equal to":"less than"} ${D.maximum}`;else if(D.type==="bigint")r=`BigInt must be ${D.exact?"exactly":D.inclusive?"less than or equal to":"less than"} ${D.maximum}`;else if(D.type==="date")r=`Date must be ${D.exact?"exactly":D.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(D.maximum))}`;else r="Invalid input";break;case P.custom:r="Invalid input";break;case P.invalid_intersection_types:r="Intersection results could not be merged";break;case P.not_multiple_of:r=`Number must be a multiple of ${D.multipleOf}`;break;case P.not_finite:r="Number must be finite";break;default:r=u.defaultError,DD.assertNever(D)}return{message:r}},Nr;var zF=W(()=>{W8();U1();Nr=fH});function FH(D){fE=D}function w2(){return fE}var fE;var G8=W(()=>{zF();fE=Nr});function N(D,u){let r=w2(),A=X1({issueData:u,data:D.data,path:D.path,errorMaps:[D.common.contextualErrorMap,D.schemaErrorMap,r,r===Nr?void 0:Nr].filter((f)=>!!f)});D.common.issues.push(A)}class dD{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(D,u){let r=[];for(let A of u){if(A.status==="aborted")return o;if(A.status==="dirty")D.dirty();r.push(A.value)}return{status:D.value,value:r}}static async mergeObjectAsync(D,u){let r=[];for(let A of u){let f=await A.key,w=await A.value;r.push({key:f,value:w})}return dD.mergeObjectSync(D,r)}static mergeObjectSync(D,u){let r={};for(let A of u){let{key:f,value:w}=A;if(f.status==="aborted")return o;if(w.status==="aborted")return o;if(f.status==="dirty")D.dirty();if(w.status==="dirty")D.dirty();if(f.value!=="__proto__"&&(typeof w.value<"u"||A.alwaysSet))r[f.value]=w.value}return{status:D.value,value:r}}}var X1=(D)=>{let{data:u,path:r,errorMaps:A,issueData:f}=D,w=[...r,...f.path||[]],F={...f,path:w};if(f.message!==void 0)return{...f,path:w,message:f.message};let E="",$=A.filter((g)=>!!g).slice().reverse();for(let g of $)E=g(F,{data:u,defaultError:E}).message;return{...f,path:w,message:E}},wH,o,I0=(D)=>({status:"dirty",value:D}),xD=(D)=>({status:"valid",value:D}),C8=(D)=>D.status==="aborted",H8=(D)=>D.status==="dirty",ar=(D)=>D.status==="valid",$2=(D)=>typeof Promise<"u"&&D instanceof Promise;var jF=W(()=>{G8();zF();wH=[];o=Object.freeze({status:"aborted"})});var FE=()=>{};var T;var wE=W(()=>{(function(D){D.errToObj=(u)=>typeof u==="string"?{message:u}:u||{},D.toString=(u)=>typeof u==="string"?u:u?.message})(T||(T={}))});class vu{constructor(D,u,r,A){this._cachedPath=[],this.parent=D,this.data=u,this._path=r,this._key=A}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function t(D){if(!D)return{};let{errorMap:u,invalid_type_error:r,required_error:A,description:f}=D;if(u&&(r||A))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(u)return{errorMap:u,description:f};return{errorMap:(F,E)=>{let{message:$}=D;if(F.code==="invalid_enum_value")return{message:$??E.defaultError};if(typeof E.data>"u")return{message:$??A??E.defaultError};if(F.code!=="invalid_type")return{message:E.defaultError};return{message:$??r??E.defaultError}},description:f}}class x{get description(){return this._def.description}_getType(D){return Br(D.data)}_getOrReturnCtx(D,u){return u||{common:D.parent.common,data:D.data,parsedType:Br(D.data),schemaErrorMap:this._def.errorMap,path:D.path,parent:D.parent}}_processInputParams(D){return{status:new dD,ctx:{common:D.parent.common,data:D.data,parsedType:Br(D.data),schemaErrorMap:this._def.errorMap,path:D.path,parent:D.parent}}}_parseSync(D){let u=this._parse(D);if($2(u))throw Error("Synchronous parse encountered promise.");return u}_parseAsync(D){let u=this._parse(D);return Promise.resolve(u)}parse(D,u){let r=this.safeParse(D,u);if(r.success)return r.data;throw r.error}safeParse(D,u){let r={common:{issues:[],async:u?.async??!1,contextualErrorMap:u?.errorMap},path:u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)},A=this._parseSync({data:D,path:r.path,parent:r});return $E(r,A)}"~validate"(D){let u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)};if(!this["~standard"].async)try{let r=this._parseSync({data:D,path:[],parent:u});return ar(r)?{value:r.value}:{issues:u.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;u.common={issues:[],async:!0}}return this._parseAsync({data:D,path:[],parent:u}).then((r)=>ar(r)?{value:r.value}:{issues:u.common.issues})}async parseAsync(D,u){let r=await this.safeParseAsync(D,u);if(r.success)return r.data;throw r.error}async safeParseAsync(D,u){let r={common:{issues:[],contextualErrorMap:u?.errorMap,async:!0},path:u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)},A=this._parse({data:D,path:r.path,parent:r}),f=await($2(A)?A:Promise.resolve(A));return $E(r,f)}refine(D,u){let r=(A)=>{if(typeof u==="string"||typeof u>"u")return{message:u};else if(typeof u==="function")return u(A);else return u};return this._refinement((A,f)=>{let w=D(A),F=()=>f.addIssue({code:P.custom,...r(A)});if(typeof Promise<"u"&&w instanceof Promise)return w.then((E)=>{if(!E)return F(),!1;else return!0});if(!w)return F(),!1;else return!0})}refinement(D,u){return this._refinement((r,A)=>{if(!D(r))return A.addIssue(typeof u==="function"?u(r,A):u),!1;else return!0})}_refinement(D){return new su({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:D}})}superRefine(D){return this._refinement(D)}constructor(D){this.spa=this.safeParseAsync,this._def=D,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(u)=>this["~validate"](u)}}optional(){return Tu.create(this,this._def)}nullable(){return Lr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ju.create(this)}promise(){return N0.create(this,this._def)}or(D){return B2.create([this,D],this._def)}and(D){return J2.create(this,D,this._def)}transform(D){return new su({...t(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:D}})}default(D){let u=typeof D==="function"?D:()=>D;return new H2({...t(this._def),innerType:this,defaultValue:u,typeName:y.ZodDefault})}brand(){return new U8({typeName:y.ZodBranded,type:this,...t(this._def)})}catch(D){let u=typeof D==="function"?D:()=>D;return new n2({...t(this._def),innerType:this,catchValue:u,typeName:y.ZodCatch})}describe(D){return new this.constructor({...this._def,description:D})}pipe(D){return k1.create(this,D)}readonly(){return U2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function _E(D){let u="[0-5]\\d";if(D.precision)u=`${u}\\.\\d{${D.precision}}`;else if(D.precision==null)u=`${u}(\\.\\d+)?`;let r=D.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${u})${r}`}function MH(D){return new RegExp(`^${_E(D)}$`)}function RE(D){let u=`${gE}T${_E(D)}`,r=[];if(r.push(D.local?"Z?":"Z"),D.offset)r.push("([+-]\\d{2}:?\\d{2})");return u=`${u}(${r.join("|")})`,new RegExp(`^${u}$`)}function OH(D,u){if((u==="v4"||!u)&&GH.test(D))return!0;if((u==="v6"||!u)&&HH.test(D))return!0;return!1}function PH(D,u){if(!SH.test(D))return!1;try{let[r]=D.split(".");if(!r)return!1;let A=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),f=JSON.parse(atob(A));if(typeof f!=="object"||f===null)return!1;if("typ"in f&&f?.typ!=="JWT")return!1;if(!f.alg)return!1;if(u&&f.alg!==u)return!1;return!0}catch{return!1}}function iH(D,u){if((u==="v4"||!u)&&CH.test(D))return!0;if((u==="v6"||!u)&&nH.test(D))return!0;return!1}function kH(D,u){let r=(D.toString().split(".")[1]||"").length,A=(u.toString().split(".")[1]||"").length,f=r>A?r:A,w=Number.parseInt(D.toFixed(f).replace(".","")),F=Number.parseInt(u.toFixed(f).replace(".",""));return w%F/10**f}function E2(D){if(D instanceof UD){let u={};for(let r in D.shape){let A=D.shape[r];u[r]=Tu.create(E2(A))}return new UD({...D._def,shape:()=>u})}else if(D instanceof ju)return new ju({...D._def,type:E2(D.element)});else if(D instanceof Tu)return Tu.create(E2(D.unwrap()));else if(D instanceof Lr)return Lr.create(E2(D.unwrap()));else if(D instanceof Wr)return Wr.create(D.items.map((u)=>E2(u)));else return D}function vF(D,u){let r=Br(D),A=Br(u);if(D===u)return{valid:!0,data:D};else if(r===K.object&&A===K.object){let f=DD.objectKeys(u),w=DD.objectKeys(D).filter((E)=>f.indexOf(E)!==-1),F={...D,...u};for(let E of w){let $=vF(D[E],u[E]);if(!$.valid)return{valid:!1};F[E]=$.data}return{valid:!0,data:F}}else if(r===K.array&&A===K.array){if(D.length!==u.length)return{valid:!1};let f=[];for(let w=0;w<D.length;w++){let F=D[w],E=u[w],$=vF(F,E);if(!$.valid)return{valid:!1};f.push($.data)}return{valid:!0,data:f}}else if(r===K.date&&A===K.date&&+D===+u)return{valid:!0,data:D};else return{valid:!1}}function SE(D,u){return new r0({values:D,typeName:y.ZodEnum,...t(u)})}function EE(D,u){let r=typeof D==="function"?D(u):typeof D==="string"?{message:D}:D;return typeof r==="string"?{message:r}:r}function BE(D,u={},r){if(D)return K0.create().superRefine((A,f)=>{let w=D(A);if(w instanceof Promise)return w.then((F)=>{if(!F){let E=EE(u,A),$=E.fatal??r??!0;f.addIssue({code:"custom",...E,fatal:$})}});if(!w){let F=EE(u,A),E=F.fatal??r??!0;f.addIssue({code:"custom",...F,fatal:E})}return});return K0.create()}var $E=(D,u)=>{if(ar(u))return{success:!0,data:u.value};else{if(!D.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Fu(D.common.issues);return this._error=r,this._error}}}},$H,EH,gH,_H,RH,SH,BH,JH,WH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",TF,GH,CH,HH,nH,UH,XH,gE="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",YH,zu,D0,u0,_2,V0,Y1,R2,S2,K0,er,Jr,M1,ju,UD,B2,Qr=(D)=>{if(D instanceof W2)return Qr(D.schema);else if(D instanceof su)return Qr(D.innerType());else if(D instanceof G2)return[D.value];else if(D instanceof r0)return D.options;else if(D instanceof C2)return DD.objectValues(D.enum);else if(D instanceof H2)return Qr(D._def.innerType);else if(D instanceof R2)return[void 0];else if(D instanceof S2)return[null];else if(D instanceof Tu)return[void 0,...Qr(D.unwrap())];else if(D instanceof Lr)return[null,...Qr(D.unwrap())];else if(D instanceof U8)return Qr(D.unwrap());else if(D instanceof U2)return Qr(D.unwrap());else if(D instanceof n2)return Qr(D._def.innerType);else return[]},n8,J2,Wr,O1,P1,h0,g2,W2,G2,r0,C2,N0,su,Tu,Lr,H2,n2,i1,IH,U8,k1,U2,VH,y,KH=(D,u={message:`Input not instance of ${D.name}`})=>BE((r)=>r instanceof D,u),JE,WE,hH,NH,GE,QH,LH,qH,bH,zH,jH,TH,vH,sH,ZH,oH,dH,yH,lH,cH,tH,xH,mH,pH,aH,eH,Dn,un,rn,An,fn,Fn,wn,$n,En=()=>JE().optional(),gn=()=>WE().optional(),_n=()=>GE().optional(),Rn,Sn;var CE=W(()=>{W8();G8();wE();jF();U1();$H=/^c[^\s-]{8,}$/i,EH=/^[0-9a-z]+$/,gH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_H=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,RH=/^[a-z0-9_-]{21}$/i,SH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,BH=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,JH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,GH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,CH=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,HH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nH=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,UH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,XH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YH=new RegExp(`^${gE}$`);zu=class zu extends x{_parse(D){if(this._def.coerce)D.data=String(D.data);if(this._getType(D)!==K.string){let f=this._getOrReturnCtx(D);return N(f,{code:P.invalid_type,expected:K.string,received:f.parsedType}),o}let r=new dD,A=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(D.data.length<f.value)A=this._getOrReturnCtx(D,A),N(A,{code:P.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),r.dirty()}else if(f.kind==="max"){if(D.data.length>f.value)A=this._getOrReturnCtx(D,A),N(A,{code:P.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),r.dirty()}else if(f.kind==="length"){let w=D.data.length>f.value,F=D.data.length<f.value;if(w||F){if(A=this._getOrReturnCtx(D,A),w)N(A,{code:P.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(F)N(A,{code:P.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});r.dirty()}}else if(f.kind==="email"){if(!JH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"email",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="emoji"){if(!TF)TF=new RegExp(WH,"u");if(!TF.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"emoji",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="uuid"){if(!_H.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"uuid",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="nanoid"){if(!RH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"nanoid",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cuid"){if(!$H.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"cuid",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cuid2"){if(!EH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"cuid2",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="ulid"){if(!gH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"ulid",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="url")try{new URL(D.data)}catch{A=this._getOrReturnCtx(D,A),N(A,{validation:"url",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"regex",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="trim")D.data=D.data.trim();else if(f.kind==="includes"){if(!D.data.includes(f.value,f.position))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),r.dirty()}else if(f.kind==="toLowerCase")D.data=D.data.toLowerCase();else if(f.kind==="toUpperCase")D.data=D.data.toUpperCase();else if(f.kind==="startsWith"){if(!D.data.startsWith(f.value))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:{startsWith:f.value},message:f.message}),r.dirty()}else if(f.kind==="endsWith"){if(!D.data.endsWith(f.value))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:{endsWith:f.value},message:f.message}),r.dirty()}else if(f.kind==="datetime"){if(!RE(f).test(D.data))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:"datetime",message:f.message}),r.dirty()}else if(f.kind==="date"){if(!YH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:"date",message:f.message}),r.dirty()}else if(f.kind==="time"){if(!MH(f).test(D.data))A=this._getOrReturnCtx(D,A),N(A,{code:P.invalid_string,validation:"time",message:f.message}),r.dirty()}else if(f.kind==="duration"){if(!BH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"duration",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="ip"){if(!OH(D.data,f.version))A=this._getOrReturnCtx(D,A),N(A,{validation:"ip",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="jwt"){if(!PH(D.data,f.alg))A=this._getOrReturnCtx(D,A),N(A,{validation:"jwt",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cidr"){if(!iH(D.data,f.version))A=this._getOrReturnCtx(D,A),N(A,{validation:"cidr",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="base64"){if(!UH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"base64",code:P.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="base64url"){if(!XH.test(D.data))A=this._getOrReturnCtx(D,A),N(A,{validation:"base64url",code:P.invalid_string,message:f.message}),r.dirty()}else DD.assertNever(f);return{status:r.value,value:D.data}}_regex(D,u,r){return this.refinement((A)=>D.test(A),{validation:u,code:P.invalid_string,...T.errToObj(r)})}_addCheck(D){return new zu({...this._def,checks:[...this._def.checks,D]})}email(D){return this._addCheck({kind:"email",...T.errToObj(D)})}url(D){return this._addCheck({kind:"url",...T.errToObj(D)})}emoji(D){return this._addCheck({kind:"emoji",...T.errToObj(D)})}uuid(D){return this._addCheck({kind:"uuid",...T.errToObj(D)})}nanoid(D){return this._addCheck({kind:"nanoid",...T.errToObj(D)})}cuid(D){return this._addCheck({kind:"cuid",...T.errToObj(D)})}cuid2(D){return this._addCheck({kind:"cuid2",...T.errToObj(D)})}ulid(D){return this._addCheck({kind:"ulid",...T.errToObj(D)})}base64(D){return this._addCheck({kind:"base64",...T.errToObj(D)})}base64url(D){return this._addCheck({kind:"base64url",...T.errToObj(D)})}jwt(D){return this._addCheck({kind:"jwt",...T.errToObj(D)})}ip(D){return this._addCheck({kind:"ip",...T.errToObj(D)})}cidr(D){return this._addCheck({kind:"cidr",...T.errToObj(D)})}datetime(D){if(typeof D==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:D});return this._addCheck({kind:"datetime",precision:typeof D?.precision>"u"?null:D?.precision,offset:D?.offset??!1,local:D?.local??!1,...T.errToObj(D?.message)})}date(D){return this._addCheck({kind:"date",message:D})}time(D){if(typeof D==="string")return this._addCheck({kind:"time",precision:null,message:D});return this._addCheck({kind:"time",precision:typeof D?.precision>"u"?null:D?.precision,...T.errToObj(D?.message)})}duration(D){return this._addCheck({kind:"duration",...T.errToObj(D)})}regex(D,u){return this._addCheck({kind:"regex",regex:D,...T.errToObj(u)})}includes(D,u){return this._addCheck({kind:"includes",value:D,position:u?.position,...T.errToObj(u?.message)})}startsWith(D,u){return this._addCheck({kind:"startsWith",value:D,...T.errToObj(u)})}endsWith(D,u){return this._addCheck({kind:"endsWith",value:D,...T.errToObj(u)})}min(D,u){return this._addCheck({kind:"min",value:D,...T.errToObj(u)})}max(D,u){return this._addCheck({kind:"max",value:D,...T.errToObj(u)})}length(D,u){return this._addCheck({kind:"length",value:D,...T.errToObj(u)})}nonempty(D){return this.min(1,T.errToObj(D))}trim(){return new zu({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new zu({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new zu({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((D)=>D.kind==="datetime")}get isDate(){return!!this._def.checks.find((D)=>D.kind==="date")}get isTime(){return!!this._def.checks.find((D)=>D.kind==="time")}get isDuration(){return!!this._def.checks.find((D)=>D.kind==="duration")}get isEmail(){return!!this._def.checks.find((D)=>D.kind==="email")}get isURL(){return!!this._def.checks.find((D)=>D.kind==="url")}get isEmoji(){return!!this._def.checks.find((D)=>D.kind==="emoji")}get isUUID(){return!!this._def.checks.find((D)=>D.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((D)=>D.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((D)=>D.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((D)=>D.kind==="cuid2")}get isULID(){return!!this._def.checks.find((D)=>D.kind==="ulid")}get isIP(){return!!this._def.checks.find((D)=>D.kind==="ip")}get isCIDR(){return!!this._def.checks.find((D)=>D.kind==="cidr")}get isBase64(){return!!this._def.checks.find((D)=>D.kind==="base64")}get isBase64url(){return!!this._def.checks.find((D)=>D.kind==="base64url")}get minLength(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxLength(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}};zu.create=(D)=>{return new zu({checks:[],typeName:y.ZodString,coerce:D?.coerce??!1,...t(D)})};D0=class D0 extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(D){if(this._def.coerce)D.data=Number(D.data);if(this._getType(D)!==K.number){let f=this._getOrReturnCtx(D);return N(f,{code:P.invalid_type,expected:K.number,received:f.parsedType}),o}let r=void 0,A=new dD;for(let f of this._def.checks)if(f.kind==="int"){if(!DD.isInteger(D.data))r=this._getOrReturnCtx(D,r),N(r,{code:P.invalid_type,expected:"integer",received:"float",message:f.message}),A.dirty()}else if(f.kind==="min"){if(f.inclusive?D.data<f.value:D.data<=f.value)r=this._getOrReturnCtx(D,r),N(r,{code:P.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),A.dirty()}else if(f.kind==="max"){if(f.inclusive?D.data>f.value:D.data>=f.value)r=this._getOrReturnCtx(D,r),N(r,{code:P.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),A.dirty()}else if(f.kind==="multipleOf"){if(kH(D.data,f.value)!==0)r=this._getOrReturnCtx(D,r),N(r,{code:P.not_multiple_of,multipleOf:f.value,message:f.message}),A.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(D.data))r=this._getOrReturnCtx(D,r),N(r,{code:P.not_finite,message:f.message}),A.dirty()}else DD.assertNever(f);return{status:A.value,value:D.data}}gte(D,u){return this.setLimit("min",D,!0,T.toString(u))}gt(D,u){return this.setLimit("min",D,!1,T.toString(u))}lte(D,u){return this.setLimit("max",D,!0,T.toString(u))}lt(D,u){return this.setLimit("max",D,!1,T.toString(u))}setLimit(D,u,r,A){return new D0({...this._def,checks:[...this._def.checks,{kind:D,value:u,inclusive:r,message:T.toString(A)}]})}_addCheck(D){return new D0({...this._def,checks:[...this._def.checks,D]})}int(D){return this._addCheck({kind:"int",message:T.toString(D)})}positive(D){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(D)})}negative(D){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(D)})}nonpositive(D){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(D)})}nonnegative(D){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(D)})}multipleOf(D,u){return this._addCheck({kind:"multipleOf",value:D,message:T.toString(u)})}finite(D){return this._addCheck({kind:"finite",message:T.toString(D)})}safe(D){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(D)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(D)})}get minValue(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxValue(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}get isInt(){return!!this._def.checks.find((D)=>D.kind==="int"||D.kind==="multipleOf"&&DD.isInteger(D.value))}get isFinite(){let D=null,u=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(u===null||r.value>u)u=r.value}else if(r.kind==="max"){if(D===null||r.value<D)D=r.value}return Number.isFinite(u)&&Number.isFinite(D)}};D0.create=(D)=>{return new D0({checks:[],typeName:y.ZodNumber,coerce:D?.coerce||!1,...t(D)})};u0=class u0 extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(D){if(this._def.coerce)try{D.data=BigInt(D.data)}catch{return this._getInvalidInput(D)}if(this._getType(D)!==K.bigint)return this._getInvalidInput(D);let r=void 0,A=new dD;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?D.data<f.value:D.data<=f.value)r=this._getOrReturnCtx(D,r),N(r,{code:P.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),A.dirty()}else if(f.kind==="max"){if(f.inclusive?D.data>f.value:D.data>=f.value)r=this._getOrReturnCtx(D,r),N(r,{code:P.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),A.dirty()}else if(f.kind==="multipleOf"){if(D.data%f.value!==BigInt(0))r=this._getOrReturnCtx(D,r),N(r,{code:P.not_multiple_of,multipleOf:f.value,message:f.message}),A.dirty()}else DD.assertNever(f);return{status:A.value,value:D.data}}_getInvalidInput(D){let u=this._getOrReturnCtx(D);return N(u,{code:P.invalid_type,expected:K.bigint,received:u.parsedType}),o}gte(D,u){return this.setLimit("min",D,!0,T.toString(u))}gt(D,u){return this.setLimit("min",D,!1,T.toString(u))}lte(D,u){return this.setLimit("max",D,!0,T.toString(u))}lt(D,u){return this.setLimit("max",D,!1,T.toString(u))}setLimit(D,u,r,A){return new u0({...this._def,checks:[...this._def.checks,{kind:D,value:u,inclusive:r,message:T.toString(A)}]})}_addCheck(D){return new u0({...this._def,checks:[...this._def.checks,D]})}positive(D){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(D)})}negative(D){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(D)})}nonpositive(D){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(D)})}nonnegative(D){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(D)})}multipleOf(D,u){return this._addCheck({kind:"multipleOf",value:D,message:T.toString(u)})}get minValue(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxValue(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}};u0.create=(D)=>{return new u0({checks:[],typeName:y.ZodBigInt,coerce:D?.coerce??!1,...t(D)})};_2=class _2 extends x{_parse(D){if(this._def.coerce)D.data=Boolean(D.data);if(this._getType(D)!==K.boolean){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.boolean,received:r.parsedType}),o}return xD(D.data)}};_2.create=(D)=>{return new _2({typeName:y.ZodBoolean,coerce:D?.coerce||!1,...t(D)})};V0=class V0 extends x{_parse(D){if(this._def.coerce)D.data=new Date(D.data);if(this._getType(D)!==K.date){let f=this._getOrReturnCtx(D);return N(f,{code:P.invalid_type,expected:K.date,received:f.parsedType}),o}if(Number.isNaN(D.data.getTime())){let f=this._getOrReturnCtx(D);return N(f,{code:P.invalid_date}),o}let r=new dD,A=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(D.data.getTime()<f.value)A=this._getOrReturnCtx(D,A),N(A,{code:P.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),r.dirty()}else if(f.kind==="max"){if(D.data.getTime()>f.value)A=this._getOrReturnCtx(D,A),N(A,{code:P.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),r.dirty()}else DD.assertNever(f);return{status:r.value,value:new Date(D.data.getTime())}}_addCheck(D){return new V0({...this._def,checks:[...this._def.checks,D]})}min(D,u){return this._addCheck({kind:"min",value:D.getTime(),message:T.toString(u)})}max(D,u){return this._addCheck({kind:"max",value:D.getTime(),message:T.toString(u)})}get minDate(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D!=null?new Date(D):null}get maxDate(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D!=null?new Date(D):null}};V0.create=(D)=>{return new V0({checks:[],coerce:D?.coerce||!1,typeName:y.ZodDate,...t(D)})};Y1=class Y1 extends x{_parse(D){if(this._getType(D)!==K.symbol){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.symbol,received:r.parsedType}),o}return xD(D.data)}};Y1.create=(D)=>{return new Y1({typeName:y.ZodSymbol,...t(D)})};R2=class R2 extends x{_parse(D){if(this._getType(D)!==K.undefined){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.undefined,received:r.parsedType}),o}return xD(D.data)}};R2.create=(D)=>{return new R2({typeName:y.ZodUndefined,...t(D)})};S2=class S2 extends x{_parse(D){if(this._getType(D)!==K.null){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.null,received:r.parsedType}),o}return xD(D.data)}};S2.create=(D)=>{return new S2({typeName:y.ZodNull,...t(D)})};K0=class K0 extends x{constructor(){super(...arguments);this._any=!0}_parse(D){return xD(D.data)}};K0.create=(D)=>{return new K0({typeName:y.ZodAny,...t(D)})};er=class er extends x{constructor(){super(...arguments);this._unknown=!0}_parse(D){return xD(D.data)}};er.create=(D)=>{return new er({typeName:y.ZodUnknown,...t(D)})};Jr=class Jr extends x{_parse(D){let u=this._getOrReturnCtx(D);return N(u,{code:P.invalid_type,expected:K.never,received:u.parsedType}),o}};Jr.create=(D)=>{return new Jr({typeName:y.ZodNever,...t(D)})};M1=class M1 extends x{_parse(D){if(this._getType(D)!==K.undefined){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.void,received:r.parsedType}),o}return xD(D.data)}};M1.create=(D)=>{return new M1({typeName:y.ZodVoid,...t(D)})};ju=class ju extends x{_parse(D){let{ctx:u,status:r}=this._processInputParams(D),A=this._def;if(u.parsedType!==K.array)return N(u,{code:P.invalid_type,expected:K.array,received:u.parsedType}),o;if(A.exactLength!==null){let w=u.data.length>A.exactLength.value,F=u.data.length<A.exactLength.value;if(w||F)N(u,{code:w?P.too_big:P.too_small,minimum:F?A.exactLength.value:void 0,maximum:w?A.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:A.exactLength.message}),r.dirty()}if(A.minLength!==null){if(u.data.length<A.minLength.value)N(u,{code:P.too_small,minimum:A.minLength.value,type:"array",inclusive:!0,exact:!1,message:A.minLength.message}),r.dirty()}if(A.maxLength!==null){if(u.data.length>A.maxLength.value)N(u,{code:P.too_big,maximum:A.maxLength.value,type:"array",inclusive:!0,exact:!1,message:A.maxLength.message}),r.dirty()}if(u.common.async)return Promise.all([...u.data].map((w,F)=>{return A.type._parseAsync(new vu(u,w,u.path,F))})).then((w)=>{return dD.mergeArray(r,w)});let f=[...u.data].map((w,F)=>{return A.type._parseSync(new vu(u,w,u.path,F))});return dD.mergeArray(r,f)}get element(){return this._def.type}min(D,u){return new ju({...this._def,minLength:{value:D,message:T.toString(u)}})}max(D,u){return new ju({...this._def,maxLength:{value:D,message:T.toString(u)}})}length(D,u){return new ju({...this._def,exactLength:{value:D,message:T.toString(u)}})}nonempty(D){return this.min(1,D)}};ju.create=(D,u)=>{return new ju({type:D,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...t(u)})};UD=class UD extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let D=this._def.shape(),u=DD.objectKeys(D);return this._cached={shape:D,keys:u},this._cached}_parse(D){if(this._getType(D)!==K.object){let $=this._getOrReturnCtx(D);return N($,{code:P.invalid_type,expected:K.object,received:$.parsedType}),o}let{status:r,ctx:A}=this._processInputParams(D),{shape:f,keys:w}=this._getCached(),F=[];if(!(this._def.catchall instanceof Jr&&this._def.unknownKeys==="strip")){for(let $ in A.data)if(!w.includes($))F.push($)}let E=[];for(let $ of w){let g=f[$],R=A.data[$];E.push({key:{status:"valid",value:$},value:g._parse(new vu(A,R,A.path,$)),alwaysSet:$ in A.data})}if(this._def.catchall instanceof Jr){let $=this._def.unknownKeys;if($==="passthrough")for(let g of F)E.push({key:{status:"valid",value:g},value:{status:"valid",value:A.data[g]}});else if($==="strict"){if(F.length>0)N(A,{code:P.unrecognized_keys,keys:F}),r.dirty()}else if($==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let $=this._def.catchall;for(let g of F){let R=A.data[g];E.push({key:{status:"valid",value:g},value:$._parse(new vu(A,R,A.path,g)),alwaysSet:g in A.data})}}if(A.common.async)return Promise.resolve().then(async()=>{let $=[];for(let g of E){let R=await g.key,S=await g.value;$.push({key:R,value:S,alwaysSet:g.alwaysSet})}return $}).then(($)=>{return dD.mergeObjectSync(r,$)});else return dD.mergeObjectSync(r,E)}get shape(){return this._def.shape()}strict(D){return T.errToObj,new UD({...this._def,unknownKeys:"strict",...D!==void 0?{errorMap:(u,r)=>{let A=this._def.errorMap?.(u,r).message??r.defaultError;if(u.code==="unrecognized_keys")return{message:T.errToObj(D).message??A};return{message:A}}}:{}})}strip(){return new UD({...this._def,unknownKeys:"strip"})}passthrough(){return new UD({...this._def,unknownKeys:"passthrough"})}extend(D){return new UD({...this._def,shape:()=>({...this._def.shape(),...D})})}merge(D){return new UD({unknownKeys:D._def.unknownKeys,catchall:D._def.catchall,shape:()=>({...this._def.shape(),...D._def.shape()}),typeName:y.ZodObject})}setKey(D,u){return this.augment({[D]:u})}catchall(D){return new UD({...this._def,catchall:D})}pick(D){let u={};for(let r of DD.objectKeys(D))if(D[r]&&this.shape[r])u[r]=this.shape[r];return new UD({...this._def,shape:()=>u})}omit(D){let u={};for(let r of DD.objectKeys(this.shape))if(!D[r])u[r]=this.shape[r];return new UD({...this._def,shape:()=>u})}deepPartial(){return E2(this)}partial(D){let u={};for(let r of DD.objectKeys(this.shape)){let A=this.shape[r];if(D&&!D[r])u[r]=A;else u[r]=A.optional()}return new UD({...this._def,shape:()=>u})}required(D){let u={};for(let r of DD.objectKeys(this.shape))if(D&&!D[r])u[r]=this.shape[r];else{let f=this.shape[r];while(f instanceof Tu)f=f._def.innerType;u[r]=f}return new UD({...this._def,shape:()=>u})}keyof(){return SE(DD.objectKeys(this.shape))}};UD.create=(D,u)=>{return new UD({shape:()=>D,unknownKeys:"strip",catchall:Jr.create(),typeName:y.ZodObject,...t(u)})};UD.strictCreate=(D,u)=>{return new UD({shape:()=>D,unknownKeys:"strict",catchall:Jr.create(),typeName:y.ZodObject,...t(u)})};UD.lazycreate=(D,u)=>{return new UD({shape:D,unknownKeys:"strip",catchall:Jr.create(),typeName:y.ZodObject,...t(u)})};B2=class B2 extends x{_parse(D){let{ctx:u}=this._processInputParams(D),r=this._def.options;function A(f){for(let F of f)if(F.result.status==="valid")return F.result;for(let F of f)if(F.result.status==="dirty")return u.common.issues.push(...F.ctx.common.issues),F.result;let w=f.map((F)=>new Fu(F.ctx.common.issues));return N(u,{code:P.invalid_union,unionErrors:w}),o}if(u.common.async)return Promise.all(r.map(async(f)=>{let w={...u,common:{...u.common,issues:[]},parent:null};return{result:await f._parseAsync({data:u.data,path:u.path,parent:w}),ctx:w}})).then(A);else{let f=void 0,w=[];for(let E of r){let $={...u,common:{...u.common,issues:[]},parent:null},g=E._parseSync({data:u.data,path:u.path,parent:$});if(g.status==="valid")return g;else if(g.status==="dirty"&&!f)f={result:g,ctx:$};if($.common.issues.length)w.push($.common.issues)}if(f)return u.common.issues.push(...f.ctx.common.issues),f.result;let F=w.map((E)=>new Fu(E));return N(u,{code:P.invalid_union,unionErrors:F}),o}}get options(){return this._def.options}};B2.create=(D,u)=>{return new B2({options:D,typeName:y.ZodUnion,...t(u)})};n8=class n8 extends x{_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.object)return N(u,{code:P.invalid_type,expected:K.object,received:u.parsedType}),o;let r=this.discriminator,A=u.data[r],f=this.optionsMap.get(A);if(!f)return N(u,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),o;if(u.common.async)return f._parseAsync({data:u.data,path:u.path,parent:u});else return f._parseSync({data:u.data,path:u.path,parent:u})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(D,u,r){let A=new Map;for(let f of u){let w=Qr(f.shape[D]);if(!w.length)throw Error(`A discriminator value for key \`${D}\` could not be extracted from all schema options`);for(let F of w){if(A.has(F))throw Error(`Discriminator property ${String(D)} has duplicate value ${String(F)}`);A.set(F,f)}}return new n8({typeName:y.ZodDiscriminatedUnion,discriminator:D,options:u,optionsMap:A,...t(r)})}};J2=class J2 extends x{_parse(D){let{status:u,ctx:r}=this._processInputParams(D),A=(f,w)=>{if(C8(f)||C8(w))return o;let F=vF(f.value,w.value);if(!F.valid)return N(r,{code:P.invalid_intersection_types}),o;if(H8(f)||H8(w))u.dirty();return{status:u.value,value:F.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([f,w])=>A(f,w));else return A(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};J2.create=(D,u,r)=>{return new J2({left:D,right:u,typeName:y.ZodIntersection,...t(r)})};Wr=class Wr extends x{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.array)return N(r,{code:P.invalid_type,expected:K.array,received:r.parsedType}),o;if(r.data.length<this._def.items.length)return N(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),o;if(!this._def.rest&&r.data.length>this._def.items.length)N(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u.dirty();let f=[...r.data].map((w,F)=>{let E=this._def.items[F]||this._def.rest;if(!E)return null;return E._parse(new vu(r,w,r.path,F))}).filter((w)=>!!w);if(r.common.async)return Promise.all(f).then((w)=>{return dD.mergeArray(u,w)});else return dD.mergeArray(u,f)}get items(){return this._def.items}rest(D){return new Wr({...this._def,rest:D})}};Wr.create=(D,u)=>{if(!Array.isArray(D))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Wr({items:D,typeName:y.ZodTuple,rest:null,...t(u)})};O1=class O1 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.object)return N(r,{code:P.invalid_type,expected:K.object,received:r.parsedType}),o;let A=[],f=this._def.keyType,w=this._def.valueType;for(let F in r.data)A.push({key:f._parse(new vu(r,F,r.path,F)),value:w._parse(new vu(r,r.data[F],r.path,F)),alwaysSet:F in r.data});if(r.common.async)return dD.mergeObjectAsync(u,A);else return dD.mergeObjectSync(u,A)}get element(){return this._def.valueType}static create(D,u,r){if(u instanceof x)return new O1({keyType:D,valueType:u,typeName:y.ZodRecord,...t(r)});return new O1({keyType:zu.create(),valueType:D,typeName:y.ZodRecord,...t(u)})}};P1=class P1 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.map)return N(r,{code:P.invalid_type,expected:K.map,received:r.parsedType}),o;let A=this._def.keyType,f=this._def.valueType,w=[...r.data.entries()].map(([F,E],$)=>{return{key:A._parse(new vu(r,F,r.path,[$,"key"])),value:f._parse(new vu(r,E,r.path,[$,"value"]))}});if(r.common.async){let F=new Map;return Promise.resolve().then(async()=>{for(let E of w){let $=await E.key,g=await E.value;if($.status==="aborted"||g.status==="aborted")return o;if($.status==="dirty"||g.status==="dirty")u.dirty();F.set($.value,g.value)}return{status:u.value,value:F}})}else{let F=new Map;for(let E of w){let{key:$,value:g}=E;if($.status==="aborted"||g.status==="aborted")return o;if($.status==="dirty"||g.status==="dirty")u.dirty();F.set($.value,g.value)}return{status:u.value,value:F}}}};P1.create=(D,u,r)=>{return new P1({valueType:u,keyType:D,typeName:y.ZodMap,...t(r)})};h0=class h0 extends x{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.set)return N(r,{code:P.invalid_type,expected:K.set,received:r.parsedType}),o;let A=this._def;if(A.minSize!==null){if(r.data.size<A.minSize.value)N(r,{code:P.too_small,minimum:A.minSize.value,type:"set",inclusive:!0,exact:!1,message:A.minSize.message}),u.dirty()}if(A.maxSize!==null){if(r.data.size>A.maxSize.value)N(r,{code:P.too_big,maximum:A.maxSize.value,type:"set",inclusive:!0,exact:!1,message:A.maxSize.message}),u.dirty()}let f=this._def.valueType;function w(E){let $=new Set;for(let g of E){if(g.status==="aborted")return o;if(g.status==="dirty")u.dirty();$.add(g.value)}return{status:u.value,value:$}}let F=[...r.data.values()].map((E,$)=>f._parse(new vu(r,E,r.path,$)));if(r.common.async)return Promise.all(F).then((E)=>w(E));else return w(F)}min(D,u){return new h0({...this._def,minSize:{value:D,message:T.toString(u)}})}max(D,u){return new h0({...this._def,maxSize:{value:D,message:T.toString(u)}})}size(D,u){return this.min(D,u).max(D,u)}nonempty(D){return this.min(1,D)}};h0.create=(D,u)=>{return new h0({valueType:D,minSize:null,maxSize:null,typeName:y.ZodSet,...t(u)})};g2=class g2 extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.function)return N(u,{code:P.invalid_type,expected:K.function,received:u.parsedType}),o;function r(F,E){return X1({data:F,path:u.path,errorMaps:[u.common.contextualErrorMap,u.schemaErrorMap,w2(),Nr].filter(($)=>!!$),issueData:{code:P.invalid_arguments,argumentsError:E}})}function A(F,E){return X1({data:F,path:u.path,errorMaps:[u.common.contextualErrorMap,u.schemaErrorMap,w2(),Nr].filter(($)=>!!$),issueData:{code:P.invalid_return_type,returnTypeError:E}})}let f={errorMap:u.common.contextualErrorMap},w=u.data;if(this._def.returns instanceof N0){let F=this;return xD(async function(...E){let $=new Fu([]),g=await F._def.args.parseAsync(E,f).catch((B)=>{throw $.addIssue(r(E,B)),$}),R=await Reflect.apply(w,this,g);return await F._def.returns._def.type.parseAsync(R,f).catch((B)=>{throw $.addIssue(A(R,B)),$})})}else{let F=this;return xD(function(...E){let $=F._def.args.safeParse(E,f);if(!$.success)throw new Fu([r(E,$.error)]);let g=Reflect.apply(w,this,$.data),R=F._def.returns.safeParse(g,f);if(!R.success)throw new Fu([A(g,R.error)]);return R.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...D){return new g2({...this._def,args:Wr.create(D).rest(er.create())})}returns(D){return new g2({...this._def,returns:D})}implement(D){return this.parse(D)}strictImplement(D){return this.parse(D)}static create(D,u,r){return new g2({args:D?D:Wr.create([]).rest(er.create()),returns:u||er.create(),typeName:y.ZodFunction,...t(r)})}};W2=class W2 extends x{get schema(){return this._def.getter()}_parse(D){let{ctx:u}=this._processInputParams(D);return this._def.getter()._parse({data:u.data,path:u.path,parent:u})}};W2.create=(D,u)=>{return new W2({getter:D,typeName:y.ZodLazy,...t(u)})};G2=class G2 extends x{_parse(D){if(D.data!==this._def.value){let u=this._getOrReturnCtx(D);return N(u,{received:u.data,code:P.invalid_literal,expected:this._def.value}),o}return{status:"valid",value:D.data}}get value(){return this._def.value}};G2.create=(D,u)=>{return new G2({value:D,typeName:y.ZodLiteral,...t(u)})};r0=class r0 extends x{_parse(D){if(typeof D.data!=="string"){let u=this._getOrReturnCtx(D),r=this._def.values;return N(u,{expected:DD.joinValues(r),received:u.parsedType,code:P.invalid_type}),o}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(D.data)){let u=this._getOrReturnCtx(D),r=this._def.values;return N(u,{received:u.data,code:P.invalid_enum_value,options:r}),o}return xD(D.data)}get options(){return this._def.values}get enum(){let D={};for(let u of this._def.values)D[u]=u;return D}get Values(){let D={};for(let u of this._def.values)D[u]=u;return D}get Enum(){let D={};for(let u of this._def.values)D[u]=u;return D}extract(D,u=this._def){return r0.create(D,{...this._def,...u})}exclude(D,u=this._def){return r0.create(this.options.filter((r)=>!D.includes(r)),{...this._def,...u})}};r0.create=SE;C2=class C2 extends x{_parse(D){let u=DD.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(D);if(r.parsedType!==K.string&&r.parsedType!==K.number){let A=DD.objectValues(u);return N(r,{expected:DD.joinValues(A),received:r.parsedType,code:P.invalid_type}),o}if(!this._cache)this._cache=new Set(DD.getValidEnumValues(this._def.values));if(!this._cache.has(D.data)){let A=DD.objectValues(u);return N(r,{received:r.data,code:P.invalid_enum_value,options:A}),o}return xD(D.data)}get enum(){return this._def.values}};C2.create=(D,u)=>{return new C2({values:D,typeName:y.ZodNativeEnum,...t(u)})};N0=class N0 extends x{unwrap(){return this._def.type}_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.promise&&u.common.async===!1)return N(u,{code:P.invalid_type,expected:K.promise,received:u.parsedType}),o;let r=u.parsedType===K.promise?u.data:Promise.resolve(u.data);return xD(r.then((A)=>{return this._def.type.parseAsync(A,{path:u.path,errorMap:u.common.contextualErrorMap})}))}};N0.create=(D,u)=>{return new N0({type:D,typeName:y.ZodPromise,...t(u)})};su=class su extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(D){let{status:u,ctx:r}=this._processInputParams(D),A=this._def.effect||null,f={addIssue:(w)=>{if(N(r,w),w.fatal)u.abort();else u.dirty()},get path(){return r.path}};if(f.addIssue=f.addIssue.bind(f),A.type==="preprocess"){let w=A.transform(r.data,f);if(r.common.async)return Promise.resolve(w).then(async(F)=>{if(u.value==="aborted")return o;let E=await this._def.schema._parseAsync({data:F,path:r.path,parent:r});if(E.status==="aborted")return o;if(E.status==="dirty")return I0(E.value);if(u.value==="dirty")return I0(E.value);return E});else{if(u.value==="aborted")return o;let F=this._def.schema._parseSync({data:w,path:r.path,parent:r});if(F.status==="aborted")return o;if(F.status==="dirty")return I0(F.value);if(u.value==="dirty")return I0(F.value);return F}}if(A.type==="refinement"){let w=(F)=>{let E=A.refinement(F,f);if(r.common.async)return Promise.resolve(E);if(E instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return F};if(r.common.async===!1){let F=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(F.status==="aborted")return o;if(F.status==="dirty")u.dirty();return w(F.value),{status:u.value,value:F.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((F)=>{if(F.status==="aborted")return o;if(F.status==="dirty")u.dirty();return w(F.value).then(()=>{return{status:u.value,value:F.value}})})}if(A.type==="transform")if(r.common.async===!1){let w=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ar(w))return o;let F=A.transform(w.value,f);if(F instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:u.value,value:F}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((w)=>{if(!ar(w))return o;return Promise.resolve(A.transform(w.value,f)).then((F)=>({status:u.value,value:F}))});DD.assertNever(A)}};su.create=(D,u,r)=>{return new su({schema:D,typeName:y.ZodEffects,effect:u,...t(r)})};su.createWithPreprocess=(D,u,r)=>{return new su({schema:u,effect:{type:"preprocess",transform:D},typeName:y.ZodEffects,...t(r)})};Tu=class Tu extends x{_parse(D){if(this._getType(D)===K.undefined)return xD(void 0);return this._def.innerType._parse(D)}unwrap(){return this._def.innerType}};Tu.create=(D,u)=>{return new Tu({innerType:D,typeName:y.ZodOptional,...t(u)})};Lr=class Lr extends x{_parse(D){if(this._getType(D)===K.null)return xD(null);return this._def.innerType._parse(D)}unwrap(){return this._def.innerType}};Lr.create=(D,u)=>{return new Lr({innerType:D,typeName:y.ZodNullable,...t(u)})};H2=class H2 extends x{_parse(D){let{ctx:u}=this._processInputParams(D),r=u.data;if(u.parsedType===K.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:u.path,parent:u})}removeDefault(){return this._def.innerType}};H2.create=(D,u)=>{return new H2({innerType:D,typeName:y.ZodDefault,defaultValue:typeof u.default==="function"?u.default:()=>u.default,...t(u)})};n2=class n2 extends x{_parse(D){let{ctx:u}=this._processInputParams(D),r={...u,common:{...u.common,issues:[]}},A=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if($2(A))return A.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new Fu(r.common.issues)},input:r.data})}});else return{status:"valid",value:A.status==="valid"?A.value:this._def.catchValue({get error(){return new Fu(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};n2.create=(D,u)=>{return new n2({innerType:D,typeName:y.ZodCatch,catchValue:typeof u.catch==="function"?u.catch:()=>u.catch,...t(u)})};i1=class i1 extends x{_parse(D){if(this._getType(D)!==K.nan){let r=this._getOrReturnCtx(D);return N(r,{code:P.invalid_type,expected:K.nan,received:r.parsedType}),o}return{status:"valid",value:D.data}}};i1.create=(D)=>{return new i1({typeName:y.ZodNaN,...t(D)})};IH=Symbol("zod_brand");U8=class U8 extends x{_parse(D){let{ctx:u}=this._processInputParams(D),r=u.data;return this._def.type._parse({data:r,path:u.path,parent:u})}unwrap(){return this._def.type}};k1=class k1 extends x{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.common.async)return(async()=>{let f=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(f.status==="aborted")return o;if(f.status==="dirty")return u.dirty(),I0(f.value);else return this._def.out._parseAsync({data:f.value,path:r.path,parent:r})})();else{let A=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(A.status==="aborted")return o;if(A.status==="dirty")return u.dirty(),{status:"dirty",value:A.value};else return this._def.out._parseSync({data:A.value,path:r.path,parent:r})}}static create(D,u){return new k1({in:D,out:u,typeName:y.ZodPipeline})}};U2=class U2 extends x{_parse(D){let u=this._def.innerType._parse(D),r=(A)=>{if(ar(A))A.value=Object.freeze(A.value);return A};return $2(u)?u.then((A)=>r(A)):r(u)}unwrap(){return this._def.innerType}};U2.create=(D,u)=>{return new U2({innerType:D,typeName:y.ZodReadonly,...t(u)})};VH={object:UD.lazycreate};(function(D){D.ZodString="ZodString",D.ZodNumber="ZodNumber",D.ZodNaN="ZodNaN",D.ZodBigInt="ZodBigInt",D.ZodBoolean="ZodBoolean",D.ZodDate="ZodDate",D.ZodSymbol="ZodSymbol",D.ZodUndefined="ZodUndefined",D.ZodNull="ZodNull",D.ZodAny="ZodAny",D.ZodUnknown="ZodUnknown",D.ZodNever="ZodNever",D.ZodVoid="ZodVoid",D.ZodArray="ZodArray",D.ZodObject="ZodObject",D.ZodUnion="ZodUnion",D.ZodDiscriminatedUnion="ZodDiscriminatedUnion",D.ZodIntersection="ZodIntersection",D.ZodTuple="ZodTuple",D.ZodRecord="ZodRecord",D.ZodMap="ZodMap",D.ZodSet="ZodSet",D.ZodFunction="ZodFunction",D.ZodLazy="ZodLazy",D.ZodLiteral="ZodLiteral",D.ZodEnum="ZodEnum",D.ZodEffects="ZodEffects",D.ZodNativeEnum="ZodNativeEnum",D.ZodOptional="ZodOptional",D.ZodNullable="ZodNullable",D.ZodDefault="ZodDefault",D.ZodCatch="ZodCatch",D.ZodPromise="ZodPromise",D.ZodBranded="ZodBranded",D.ZodPipeline="ZodPipeline",D.ZodReadonly="ZodReadonly"})(y||(y={}));JE=zu.create,WE=D0.create,hH=i1.create,NH=u0.create,GE=_2.create,QH=V0.create,LH=Y1.create,qH=R2.create,bH=S2.create,zH=K0.create,jH=er.create,TH=Jr.create,vH=M1.create,sH=ju.create,ZH=UD.create,oH=UD.strictCreate,dH=B2.create,yH=n8.create,lH=J2.create,cH=Wr.create,tH=O1.create,xH=P1.create,mH=h0.create,pH=g2.create,aH=W2.create,eH=G2.create,Dn=r0.create,un=C2.create,rn=N0.create,An=su.create,fn=Tu.create,Fn=Lr.create,wn=su.createWithPreprocess,$n=k1.create,Rn={string:(D)=>zu.create({...D,coerce:!0}),number:(D)=>D0.create({...D,coerce:!0}),boolean:(D)=>_2.create({...D,coerce:!0}),bigint:(D)=>u0.create({...D,coerce:!0}),date:(D)=>V0.create({...D,coerce:!0})},Sn=o});var _={};dA(_,{void:()=>vH,util:()=>DD,unknown:()=>jH,union:()=>dH,undefined:()=>qH,tuple:()=>cH,transformer:()=>An,symbol:()=>LH,string:()=>JE,strictObject:()=>oH,setErrorMap:()=>FH,set:()=>mH,record:()=>tH,quotelessJson:()=>AH,promise:()=>rn,preprocess:()=>wn,pipeline:()=>$n,ostring:()=>En,optional:()=>fn,onumber:()=>gn,oboolean:()=>_n,objectUtil:()=>bF,object:()=>ZH,number:()=>WE,nullable:()=>Fn,null:()=>bH,never:()=>TH,nativeEnum:()=>un,nan:()=>hH,map:()=>xH,makeIssue:()=>X1,literal:()=>eH,lazy:()=>aH,late:()=>VH,isValid:()=>ar,isDirty:()=>H8,isAsync:()=>$2,isAborted:()=>C8,intersection:()=>lH,instanceof:()=>KH,getParsedType:()=>Br,getErrorMap:()=>w2,function:()=>pH,enum:()=>Dn,effect:()=>An,discriminatedUnion:()=>yH,defaultErrorMap:()=>Nr,datetimeRegex:()=>RE,date:()=>QH,custom:()=>BE,coerce:()=>Rn,boolean:()=>GE,bigint:()=>NH,array:()=>sH,any:()=>zH,addIssueToContext:()=>N,ZodVoid:()=>M1,ZodUnknown:()=>er,ZodUnion:()=>B2,ZodUndefined:()=>R2,ZodType:()=>x,ZodTuple:()=>Wr,ZodTransformer:()=>su,ZodSymbol:()=>Y1,ZodString:()=>zu,ZodSet:()=>h0,ZodSchema:()=>x,ZodRecord:()=>O1,ZodReadonly:()=>U2,ZodPromise:()=>N0,ZodPipeline:()=>k1,ZodParsedType:()=>K,ZodOptional:()=>Tu,ZodObject:()=>UD,ZodNumber:()=>D0,ZodNullable:()=>Lr,ZodNull:()=>S2,ZodNever:()=>Jr,ZodNativeEnum:()=>C2,ZodNaN:()=>i1,ZodMap:()=>P1,ZodLiteral:()=>G2,ZodLazy:()=>W2,ZodIssueCode:()=>P,ZodIntersection:()=>J2,ZodFunction:()=>g2,ZodFirstPartyTypeKind:()=>y,ZodError:()=>Fu,ZodEnum:()=>r0,ZodEffects:()=>su,ZodDiscriminatedUnion:()=>n8,ZodDefault:()=>H2,ZodDate:()=>V0,ZodCatch:()=>n2,ZodBranded:()=>U8,ZodBoolean:()=>_2,ZodBigInt:()=>u0,ZodArray:()=>ju,ZodAny:()=>K0,Schema:()=>x,ParseStatus:()=>dD,OK:()=>xD,NEVER:()=>Sn,INVALID:()=>o,EMPTY_PATH:()=>wH,DIRTY:()=>I0,BRAND:()=>IH});var sF=W(()=>{G8();jF();FE();U1();CE();W8()});var YD=W(()=>{sF();sF()});import HE from"path";import Bn from"process";function Zu(){if(X8)return X8;return X8=Object.freeze(Jn.parse(Bn.env)),X8}var Jn,X8=null,X2;var nE=W(()=>{k3();Sr();YD();Jn=_.object({PORT:_.coerce.number().int().min(1).default(9217),AIWORKER_WORKER_HOST:_.string().min(1).default("127.0.0.1"),WORKER_DB_PATH:_.string().default(()=>HE.join(i3(),"aiworker.db")),WORKER_MIGRATIONS_FOLDER:_.string().default(()=>KF),WORKER_WORKSPACE_ROOT:_.string().default(()=>HE.join(i3(),"workers")),AIWORKER_LOCAL_TOKEN:_.string().min(16).optional()});X2=new Proxy({},{get(D,u){return Zu()[u]},has(D,u){return u in Zu()},ownKeys(){return Reflect.ownKeys(Zu())},getOwnPropertyDescriptor(D,u){return Reflect.getOwnPropertyDescriptor(Zu(),u)}})});import{Buffer as UE}from"buffer";import{timingSafeEqual as Wn}from"crypto";function ZF(D={}){let u=D.token??null,r=D.operatorId??"operator-local";return{authenticate(A){if(!u)return{status:"anonymous"};let f=`Bearer ${u}`;if(!Gn(A.authorization??"",f))return{reason:"Missing or invalid local bearer token.",status:"denied"};return{identity:{authMethod:"local-bearer",grants:[{action:"access",kind:"host",target:"api/local"}],operatorId:r,providerId:"local-bearer",subject:`local:${r}`},status:"authenticated"}},id:"local-bearer",kind:"local-bearer"}}function Gn(D,u){let r=UE.from(D),A=UE.from(u);return r.length===A.length&&Wn(r,A)}var XE=()=>{};var oF=()=>{};var Cn,Hn,ME,I1,Y8,Y2,dF,yF,lF,M8,OE,PE,iE,nn,kE,Un,IE;var cF=W(()=>{YD();oF();Cn=/^[a-z0-9][a-z0-9._-]*$/,Hn=/^[a-z][a-z0-9-]*$/,ME=/^[a-z][a-z0-9-]*$/,I1=_.string().min(1).regex(Cn,"admission id must be lowercase alphanumeric with . _ -"),Y8=_.string().min(1).regex(Hn,"admission kind must be kebab-case"),Y2=_.enum(["low","medium","high"]),dF=_.enum(["pending","approved","rejected","applied","failed"]),yF=_.enum(["approved","rejected","applied","failed"]),lF=_.enum(["conversation","message","tool-call","observation","artifact","memory","log"]),M8=_.object({at:_.string().min(1),kind:lF,summary:_.string().max(500).optional(),notes:_.string().max(2000).optional(),ref:_.string().min(1)}),OE=_.object({confidence:_.number().min(0).max(1),createdAt:_.string().min(1),evidence:_.array(M8).readonly(),id:I1,kind:Y8,payload:_.record(_.string(),_.unknown()).optional(),risk:Y2,rollback:_.string().min(1),scopeId:_.string().min(1).optional(),soulId:_.string().min(1).regex(ME),status:dF,summary:_.string().min(1).max(2000),target:_.string().min(1),updatedAt:_.string().min(1)}),PE=_.object({confidence:_.number().min(0).max(1),evidence:_.array(M8).readonly().optional(),id:I1,kind:Y8,payload:_.record(_.string(),_.unknown()).optional(),risk:Y2.default("high"),rollback:_.string().min(1),scopeId:_.string().min(1).optional(),soulId:_.string().min(1).regex(ME),summary:_.string().min(1).max(2000),target:_.string().min(1)}),iE=_.object({appliedAt:_.string().min(1).optional(),decidedAt:_.string().min(1),decidedBy:_.string().min(1),decision:yF,failureReason:_.string().max(4000).optional(),id:_.number().int().positive(),proposalId:I1,reason:_.string().max(2000).optional()}),nn=/^[a-z0-9][a-z0-9._-]*$/,kE=_.object({body:_.string().min(1).max(20000),topic:_.string().min(1).regex(nn).optional(),indexEntry:_.string().min(1).max(280).optional()}),Un=/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/,IE=_.object({body:_.string().min(1).max(20000),skillId:_.string().min(1).regex(Un),overwrite:_.boolean().optional()})});var Xn,Yn,O8,P8,i8,k8,I8,VE,KE;var hE=W(()=>{YD();Xn=/^[a-z0-9][a-z0-9._-]*$/,Yn=/^[a-z][a-z0-9-]*$/,O8=_.string().min(1).regex(Xn,"artifact id must be lowercase alphanumeric with . _ -"),P8=_.string().min(1).regex(Yn,"artifact type must be kebab-case"),i8=_.enum(["public","internal","confidential","secret"]),k8=_.enum(["active","archived","removed"]),I8=_.enum(["operator","brain-runtime","executor","channel-import"]),VE=_.object({createdAt:_.string().min(1),evidenceRefs:_.array(_.string().min(1)).readonly(),hash:_.string().regex(/^[a-f0-9]{64}$/).optional(),id:O8,metadata:_.record(_.string(),_.unknown()).optional(),ref:_.string().min(1),retention:_.string().min(1).optional(),scopeId:_.string().min(1).optional(),sensitivity:i8,source:I8,status:k8,summary:_.string().max(2000).optional(),type:P8,updatedAt:_.string().min(1)}),KE=_.object({evidenceRefs:_.array(_.string().min(1)).readonly().optional(),hash:_.string().regex(/^[a-f0-9]{64}$/).optional(),id:O8,metadata:_.record(_.string(),_.unknown()).optional(),ref:_.string().min(1),retention:_.string().min(1).optional(),scopeId:_.string().min(1).optional(),sensitivity:i8.default("internal"),source:I8,status:k8.default("active"),summary:_.string().max(2000).optional(),type:P8})});var Mn,V8,tF,xF,mF,NE,QE;var LE=W(()=>{YD();cF();Mn=/^[a-z][a-z0-9-]*$/,V8=_.string().min(1).regex(Mn,"brief section id must be kebab-case"),tF=_.enum(["soul-doc","memory-doc","rollup-doc","risk-policy","admission-summary","artifact-summary","scope-manifest","soul-skeleton"]),xF=_.object({body:_.string().min(1),id:V8,protected:_.boolean(),source:tF,tokens:_.number().int().nonnegative()}),mF=_.object({estimatedTokens:_.number().int().nonnegative(),id:V8,reason:_.string().min(1)}),NE=_.object({artifactRefs:_.array(_.unknown()).transform((D)=>D.filter((u)=>typeof u==="string").map((u)=>u.trim()).filter((u)=>u.length>0)).pipe(_.array(_.string().min(1)).readonly()).optional(),executor:_.string().min(1).optional(),risk:Y2.optional(),scopeId:_.string().min(1).optional(),soulId:_.string().min(1).optional(),task:_.string().min(1).max(4000),tokenBudget:_.number().int().min(200).max(50000).optional()}),QE=_.object({compiledAt:_.string().min(1),droppedSections:_.array(mF).readonly(),executor:_.string().min(1).optional(),scopeId:_.string().min(1).optional(),sections:_.array(xF).readonly(),soulId:_.string().min(1),task:_.string().min(1),tokensBudget:_.number().int().positive(),tokensUsed:_.number().int().nonnegative(),warnings:_.array(_.string().min(1)).readonly()})});var AD=Q((Nn)=>{var pF=Symbol.for("yaml.alias"),qE=Symbol.for("yaml.document"),K8=Symbol.for("yaml.map"),bE=Symbol.for("yaml.pair"),aF=Symbol.for("yaml.scalar"),h8=Symbol.for("yaml.seq"),qr=Symbol.for("yaml.node.type"),On=(D)=>!!D&&typeof D==="object"&&D[qr]===pF,Pn=(D)=>!!D&&typeof D==="object"&&D[qr]===qE,kn=(D)=>!!D&&typeof D==="object"&&D[qr]===K8,In=(D)=>!!D&&typeof D==="object"&&D[qr]===bE,zE=(D)=>!!D&&typeof D==="object"&&D[qr]===aF,Vn=(D)=>!!D&&typeof D==="object"&&D[qr]===h8;function jE(D){if(D&&typeof D==="object")switch(D[qr]){case K8:case h8:return!0}return!1}function Kn(D){if(D&&typeof D==="object")switch(D[qr]){case pF:case K8:case aF:case h8:return!0}return!1}var hn=(D)=>(zE(D)||jE(D))&&!!D.anchor;Nn.ALIAS=pF;Nn.DOC=qE;Nn.MAP=K8;Nn.NODE_TYPE=qr;Nn.PAIR=bE;Nn.SCALAR=aF;Nn.SEQ=h8;Nn.hasAnchor=hn;Nn.isAlias=On;Nn.isCollection=jE;Nn.isDocument=Pn;Nn.isMap=kn;Nn.isNode=Kn;Nn.isPair=In;Nn.isScalar=zE;Nn.isSeq=Vn});var V1=Q((xn)=>{var hD=AD(),wu=Symbol("break visit"),TE=Symbol("skip children"),Gr=Symbol("remove node");function N8(D,u){let r=vE(u);if(hD.isDocument(D)){if(M2(null,D.contents,r,Object.freeze([D]))===Gr)D.contents=null}else M2(null,D,r,Object.freeze([]))}N8.BREAK=wu;N8.SKIP=TE;N8.REMOVE=Gr;function M2(D,u,r,A){let f=sE(D,u,r,A);if(hD.isNode(f)||hD.isPair(f))return ZE(D,A,f),M2(D,f,r,A);if(typeof f!=="symbol"){if(hD.isCollection(u)){A=Object.freeze(A.concat(u));for(let w=0;w<u.items.length;++w){let F=M2(w,u.items[w],r,A);if(typeof F==="number")w=F-1;else if(F===wu)return wu;else if(F===Gr)u.items.splice(w,1),w-=1}}else if(hD.isPair(u)){A=Object.freeze(A.concat(u));let w=M2("key",u.key,r,A);if(w===wu)return wu;else if(w===Gr)u.key=null;let F=M2("value",u.value,r,A);if(F===wu)return wu;else if(F===Gr)u.value=null}}return f}async function Q8(D,u){let r=vE(u);if(hD.isDocument(D)){if(await O2(null,D.contents,r,Object.freeze([D]))===Gr)D.contents=null}else await O2(null,D,r,Object.freeze([]))}Q8.BREAK=wu;Q8.SKIP=TE;Q8.REMOVE=Gr;async function O2(D,u,r,A){let f=await sE(D,u,r,A);if(hD.isNode(f)||hD.isPair(f))return ZE(D,A,f),O2(D,f,r,A);if(typeof f!=="symbol"){if(hD.isCollection(u)){A=Object.freeze(A.concat(u));for(let w=0;w<u.items.length;++w){let F=await O2(w,u.items[w],r,A);if(typeof F==="number")w=F-1;else if(F===wu)return wu;else if(F===Gr)u.items.splice(w,1),w-=1}}else if(hD.isPair(u)){A=Object.freeze(A.concat(u));let w=await O2("key",u.key,r,A);if(w===wu)return wu;else if(w===Gr)u.key=null;let F=await O2("value",u.value,r,A);if(F===wu)return wu;else if(F===Gr)u.value=null}}return f}function vE(D){if(typeof D==="object"&&(D.Collection||D.Node||D.Value))return Object.assign({Alias:D.Node,Map:D.Node,Scalar:D.Node,Seq:D.Node},D.Value&&{Map:D.Value,Scalar:D.Value,Seq:D.Value},D.Collection&&{Map:D.Collection,Seq:D.Collection},D);return D}function sE(D,u,r,A){if(typeof r==="function")return r(D,u,A);if(hD.isMap(u))return r.Map?.(D,u,A);if(hD.isSeq(u))return r.Seq?.(D,u,A);if(hD.isPair(u))return r.Pair?.(D,u,A);if(hD.isScalar(u))return r.Scalar?.(D,u,A);if(hD.isAlias(u))return r.Alias?.(D,u,A);return}function ZE(D,u,r){let A=u[u.length-1];if(hD.isCollection(A))A.items[D]=r;else if(hD.isPair(A))if(D==="key")A.key=r;else A.value=r;else if(hD.isDocument(A))A.contents=r;else{let f=hD.isAlias(A)?"alias":"scalar";throw Error(`Cannot replace node with ${f} parent`)}}xn.visit=N8;xn.visitAsync=Q8});var eF=Q((uU)=>{var oE=AD(),an=V1(),en={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},DU=(D)=>D.replace(/[!,[\]{}]/g,(u)=>en[u]);class Uu{constructor(D,u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Uu.defaultYaml,D),this.tags=Object.assign({},Uu.defaultTags,u)}clone(){let D=new Uu(this.yaml,this.tags);return D.docStart=this.docStart,D}atDocument(){let D=new Uu(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Uu.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Uu.defaultTags);break}return D}add(D,u){if(this.atNextDocument)this.yaml={explicit:Uu.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Uu.defaultTags),this.atNextDocument=!1;let r=D.trim().split(/[ \t]+/),A=r.shift();switch(A){case"%TAG":{if(r.length!==2){if(u(0,"%TAG directive should contain exactly two parts"),r.length<2)return!1}let[f,w]=r;return this.tags[f]=w,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return u(0,"%YAML directive should contain exactly one part"),!1;let[f]=r;if(f==="1.1"||f==="1.2")return this.yaml.version=f,!0;else{let w=/^\d+\.\d+$/.test(f);return u(6,`Unsupported YAML version ${f}`,w),!1}}default:return u(0,`Unknown directive ${A}`,!0),!1}}tagName(D,u){if(D==="!")return"!";if(D[0]!=="!")return u(`Not a valid tag: ${D}`),null;if(D[1]==="<"){let w=D.slice(2,-1);if(w==="!"||w==="!!")return u(`Verbatim tags aren't resolved, so ${D} is invalid.`),null;if(D[D.length-1]!==">")u("Verbatim tags must end with a >");return w}let[,r,A]=D.match(/^(.*!)([^!]*)$/s);if(!A)u(`The ${D} tag has no suffix`);let f=this.tags[r];if(f)try{return f+decodeURIComponent(A)}catch(w){return u(String(w)),null}if(r==="!")return D;return u(`Could not resolve tag: ${D}`),null}tagString(D){for(let[u,r]of Object.entries(this.tags))if(D.startsWith(r))return u+DU(D.substring(r.length));return D[0]==="!"?D:`!<${D}>`}toString(D){let u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),A;if(D&&r.length>0&&oE.isNode(D.contents)){let f={};an.visit(D.contents,(w,F)=>{if(oE.isNode(F)&&F.tag)f[F.tag]=!0}),A=Object.keys(f)}else A=[];for(let[f,w]of r){if(f==="!!"&&w==="tag:yaml.org,2002:")continue;if(!D||A.some((F)=>F.startsWith(w)))u.push(`%TAG ${f} ${w}`)}return u.join(`
11
- `)}}Uu.defaultYaml={explicit:!1,version:"1.2"};Uu.defaultTags={"!!":"tag:yaml.org,2002:"};uU.Directives=Uu});var L8=Q((wU)=>{var dE=AD(),AU=V1();function fU(D){if(/[\x00-\x19\s,[\]{}]/.test(D)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(D)}`;throw Error(r)}return!0}function yE(D){let u=new Set;return AU.visit(D,{Value(r,A){if(A.anchor)u.add(A.anchor)}}),u}function lE(D,u){for(let r=1;;++r){let A=`${D}${r}`;if(!u.has(A))return A}}function FU(D,u){let r=[],A=new Map,f=null;return{onAnchor:(w)=>{r.push(w),f??(f=yE(D));let F=lE(u,f);return f.add(F),F},setAnchors:()=>{for(let w of r){let F=A.get(w);if(typeof F==="object"&&F.anchor&&(dE.isScalar(F.node)||dE.isCollection(F.node)))F.node.anchor=F.anchor;else{let E=Error("Failed to resolve repeated object (this should not happen)");throw E.source=w,E}}},sourceObjects:A}}wU.anchorIsValid=fU;wU.anchorNames=yE;wU.createNodeAnchors=FU;wU.findNewAnchor=lE});var D6=Q((RU)=>{function K1(D,u,r,A){if(A&&typeof A==="object")if(Array.isArray(A))for(let f=0,w=A.length;f<w;++f){let F=A[f],E=K1(D,A,String(f),F);if(E===void 0)delete A[f];else if(E!==F)A[f]=E}else if(A instanceof Map)for(let f of Array.from(A.keys())){let w=A.get(f),F=K1(D,A,f,w);if(F===void 0)A.delete(f);else if(F!==w)A.set(f,F)}else if(A instanceof Set)for(let f of Array.from(A)){let w=K1(D,A,f,f);if(w===void 0)A.delete(f);else if(w!==f)A.delete(f),A.add(w)}else for(let[f,w]of Object.entries(A)){let F=K1(D,A,f,w);if(F===void 0)delete A[f];else if(F!==w)A[f]=F}return D.call(u,r,A)}RU.applyReviver=K1});var A0=Q((JU)=>{var BU=AD();function cE(D,u,r){if(Array.isArray(D))return D.map((A,f)=>cE(A,String(f),r));if(D&&typeof D.toJSON==="function"){if(!r||!BU.hasAnchor(D))return D.toJSON(u,r);let A={aliasCount:0,count:1,res:void 0};r.anchors.set(D,A),r.onCreate=(w)=>{A.res=w,delete r.onCreate};let f=D.toJSON(u,r);if(r.onCreate)r.onCreate(f);return f}if(typeof D==="bigint"&&!r?.keep)return Number(D);return D}JU.toJS=cE});var q8=Q((HU)=>{var GU=D6(),tE=AD(),CU=A0();class xE{constructor(D){Object.defineProperty(this,tE.NODE_TYPE,{value:D})}clone(){let D=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)D.range=this.range.slice();return D}toJS(D,{mapAsMap:u,maxAliasCount:r,onAnchor:A,reviver:f}={}){if(!tE.isDocument(D))throw TypeError("A document argument is required");let w={anchors:new Map,doc:D,keep:!0,mapAsMap:u===!0,mapKeyWarned:!1,maxAliasCount:typeof r==="number"?r:100},F=CU.toJS(this,"",w);if(typeof A==="function")for(let{count:E,res:$}of w.anchors.values())A($,E);return typeof f==="function"?GU.applyReviver(f,{"":F},"",F):F}}HU.NodeBase=xE});var h1=Q((OU)=>{var UU=L8(),XU=V1(),P2=AD(),YU=q8(),MU=A0();class mE extends YU.NodeBase{constructor(D){super(P2.ALIAS);this.source=D,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(D,u){let r;if(u?.aliasResolveCache)r=u.aliasResolveCache;else if(r=[],XU.visit(D,{Node:(f,w)=>{if(P2.isAlias(w)||P2.hasAnchor(w))r.push(w)}}),u)u.aliasResolveCache=r;let A=void 0;for(let f of r){if(f===this)break;if(f.anchor===this.source)A=f}return A}toJSON(D,u){if(!u)return{source:this.source};let{anchors:r,doc:A,maxAliasCount:f}=u,w=this.resolve(A,u);if(!w){let E=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(E)}let F=r.get(w);if(!F)MU.toJS(w,null,u),F=r.get(w);if(F?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(f>=0){if(F.count+=1,F.aliasCount===0)F.aliasCount=b8(A,w,r);if(F.count*F.aliasCount>f)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return F.res}toString(D,u,r){let A=`*${this.source}`;if(D){if(UU.anchorIsValid(this.source),D.options.verifyAliasOrder&&!D.anchors.has(this.source)){let f=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(f)}if(D.implicitKey)return`${A} `}return A}}function b8(D,u,r){if(P2.isAlias(u)){let A=u.resolve(D),f=r&&A&&r.get(A);return f?f.count*f.aliasCount:0}else if(P2.isCollection(u)){let A=0;for(let f of u.items){let w=b8(D,f,r);if(w>A)A=w}return A}else if(P2.isPair(u)){let A=b8(D,u.key,r),f=b8(D,u.value,r);return Math.max(A,f)}return 1}OU.Alias=mE});var ID=Q((KU)=>{var iU=AD(),kU=q8(),IU=A0(),VU=(D)=>!D||typeof D!=="function"&&typeof D!=="object";class Q0 extends kU.NodeBase{constructor(D){super(iU.SCALAR);this.value=D}toJSON(D,u){return u?.keep?this.value:IU.toJS(this.value,D,u)}toString(){return String(this.value)}}Q0.BLOCK_FOLDED="BLOCK_FOLDED";Q0.BLOCK_LITERAL="BLOCK_LITERAL";Q0.PLAIN="PLAIN";Q0.QUOTE_DOUBLE="QUOTE_DOUBLE";Q0.QUOTE_SINGLE="QUOTE_SINGLE";KU.Scalar=Q0;KU.isScalarValue=VU});var N1=Q((zU)=>{var QU=h1(),L0=AD(),pE=ID(),LU="tag:yaml.org,2002:";function qU(D,u,r){if(u){let A=r.filter((w)=>w.tag===u),f=A.find((w)=>!w.format)??A[0];if(!f)throw Error(`Tag ${u} not found`);return f}return r.find((A)=>A.identify?.(D)&&!A.format)}function bU(D,u,r){if(L0.isDocument(D))D=D.contents;if(L0.isNode(D))return D;if(L0.isPair(D)){let S=r.schema[L0.MAP].createNode?.(r.schema,null,r);return S.items.push(D),S}if(D instanceof String||D instanceof Number||D instanceof Boolean||typeof BigInt<"u"&&D instanceof BigInt)D=D.valueOf();let{aliasDuplicateObjects:A,onAnchor:f,onTagObj:w,schema:F,sourceObjects:E}=r,$=void 0;if(A&&D&&typeof D==="object")if($=E.get(D),$)return $.anchor??($.anchor=f(D)),new QU.Alias($.anchor);else $={anchor:null,node:null},E.set(D,$);if(u?.startsWith("!!"))u=LU+u.slice(2);let g=qU(D,u,F.tags);if(!g){if(D&&typeof D.toJSON==="function")D=D.toJSON();if(!D||typeof D!=="object"){let S=new pE.Scalar(D);if($)$.node=S;return S}g=D instanceof Map?F[L0.MAP]:(Symbol.iterator in Object(D))?F[L0.SEQ]:F[L0.MAP]}if(w)w(g),delete r.onTagObj;let R=g?.createNode?g.createNode(r.schema,D,r):typeof g?.nodeClass?.from==="function"?g.nodeClass.from(r.schema,D,r):new pE.Scalar(D);if(u)R.tag=u;else if(!g.default)R.tag=g.tag;if($)$.node=R;return R}zU.createNode=bU});var z8=Q((sU)=>{var TU=N1(),Cr=AD(),vU=q8();function u6(D,u,r){let A=r;for(let f=u.length-1;f>=0;--f){let w=u[f];if(typeof w==="number"&&Number.isInteger(w)&&w>=0){let F=[];F[w]=A,A=F}else A=new Map([[w,A]])}return TU.createNode(A,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:D,sourceObjects:new Map})}var aE=(D)=>D==null||typeof D==="object"&&!!D[Symbol.iterator]().next().done;class eE extends vU.NodeBase{constructor(D,u){super(D);Object.defineProperty(this,"schema",{value:u,configurable:!0,enumerable:!1,writable:!0})}clone(D){let u=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(D)u.schema=D;if(u.items=u.items.map((r)=>Cr.isNode(r)||Cr.isPair(r)?r.clone(D):r),this.range)u.range=this.range.slice();return u}addIn(D,u){if(aE(D))this.add(u);else{let[r,...A]=D,f=this.get(r,!0);if(Cr.isCollection(f))f.addIn(A,u);else if(f===void 0&&this.schema)this.set(r,u6(this.schema,A,u));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${A}`)}}deleteIn(D){let[u,...r]=D;if(r.length===0)return this.delete(u);let A=this.get(u,!0);if(Cr.isCollection(A))return A.deleteIn(r);else throw Error(`Expected YAML collection at ${u}. Remaining path: ${r}`)}getIn(D,u){let[r,...A]=D,f=this.get(r,!0);if(A.length===0)return!u&&Cr.isScalar(f)?f.value:f;else return Cr.isCollection(f)?f.getIn(A,u):void 0}hasAllNullValues(D){return this.items.every((u)=>{if(!Cr.isPair(u))return!1;let r=u.value;return r==null||D&&Cr.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(D){let[u,...r]=D;if(r.length===0)return this.has(u);let A=this.get(u,!0);return Cr.isCollection(A)?A.hasIn(r):!1}setIn(D,u){let[r,...A]=D;if(A.length===0)this.set(r,u);else{let f=this.get(r,!0);if(Cr.isCollection(f))f.setIn(A,u);else if(f===void 0&&this.schema)this.set(r,u6(this.schema,A,u));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${A}`)}}}sU.Collection=eE;sU.collectionFromPath=u6;sU.isEmptyPath=aE});var Q1=Q((cU)=>{var yU=(D)=>D.replace(/^(?!$)(?: $)?/gm,"#");function r6(D,u){if(/^\n+$/.test(D))return D.substring(1);return u?D.replace(/^(?! *$)/gm,u):D}var lU=(D,u,r)=>D.endsWith(`
12
- `)?r6(r,u):r.includes(`
10
+ `;u.run(f);let F=u.values(G`SELECT id, hash, created_at FROM ${G.identifier(A)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;u.run(G`BEGIN`);try{for(let E of D)if(!F||Number(F[2])<E.folderMillis){for(let $ of E.sql)u.run(G.raw($));u.run(G`INSERT INTO ${G.identifier(A)} ("hash", "created_at") VALUES(${E.hash}, ${E.folderMillis})`)}u.run(G`COMMIT`)}catch(E){throw u.run(G`ROLLBACK`),E}}}});var _F;var q5=W(()=>{y();_F=class _F{static[i]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function _8(D,u){return(r,A,...f)=>{let w=[A,...f].map((F)=>({type:D,isAll:u,rightSelect:F}));for(let F of w)if(!FA(r.getSelectedFields(),F.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(w)}}var qu,b5,RF,_C=()=>({union:RC,unionAll:nC,intersect:BC,except:WC}),RC,nC,BC,WC;var nF=W(()=>{y();q5();Kr();m0();dD();Qu();pD();Au();Ir();e0();g8();qu=class qu{static[i]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(D){this.fields=D.fields,this.session=D.session,this.dialect=D.dialect,this.withList=D.withList,this.distinct=D.distinct}from(D){let u=!!this.fields,r;if(this.fields)r=this.fields;else if(U(D,kD))r=Object.fromEntries(Object.keys(D._.selectedFields).map((A)=>[A,D[A]]));else if(U(D,M0))r=D[HD].selectedFields;else if(U(D,b))r={};else r=g4(D);return new RF({table:D,fields:r,isPartialSelect:u,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};b5=class b5 extends _F{static[i]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:D,fields:u,isPartialSelect:r,session:A,dialect:f,withList:w,distinct:F}){super();this.config={withList:w,table:D,fields:{...u},distinct:F,setOperators:[]},this.isPartialSelect=r,this.session=A,this.dialect=f,this._={selectedFields:u,config:this.config},this.tableName=wA(D),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let E of Lu(D))this.usedTables.add(E)}getUsedTables(){return[...this.usedTables]}createJoin(D){return(u,r)=>{let A=this.tableName,f=wA(u);for(let w of Lu(u))this.usedTables.add(w);if(typeof f==="string"&&this.config.joins?.some((w)=>w.alias===f))throw Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof A==="string")this.config.fields={[A]:this.config.fields};if(typeof f==="string"&&!U(u,b)){let w=U(u,kD)?u._.selectedFields:U(u,Gu)?u[HD].selectedFields:u[V.Symbol.Columns];this.config.fields[f]=w}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new ID({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:u,joinType:D,alias:f}),typeof f==="string")switch(D){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([w])=>[w,!1])),this.joinsNotNullableMap[f]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([w])=>[w,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(D,u){return(r)=>{let A=typeof r==="function"?r(_C()):r;if(!FA(this.getSelectedFields(),A.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:D,isAll:u,rightSelect:A}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(D){return this.config.setOperators.push(...D),this}where(D){if(typeof D==="function")D=D(new Proxy(this.config.fields,new ID({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=D,this}having(D){if(typeof D==="function")D=D(new Proxy(this.config.fields,new ID({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=D,this}groupBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.fields,new ID({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(u)?u:[u]}else this.config.groupBy=D;return this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.fields,new ID({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let u=D;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=u;else this.config.orderBy=u}return this}limit(D){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=D;else this.config.limit=D;return this}offset(D){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=D;else this.config.offset=D;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}as(D){let u=[];if(u.push(...Lu(this.config.table)),this.config.joins)for(let r of this.config.joins)u.push(...Lu(r.table));return new Proxy(new kD(this.getSQL(),this.config.fields,D,!1,[...new Set(u)]),new ID({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new ID({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};RF=class RF extends b5{static[i]="SQLiteSelect";_prepare(D=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let u=Cu(this.config.fields),r=this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),u,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(D){return this.cacheConfig=D===void 0?{config:{},enable:!0,autoInvalidate:!0}:D===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...D},this}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.all()}};E4(RF,[eD]);RC=_8("union",!1),nC=_8("union",!0),BC=_8("intersect",!1),WC=_8("except",!1)});var _A;var BF=W(()=>{y();m0();S8();Qu();nF();_A=class _A{static[i]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(D){this.dialect=U(D,gA)?D:void 0,this.dialectConfig=U(D,gA)?void 0:D}$with=(D,u)=>{let r=this;return{as:(f)=>{if(typeof f==="function")f=f(r);return new Proxy(new DA(f.getSQL(),u??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),D,!0),new ID({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...D){let u=this;function r(f){return new qu({fields:f??void 0,session:void 0,dialect:u.getDialect(),withList:D})}function A(f){return new qu({fields:f??void 0,session:void 0,dialect:u.getDialect(),withList:D,distinct:!0})}return{select:r,selectDistinct:A}}select(D){return new qu({fields:D??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(D){return new qu({fields:D??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new SA(this.dialectConfig);return this.dialect}}});var R8,WF;var s5=W(()=>{y();Kr();dD();Y0();pD();Au();e0();BF();R8=class R8{constructor(D,u,r,A){this.table=D,this.session=u,this.dialect=r,this.withList=A}static[i]="SQLiteInsertBuilder";values(D){if(D=Array.isArray(D)?D:[D],D.length===0)throw Error("values() must be called with at least one value");let u=D.map((r)=>{let A={},f=this.table[V.Symbol.Columns];for(let w of Object.keys(r)){let F=r[w];A[w]=U(F,b)?F:new nu(F,f[w])}return A});return new WF(this.table,u,this.session,this.dialect,this.withList)}select(D){let u=typeof D==="function"?D(new _A):D;if(!U(u,b)&&!FA(this.table[a1],u._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new WF(this.table,u,this.session,this.dialect,this.withList,!0)}};WF=class WF extends eD{constructor(D,u,r,A,f,w){super();this.session=r,this.dialect=A,this.config={table:D,values:u,withList:f,select:w}}static[i]="SQLiteInsert";config;returning(D=this.config.table[sD.Symbol.Columns]){return this.config.returning=Cu(D),this}onConflictDoNothing(D={}){if(!this.config.onConflict)this.config.onConflict=[];if(D.target===void 0)this.config.onConflict.push(G` on conflict do nothing`);else{let u=Array.isArray(D.target)?G`${D.target}`:G`${[D.target]}`,r=D.where?G` where ${D.where}`:G``;this.config.onConflict.push(G` on conflict ${u} do nothing${r}`)}return this}onConflictDoUpdate(D){if(D.where&&(D.targetWhere||D.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let u=D.where?G` where ${D.where}`:void 0,r=D.targetWhere?G` where ${D.targetWhere}`:void 0,A=D.setWhere?G` where ${D.setWhere}`:void 0,f=Array.isArray(D.target)?G`${D.target}`:G`${[D.target]}`,w=this.dialect.buildUpdateSet(this.config.table,f8(this.config.table,D.set));return this.config.onConflict.push(G` on conflict ${f}${r} do update set ${w}${u}${A}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Lu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var n8,z5;var j5=W(()=>{y();Kr();m0();Y0();Qu();pD();Au();Ir();e0();g8();n8=class n8{constructor(D,u,r,A){this.table=D,this.session=u,this.dialect=r,this.withList=A}static[i]="SQLiteUpdateBuilder";set(D){return new z5(this.table,f8(this.table,D),this.session,this.dialect,this.withList)}};z5=class z5 extends eD{constructor(D,u,r,A,f){super();this.session=r,this.dialect=A,this.config={set:u,table:D,withList:f,joins:[]}}static[i]="SQLiteUpdate";config;from(D){return this.config.from=D,this}createJoin(D){return(u,r)=>{let A=wA(u);if(typeof A==="string"&&this.config.joins.some((f)=>f.alias===A))throw Error(`Alias "${A}" is already used in this query`);if(typeof r==="function"){let f=this.config.from?U(u,sD)?u[V.Symbol.Columns]:U(u,kD)?u._.selectedFields:U(u,M0)?u[HD].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[V.Symbol.Columns],new ID({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),f&&new Proxy(f,new ID({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:u,joinType:D,alias:A}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(D){return this.config.where=D,this}orderBy(...D){if(typeof D[0]==="function"){let u=D[0](new Proxy(this.config.table[V.Symbol.Columns],new ID({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(u)?u:[u];this.config.orderBy=r}else{let u=D;this.config.orderBy=u}return this}limit(D){return this.config.limit=D,this}returning(D=this.config.table[sD.Symbol.Columns]){return this.config.returning=Cu(D),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:D,...u}=this.dialect.sqlToQuery(this.getSQL());return u}_prepare(D=!0){return this.session[D?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Lu(this.config.table)})}prepare(){return this._prepare(!1)}run=(D)=>{return this._prepare().run(D)};all=(D)=>{return this._prepare().all(D)};get=(D)=>{return this._prepare().get(D)};values=(D)=>{return this._prepare().values(D)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var JF=W(()=>{Q5();s5();BF();nF();j5()});var RA;var T5=W(()=>{y();dD();RA=class RA extends b{constructor(D){super(RA.buildEmbeddedCount(D.source,D.filters).queryChunks);this.params=D,this.session=D.session,this.sql=RA.buildCount(D.source,D.filters)}sql;static[i]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(D,u){return G`(select count(*) from ${D}${G.raw(" where ").if(u)}${u})`}static buildCount(D,u){return G`select count(*) from ${D}${G.raw(" where ").if(u)}${u}`}then(D,u){return Promise.resolve(this.session.count(this.sql)).then(D,u)}catch(D){return this.then(void 0,D)}finally(D){return this.then((u)=>{return D?.(),u},(u)=>{throw D?.(),u})}}});var CF,B8,GF;var v5=W(()=>{y();Kr();EA();CF=class CF{constructor(D,u,r,A,f,w,F,E){this.mode=D,this.fullSchema=u,this.schema=r,this.tableNamesMap=A,this.table=f,this.tableConfig=w,this.dialect=F,this.session=E}static[i]="SQLiteAsyncRelationalQueryBuilder";findMany(D){return this.mode==="sync"?new GF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?D:{},"many"):new B8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?D:{},"many")}findFirst(D){return this.mode==="sync"?new GF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?{...D,limit:1}:{limit:1},"first"):new B8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,D?{...D,limit:1}:{limit:1},"first")}};B8=class B8 extends eD{constructor(D,u,r,A,f,w,F,E,$){super();this.fullSchema=D,this.schema=u,this.tableNamesMap=r,this.table=A,this.tableConfig=f,this.dialect=w,this.session=F,this.config=E,this.mode=$}static[i]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(D=!1){let{query:u,builtQuery:r}=this._toSQL();return this.session[D?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(A,f)=>{let w=A.map((F)=>F8(this.schema,this.tableConfig,F,u.selection,f));if(this.mode==="first")return w[0];return w})}prepare(){return this._prepare(!1)}_toSQL(){let D=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),u=this.dialect.sqlToQuery(D.sql);return{query:D,builtQuery:u}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};GF=class GF extends B8{static[i]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var D2;var Z5=W(()=>{y();Kr();D2=class D2 extends eD{constructor(D,u,r,A,f){super();this.execute=D,this.getSQL=u,this.dialect=A,this.mapBatchResult=f,this.config={action:r}}static[i]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(D,u){return u?this.mapBatchResult(D):D}_prepare(){return this}isResponseInArrayMode(){return!1}}});var nA;var W8=W(()=>{y();m0();dD();JF();Qu();T5();v5();Z5();nA=class nA{constructor(D,u,r,A){this.resultKind=D,this.dialect=u,this.session=r,this._=A?{schema:A.schema,fullSchema:A.fullSchema,tableNamesMap:A.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let f=this.query;if(this._.schema)for(let[w,F]of Object.entries(this._.schema))f[w]=new CF(D,A.fullSchema,this._.schema,this._.tableNamesMap,A.fullSchema[w],F,u,r);this.$cache={invalidate:async(w)=>{}}}static[i]="BaseSQLiteDatabase";query;$with=(D,u)=>{let r=this;return{as:(f)=>{if(typeof f==="function")f=f(new _A(r.dialect));return new Proxy(new DA(f.getSQL(),u??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),D,!0),new ID({alias:D,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(D,u){return new RA({source:D,filters:u,session:this.session})}with(...D){let u=this;function r(E){return new qu({fields:E??void 0,session:u.session,dialect:u.dialect,withList:D})}function A(E){return new qu({fields:E??void 0,session:u.session,dialect:u.dialect,withList:D,distinct:!0})}function f(E){return new n8(E,u.session,u.dialect,D)}function w(E){return new R8(E,u.session,u.dialect,D)}function F(E){return new E8(E,u.session,u.dialect,D)}return{select:r,selectDistinct:A,update:f,insert:w,delete:F}}select(D){return new qu({fields:D??void 0,session:this.session,dialect:this.dialect})}selectDistinct(D){return new qu({fields:D??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(D){return new n8(D,this.session,this.dialect)}$cache;insert(D){return new R8(D,this.session,this.dialect)}delete(D){return new E8(D,this.session,this.dialect)}run(D){let u=typeof D==="string"?G.raw(D):D.getSQL();if(this.resultKind==="async")return new D2(async()=>this.session.run(u),()=>u,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(u)}all(D){let u=typeof D==="string"?G.raw(D):D.getSQL();if(this.resultKind==="async")return new D2(async()=>this.session.all(u),()=>u,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(u)}get(D){let u=typeof D==="string"?G.raw(D):D.getSQL();if(this.resultKind==="async")return new D2(async()=>this.session.get(u),()=>u,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(u)}values(D){let u=typeof D==="string"?G.raw(D):D.getSQL();if(this.resultKind==="async")return new D2(async()=>this.session.values(u),()=>u,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(u)}transaction(D,u){return this.session.transaction(D,u)}}});var o5=()=>{};async function XF(D,u){let r=`${D}-${JSON.stringify(u)}`,f=new TextEncoder().encode(r),w=await crypto.subtle.digest("SHA-256",f);return[...new Uint8Array(w)].map(($)=>$.toString(16).padStart(2,"0")).join("")}var d5,HF;var l5=W(()=>{y();d5=class d5{static[i]="Cache"};HF=class HF extends d5{strategy(){return"all"}static[i]="NoopCache";async get(D){return}async put(D,u,r,A){}async onMutate(D){}}});var y5,iF,UF,YF;var MF=W(()=>{l5();y();r8();Kr();W8();y5=class y5 extends eD{constructor(D){super();this.resultCb=D}static[i]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};iF=class iF{constructor(D,u,r,A,f,w){if(this.mode=D,this.executeMethod=u,this.query=r,this.cache=A,this.queryMetadata=f,this.cacheConfig=w,A&&A.strategy()==="all"&&w===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[i]="PreparedQuery";joinsNotNullableMap;async queryWithCache(D,u,r){if(this.cache===void 0||U(this.cache,HF)||this.queryMetadata===void 0)try{return await r()}catch(A){throw new Vr(D,u,A)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(A){throw new Vr(D,u,A)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[A]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return A}catch(A){throw new Vr(D,u,A)}if(!this.cacheConfig)try{return await r()}catch(A){throw new Vr(D,u,A)}if(this.queryMetadata.type==="select"){let A=await this.cache.get(this.cacheConfig.tag??await XF(D,u),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(A===void 0){let f;try{f=await r()}catch(w){throw new Vr(D,u,w)}return await this.cache.put(this.cacheConfig.tag??await XF(D,u),f,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),f}return A}try{return await r()}catch(A){throw new Vr(D,u,A)}}getQuery(){return this.query}mapRunResult(D,u){return D}mapAllResult(D,u){throw Error("Not implemented")}mapGetResult(D,u){throw Error("Not implemented")}execute(D){if(this.mode==="async")return this[this.executeMethod](D);return new y5(()=>this[this.executeMethod](D))}mapResult(D,u){switch(this.executeMethod){case"run":return this.mapRunResult(D,u);case"all":return this.mapAllResult(D,u);case"get":return this.mapGetResult(D,u)}}};UF=class UF{constructor(D){this.dialect=D}static[i]="SQLiteSession";prepareOneTimeQuery(D,u,r,A,f,w,F){return this.prepareQuery(D,u,r,A,f,w,F)}run(D){let u=this.dialect.sqlToQuery(D);try{return this.prepareOneTimeQuery(u,void 0,"run",!1).run()}catch(r){throw new x0({cause:r,message:`Failed to run the query '${u.sql}'`})}}extractRawRunValueFromBatchResult(D){return D}all(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(D){throw Error("Not implemented")}get(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(D){throw Error("Not implemented")}values(D){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(D),void 0,"run",!1).values()}async count(D){return(await this.values(D))[0][0]}extractRawValuesValueFromBatchResult(D){throw Error("Not implemented")}};YF=class YF extends nA{constructor(D,u,r,A,f=0){super(D,u,r,A);this.schema=A,this.nestedIndex=f}static[i]="SQLiteTransaction";rollback(){throw new Z3}}});var c5=()=>{};var OF=W(()=>{o5();I5();SF();W8();S8();e3();h5();N5();JF();MF();Y0();DF();e0();c5()});var PF,kF,t5;var IF=W(()=>{y();A8();dD();OF();MF();Au();PF=class PF extends UF{constructor(D,u,r,A={}){super(u);this.client=D,this.schema=r,this.logger=A.logger??new d3}static[i]="SQLiteBunSession";logger;exec(D){this.client.exec(D)}prepareQuery(D,u,r,A,f){let w=this.client.prepare(D.sql);return new t5(w,D,this.logger,u,r,A,f)}transaction(D,u={}){let r=new kF("sync",this.dialect,this,this.schema),A;return this.client.transaction(()=>{A=D(r)})[u.behavior??"deferred"](),A}};kF=class kF extends YF{static[i]="SQLiteBunTransaction";transaction(D){let u=`sp${this.nestedIndex}`,r=new kF("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(G.raw(`savepoint ${u}`));try{let A=D(r);return this.session.run(G.raw(`release savepoint ${u}`)),A}catch(A){throw this.session.run(G.raw(`rollback to savepoint ${u}`)),A}}};t5=class t5 extends iF{constructor(D,u,r,A,f,w,F){super("sync",f,u);this.stmt=D,this.logger=r,this.fields=A,this._isResponseInArrayMode=w,this.customResultMapper=F}static[i]="SQLiteBunPreparedQuery";run(D){let u=rA(this.query.params,D??{});return this.logger.logQuery(this.query.sql,u),this.stmt.run(...u)}all(D){let{fields:u,query:r,logger:A,joinsNotNullableMap:f,stmt:w,customResultMapper:F}=this;if(!u&&!F){let $=rA(r.params,D??{});return A.logQuery(r.sql,$),w.all(...$)}let E=this.values(D);if(F)return F(E);return E.map(($)=>l3(u,$,f))}get(D){let u=rA(this.query.params,D??{});this.logger.logQuery(this.query.sql,u);let r=this.stmt.values(...u)[0];if(!r)return;let{fields:A,joinsNotNullableMap:f,customResultMapper:w}=this;if(!A&&!w)return r;if(w)return w([r]);return l3(A,r,f)}values(D){let u=rA(this.query.params,D??{});return this.logger.logQuery(this.query.sql,u),this.stmt.values(...u)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as J8}from"bun:sqlite";function u2(D,u={}){let r=new SA({casing:u.casing}),A;if(u.logger===!0)A=new o3;else if(u.logger!==!1)A=u.logger;let f;if(u.schema){let E=v4(u.schema,o4);f={fullSchema:u.schema,schema:E.tables,tableNamesMap:E.tableNamesMap}}let w=new PF(D,r,f,{logger:A}),F=new p5("sync",r,w,f);return F.$client=D,F}function G8(...D){if(D[0]===void 0||typeof D[0]==="string"){let u=D[0]===void 0?new J8:new J8(D[0]);return u2(u,D[1])}if(S4(D[0])){let{connection:u,client:r,...A}=D[0];if(r)return u2(r,A);if(typeof u==="object"){let{source:w,...F}=u,E=Object.values(F).filter((g)=>g!==void 0).length?F:void 0,$=new J8(w,E);return u2($,A)}let f=new J8(u);return u2(f,A)}return u2(D[0],D[1])}var p5;var x5=W(()=>{y();A8();EA();W8();S8();Au();IF();p5=class p5 extends nA{static[i]="BunSQLiteDatabase"};((D)=>{function u(r){return u2({},r)}D.mock=u})(G8||(G8={}))});var m5=W(()=>{x5();IF()});import JC from"crypto";import VF from"fs";function a5(D){let u=D.migrationsFolder,r=[],A=`${u}/meta/_journal.json`;if(!VF.existsSync(A))throw Error("Can't find meta/_journal.json file");let f=VF.readFileSync(`${u}/meta/_journal.json`).toString(),w=JSON.parse(f);for(let F of w.entries){let E=`${u}/${F.tag}.sql`;try{let $=VF.readFileSync(`${u}/${F.tag}.sql`).toString(),g=$.split("--> statement-breakpoint").map((_)=>{return _});r.push({sql:g,bps:F.breakpoints,folderMillis:F.when,hash:JC.createHash("sha256").update($).digest("hex")})}catch{throw Error(`No file ${E} found in ${u} folder`)}}return r}var e5=()=>{};function DE(D,u){let r=a5(u);D.dialect.migrate(r,D.session,u)}var uE=W(()=>{e5()});var KF={};t1(KF,{workspaces:()=>TD,workers:()=>jD,workerSecrets:()=>HC,workerIdentity:()=>GC,workerConfig:()=>CC,turns:()=>OD,soulApps:()=>Bu,soulAppStorageRecords:()=>su,soulAppAuditEvents:()=>Er,settings:()=>Nr,sessions:()=>vD,sessionEvents:()=>xD,reviews:()=>$r,lessons:()=>bu,files:()=>Fu,engineInvocations:()=>ND,artifacts:()=>wr});var $D=()=>new Date().toISOString(),jD,TD,vD,OD,ND,xD,Fu,wr,$r,bu,Bu,su,Er,Nr,GC,CC,HC;var hF=W(()=>{OF();jD=zD("workers",{id:H("id").primaryKey(),soulId:H("soul_id").notNull(),name:H("name").notNull(),status:H("status",{enum:["active","paused","disabled"]}).notNull().default("active"),defaultEngineId:H("default_engine_id"),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({soulIdx:uD("workers_soul_idx").on(D.soulId),statusUpdatedAtIdx:uD("workers_status_updated_at_idx").on(D.status,D.updatedAt)})),TD=zD("workspaces",{id:H("id").primaryKey(),workerId:H("worker_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),name:H("name").notNull(),rootPath:H("root_path").notNull(),type:H("type").notNull().default("workspace"),status:H("status",{enum:["active","archived"]}).notNull().default("active"),sourcePointersJson:H("source_pointers_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({rootPathIdx:a0("workspaces_root_path_idx").on(D.rootPath),statusUpdatedAtIdx:uD("workspaces_status_updated_at_idx").on(D.status,D.updatedAt),workerUpdatedAtIdx:uD("workspaces_worker_updated_at_idx").on(D.workerId,D.updatedAt)})),vD=zD("sessions",{id:H("id").primaryKey(),workerId:H("worker_id").notNull().references(()=>jD.id,{onDelete:"cascade"}),workspaceId:H("workspace_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),capabilityTemplateId:H("capability_template_id").notNull(),title:H("title").notNull(),context:H("context").notNull().default(""),status:H("status",{enum:["active","completed","failed","cancelled"]}).notNull().default("active"),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),startedAt:H("started_at"),endedAt:H("ended_at"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({capabilityUpdatedAtIdx:uD("sessions_capability_updated_at_idx").on(D.capabilityTemplateId,D.updatedAt),statusUpdatedAtIdx:uD("sessions_status_updated_at_idx").on(D.status,D.updatedAt),workerUpdatedAtIdx:uD("sessions_worker_updated_at_idx").on(D.workerId,D.updatedAt),workspaceUpdatedAtIdx:uD("sessions_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),OD=zD("turns",{id:H("id").primaryKey(),sessionId:H("session_id").notNull().references(()=>vD.id,{onDelete:"cascade"}),seq:Hu("seq").notNull(),input:H("input").notNull(),response:H("response"),status:H("status",{enum:["queued","running","succeeded","failed","cancelled"]}).notNull().default("queued"),error:H("error"),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({sessionSeqIdx:uD("turns_session_seq_idx").on(D.sessionId,D.seq),sessionSeqUniqueIdx:a0("turns_session_seq_unique_idx").on(D.sessionId,D.seq),statusUpdatedAtIdx:uD("turns_status_updated_at_idx").on(D.status,D.updatedAt)})),ND=zD("engine_invocations",{id:H("id").primaryKey(),sessionId:H("session_id").notNull().references(()=>vD.id,{onDelete:"cascade"}),turnId:H("turn_id").notNull().references(()=>OD.id,{onDelete:"cascade"}),seq:Hu("seq").notNull(),engineId:H("engine_id").notNull(),engineCommand:H("engine_command"),status:H("status",{enum:["queued","running","succeeded","failed","cancelled"]}).notNull().default("queued"),prompt:H("prompt").notNull(),summary:H("summary"),error:H("error"),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),startedAt:H("started_at"),finishedAt:H("finished_at"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({engineUpdatedAtIdx:uD("engine_invocations_engine_updated_at_idx").on(D.engineId,D.updatedAt),sessionSeqIdx:uD("engine_invocations_session_seq_idx").on(D.sessionId,D.seq),statusUpdatedAtIdx:uD("engine_invocations_status_updated_at_idx").on(D.status,D.updatedAt),turnIdx:uD("engine_invocations_turn_idx").on(D.turnId)})),xD=zD("session_events",{id:Hu("id").primaryKey({autoIncrement:!0}),sessionId:H("session_id").notNull().references(()=>vD.id,{onDelete:"cascade"}),turnId:H("turn_id").references(()=>OD.id,{onDelete:"set null"}),invocationId:H("invocation_id").references(()=>ND.id,{onDelete:"set null"}),seq:Hu("seq").notNull(),type:H("type",{enum:["status","assistant_delta","tool","file_change","artifact","review","lesson","error","log"]}).notNull(),payloadJson:H("payload_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D)},(D)=>({sessionCreatedAtIdx:uD("session_events_session_created_at_idx").on(D.sessionId,D.createdAt),sessionSeqIdx:uD("session_events_session_seq_idx").on(D.sessionId,D.seq),sessionSeqUniqueIdx:a0("session_events_session_seq_unique_idx").on(D.sessionId,D.seq)})),Fu=zD("files",{id:H("id").primaryKey(),workspaceId:H("workspace_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),path:H("path").notNull(),kind:H("kind",{enum:["file","directory","generated","uploaded"]}).notNull().default("file"),size:Hu("size"),mtime:Hu("mtime"),hash:H("hash"),source:H("source",{enum:["user","session","system"]}).notNull().default("user"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({kindIdx:uD("files_kind_idx").on(D.kind),pathUniqueIdx:a0("files_workspace_path_idx").on(D.workspaceId,D.path),workspaceUpdatedAtIdx:uD("files_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),wr=zD("artifacts",{id:H("id").primaryKey(),workspaceId:H("workspace_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),sessionId:H("session_id").references(()=>vD.id,{onDelete:"set null"}),turnId:H("turn_id").references(()=>OD.id,{onDelete:"set null"}),invocationId:H("invocation_id").references(()=>ND.id,{onDelete:"set null"}),path:H("path").notNull(),kind:H("kind").notNull().default("file"),title:H("title").notNull(),status:H("status",{enum:["available","missing","archived"]}).notNull().default("available"),metadataJson:H("metadata_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({sessionUpdatedAtIdx:uD("artifacts_session_updated_at_idx").on(D.sessionId,D.updatedAt),statusUpdatedAtIdx:uD("artifacts_status_updated_at_idx").on(D.status,D.updatedAt),workspaceUpdatedAtIdx:uD("artifacts_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),$r=zD("reviews",{id:H("id").primaryKey(),workspaceId:H("workspace_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),sessionId:H("session_id").references(()=>vD.id,{onDelete:"set null"}),turnId:H("turn_id").references(()=>OD.id,{onDelete:"set null"}),artifactId:H("artifact_id").references(()=>wr.id,{onDelete:"set null"}),verdict:H("verdict",{enum:["pass","warn","fail","needs_review"]}).notNull().default("needs_review"),findingsJson:H("findings_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),risksJson:H("risks_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),createdAt:H("created_at").notNull().$defaultFn($D)},(D)=>({artifactCreatedAtIdx:uD("reviews_artifact_created_at_idx").on(D.artifactId,D.createdAt),sessionCreatedAtIdx:uD("reviews_session_created_at_idx").on(D.sessionId,D.createdAt),workspaceCreatedAtIdx:uD("reviews_workspace_created_at_idx").on(D.workspaceId,D.createdAt)})),bu=zD("lessons",{id:H("id").primaryKey(),workspaceId:H("workspace_id").notNull().references(()=>TD.id,{onDelete:"cascade"}),sourceReviewId:H("source_review_id").references(()=>$r.id,{onDelete:"set null"}),statement:H("statement").notNull(),evidenceJson:H("evidence_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),status:H("status",{enum:["proposed","accepted","rejected"]}).notNull().default("proposed"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({statusUpdatedAtIdx:uD("lessons_status_updated_at_idx").on(D.status,D.updatedAt),workspaceUpdatedAtIdx:uD("lessons_workspace_updated_at_idx").on(D.workspaceId,D.updatedAt)})),Bu=zD("soul_apps",{id:H("id").primaryKey(),name:H("name").notNull(),version:H("version").notNull(),protocol:H("protocol").notNull(),soulId:H("soul_id").notNull(),status:H("status",{enum:["installed","enabled","disabled","error"]}).$type().notNull().default("installed"),sourceKind:H("source_kind",{enum:["manifest-path","inline"]}).$type().notNull(),sourceRef:H("source_ref").notNull(),manifestDigest:H("manifest_digest").notNull(),manifestJson:H("manifest_json",{mode:"json"}).$type().notNull(),validationIssuesJson:H("validation_issues_json",{mode:"json"}).$type().notNull().$defaultFn(()=>[]),healthStatus:H("health_status",{enum:["unknown","pass","warn","fail"]}).$type().notNull().default("unknown"),healthMessage:H("health_message"),installedAt:H("installed_at").notNull().$defaultFn($D),enabledAt:H("enabled_at"),disabledAt:H("disabled_at"),lastHealthcheckAt:H("last_healthcheck_at"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({digestIdx:uD("soul_apps_manifest_digest_idx").on(D.manifestDigest),soulIdx:uD("soul_apps_soul_idx").on(D.soulId),statusUpdatedAtIdx:uD("soul_apps_status_updated_at_idx").on(D.status,D.updatedAt)})),su=zD("soul_app_storage_records",{id:H("id").primaryKey(),appId:H("app_id").notNull().references(()=>Bu.id,{onDelete:"cascade"}),namespace:H("namespace").notNull(),key:H("key").notNull(),valueJson:H("value_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),workerId:H("worker_id").references(()=>jD.id,{onDelete:"set null"}),workspaceId:H("workspace_id").references(()=>TD.id,{onDelete:"set null"}),sessionId:H("session_id").references(()=>vD.id,{onDelete:"set null"}),operatorId:H("operator_id"),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)},(D)=>({appKeyIdx:a0("soul_app_storage_app_key_idx").on(D.appId,D.key),appUpdatedAtIdx:uD("soul_app_storage_app_updated_at_idx").on(D.appId,D.updatedAt),namespaceIdx:uD("soul_app_storage_namespace_idx").on(D.namespace),workspaceIdx:uD("soul_app_storage_workspace_idx").on(D.workspaceId)})),Er=zD("soul_app_audit_events",{id:Hu("id").primaryKey({autoIncrement:!0}),appId:H("app_id").notNull().references(()=>Bu.id,{onDelete:"cascade"}),action:H("action").notNull(),targetKind:H("target_kind").notNull(),target:H("target").notNull(),decision:H("decision",{enum:["allowed","denied"]}).notNull(),reason:H("reason").notNull(),workerId:H("worker_id").references(()=>jD.id,{onDelete:"set null"}),workspaceId:H("workspace_id").references(()=>TD.id,{onDelete:"set null"}),sessionId:H("session_id").references(()=>vD.id,{onDelete:"set null"}),operatorId:H("operator_id"),requestJson:H("request_json",{mode:"json"}).$type().notNull().$defaultFn(()=>({})),createdAt:H("created_at").notNull().$defaultFn($D)},(D)=>({appCreatedAtIdx:uD("soul_app_audit_app_created_at_idx").on(D.appId,D.createdAt),contextIdx:uD("soul_app_audit_context_idx").on(D.workspaceId,D.sessionId),targetIdx:uD("soul_app_audit_target_idx").on(D.targetKind,D.target)})),Nr=zD("settings",{key:H("key").primaryKey(),valueJson:H("value_json",{mode:"json"}).$type().notNull(),updatedAt:H("updated_at").notNull().$defaultFn($D)}),GC=zD("worker_identity",{pk:H("pk").primaryKey().default("default"),workerId:H("worker_id").notNull().unique(),apiTokenEnc:H("api_token_enc").notNull(),nonce:H("nonce").notNull(),authTag:H("auth_tag").notNull(),bootstrapShownAt:H("bootstrap_shown_at").notNull().$defaultFn($D),createdAt:H("created_at").notNull().$defaultFn($D),rotatedAt:H("rotated_at")}),CC=zD("worker_config",{pk:H("pk").primaryKey().default("default"),configJson:H("config_json",{mode:"json"}).$type().notNull(),version:Hu("version").notNull().default(1),updatedAt:H("updated_at").notNull().$defaultFn($D),updatedBy:H("updated_by",{enum:["bootstrap","api","cli"]})}),HC=zD("worker_secrets",{id:Hu("id").primaryKey({autoIncrement:!0}),key:H("key").notNull().unique(),valueEnc:H("value_enc").notNull(),nonce:H("nonce").notNull(),authTag:H("auth_tag").notNull(),createdAt:H("created_at").notNull().$defaultFn($D),updatedAt:H("updated_at").notNull().$defaultFn($D)})});import{existsSync as rE}from"fs";import NF from"path";import{fileURLToPath as XC}from"url";import{Database as iC}from"bun:sqlite";function UC(D){let u=NF.resolve(AE,"../../drizzle",D);if(rE(u))return u;let r=NF.resolve(AE,"drizzle",D);if(rE(r))return r;return u}function YC(D){let u=new iC(D,{create:!0});return u.exec("PRAGMA journal_mode = WAL"),u.exec("PRAGMA foreign_keys = ON"),G8(u,{schema:KF})}function WA(D){return BA=YC(D),BA}function z(){if(!BA)throw Error("Worker database not initialized. Call initWorkerDb() first.");return BA}function r2(){BA=null}function JA(D=bF){DE(z(),{migrationsFolder:D}),MC()}function MC(){let u=z().all(G.raw('PRAGMA index_list("workers")')).find((r)=>r.name==="workers_soul_idx");if(u?.unique===1)z().run(G.raw("DROP INDEX IF EXISTS workers_soul_idx"));if(!u||u.unique===1)z().run(G.raw("CREATE INDEX IF NOT EXISTS workers_soul_idx ON workers (soul_id)"))}function A2(D){let u=D.at??new Date().toISOString(),r=PD(D.id);if(!r)z().insert(jD).values({id:D.id,soulId:D.soulId,name:D.name,status:D.status??"active",defaultEngineId:D.defaultEngineId??null,metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run();else z().update(jD).set({defaultEngineId:D.defaultEngineId??r.defaultEngineId,metadataJson:D.metadataJson??r.metadataJson,name:D.name,soulId:D.soulId,status:D.status??r.status,updatedAt:u}).where(d(jD.id,D.id)).run();return PD(D.id)}function PD(D){return z().select().from(jD).where(d(jD.id,D)).get()??null}function gr(D=100){return z().select().from(jD).orderBy(jD.id).limit(D).all()}function FE(D){let u=D.at??new Date().toISOString();return z().insert(TD).values({id:D.id,workerId:D.workerId,name:D.name,rootPath:D.rootPath,type:D.type??"workspace",status:D.status??"active",sourcePointersJson:D.sourcePointersJson??[],metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),Du(D.id)}function Du(D){return z().select().from(TD).where(d(TD.id,D)).get()??null}function sF(D){let u=Du(D.id);if(!u)throw Error(`Workspace not found: ${D.id}`);return z().update(TD).set({metadataJson:D.metadataJson??u.metadataJson,name:D.name??u.name,sourcePointersJson:D.sourcePointersJson??u.sourcePointersJson,status:D.status??u.status,updatedAt:D.at??new Date().toISOString()}).where(d(TD.id,D.id)).run(),Du(D.id)}function Xu(D,u=200){let r=z().select().from(TD);if(D)return r.where(d(TD.workerId,D)).orderBy(JD(TD.updatedAt)).limit(u).all();return r.orderBy(JD(TD.updatedAt)).limit(u).all()}function wE(D){let u=D.at??new Date().toISOString();return z().insert(vD).values({id:D.id,workerId:D.workerId,workspaceId:D.workspaceId,capabilityTemplateId:D.capabilityTemplateId,title:D.title,context:D.context??"",status:D.status??"active",metadataJson:D.metadataJson??{},startedAt:D.startedAt??u,endedAt:D.endedAt??null,createdAt:u,updatedAt:u}).run(),wu(D.id)}function wu(D){return z().select().from(vD).where(d(vD.id,D)).get()??null}function zF(D){let u=wu(D.id);if(!u)throw Error(`Session not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return z().update(vD).set({context:D.context??u.context,endedAt:r("endedAt")?D.endedAt??null:u.endedAt,metadataJson:D.metadataJson??u.metadataJson,startedAt:r("startedAt")?D.startedAt??null:u.startedAt,status:D.status??u.status,title:D.title??u.title,updatedAt:D.at??new Date().toISOString()}).where(d(vD.id,D.id)).run(),wu(D.id)}function tr(D,u=200){let r=z().select().from(vD);if(D)return r.where(d(vD.workspaceId,D)).orderBy(JD(vD.updatedAt)).limit(u).all();return r.orderBy(JD(vD.updatedAt)).limit(u).all()}function $E(D){let u=[...new Set(D.soulIds)].sort(),r=0;for(let A of u){let f=z().select({id:jD.id}).from(jD).where(d(jD.soulId,A)).all();if(f.length===0)continue;z().delete(jD).where(d(jD.soulId,A)).run(),r+=f.length}return{legacySoulIds:u,workersDeleted:r}}function EE(D){let u=D.at??new Date().toISOString();return z().insert(OD).values({id:D.id,sessionId:D.sessionId,seq:D.seq,input:D.input,response:D.response??null,status:D.status??"queued",error:D.error??null,metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),QF(D.id)}function QF(D){return z().select().from(OD).where(d(OD.id,D)).get()??null}function jF(D){let u=QF(D.id);if(!u)throw Error(`Turn not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return z().update(OD).set({error:r("error")?D.error??null:u.error,metadataJson:D.metadataJson??u.metadataJson,response:r("response")?D.response??null:u.response,status:D.status??u.status,updatedAt:D.at??new Date().toISOString()}).where(d(OD.id,D.id)).run(),QF(D.id)}function Sr(D,u=200){let r=z().select().from(OD);if(D)return r.where(d(OD.sessionId,D)).orderBy(OD.seq).limit(u).all();return r.orderBy(JD(OD.updatedAt)).limit(u).all()}function gE(D){return(z().select({seq:OD.seq}).from(OD).where(d(OD.sessionId,D)).orderBy(JD(OD.seq)).limit(1).get()?.seq??0)+1}function SE(D){let u=D.at??new Date().toISOString();return z().insert(ND).values({id:D.id,sessionId:D.sessionId,turnId:D.turnId,seq:D.seq,engineId:D.engineId,engineCommand:D.engineCommand??null,status:D.status??"queued",prompt:D.prompt,summary:D.summary??null,error:D.error??null,metadataJson:D.metadataJson??{},startedAt:D.startedAt??null,finishedAt:D.finishedAt??null,createdAt:u,updatedAt:u}).run(),LF(D.id)}function LF(D){return z().select().from(ND).where(d(ND.id,D)).get()??null}function TF(D){let u=LF(D.id);if(!u)throw Error(`Engine invocation not found: ${D.id}`);let r=(A)=>Object.hasOwn(D,A);return z().update(ND).set({error:r("error")?D.error??null:u.error,finishedAt:r("finishedAt")?D.finishedAt??null:u.finishedAt,metadataJson:D.metadataJson??u.metadataJson,startedAt:r("startedAt")?D.startedAt??null:u.startedAt,status:D.status??u.status,summary:r("summary")?D.summary??null:u.summary,updatedAt:D.at??new Date().toISOString()}).where(d(ND.id,D.id)).run(),LF(D.id)}function _E(D,u=200){let r=z().select().from(ND);if(D)return r.where(d(ND.sessionId,D)).orderBy(JD(ND.updatedAt)).limit(u).all();return r.orderBy(JD(ND.updatedAt)).limit(u).all()}function RE(D){return(z().select({seq:ND.seq}).from(ND).where(d(ND.sessionId,D)).orderBy(JD(ND.seq)).limit(1).get()?.seq??0)+1}function nE(D){return z().insert(xD).values({sessionId:D.sessionId,turnId:D.turnId??null,invocationId:D.invocationId??null,seq:D.seq,type:D.type,payloadJson:D.payloadJson??{},createdAt:D.at??new Date().toISOString()}).run(),z().select().from(xD).where(hr(d(xD.sessionId,D.sessionId),d(xD.seq,D.seq))).get()}function BE(D){return(z().select({seq:xD.seq}).from(xD).where(d(xD.sessionId,D)).orderBy(JD(xD.seq)).limit(1).get()?.seq??0)+1}function _r(D,u=500){let r=z().select().from(xD);if(D)return r.where(d(xD.sessionId,D)).orderBy(xD.seq).limit(u).all();return r.orderBy(JD(xD.createdAt)).limit(u).all()}function GA(D){let u=D.at??new Date().toISOString(),r=z().select().from(Fu).where(hr(d(Fu.workspaceId,D.workspaceId),d(Fu.path,D.path))).get();if(!r)z().insert(Fu).values({id:D.id,workspaceId:D.workspaceId,path:D.path,kind:D.kind??"file",size:D.size??null,mtime:D.mtime??null,hash:D.hash??null,source:D.source??"user",createdAt:u,updatedAt:u}).run();else z().update(Fu).set({kind:D.kind??r.kind,size:D.size??r.size,mtime:D.mtime??r.mtime,hash:D.hash??r.hash,source:D.source??r.source,updatedAt:u}).where(d(Fu.id,r.id)).run();return z().select().from(Fu).where(d(Fu.id,r?.id??D.id)).get()}function zu(D,u=500){let r=z().select().from(Fu);if(D)return r.where(d(Fu.workspaceId,D)).orderBy(JD(Fu.updatedAt)).limit(u).all();return r.orderBy(JD(Fu.updatedAt)).limit(u).all()}function WE(D){let u=D.at??new Date().toISOString();return z().insert(wr).values({id:D.id,workspaceId:D.workspaceId,sessionId:D.sessionId??null,turnId:D.turnId??null,invocationId:D.invocationId??null,path:D.path,kind:D.kind??"file",title:D.title,status:D.status??"available",metadataJson:D.metadataJson??{},createdAt:u,updatedAt:u}).run(),pr(D.id)}function pr(D){return z().select().from(wr).where(d(wr.id,D)).get()??null}function Rr(D,u=200){let r=z().select().from(wr);if(D)return r.where(d(wr.workspaceId,D)).orderBy(JD(wr.updatedAt)).limit(u).all();return r.orderBy(JD(wr.updatedAt)).limit(u).all()}function P0(D){return z().insert($r).values({id:D.id,workspaceId:D.workspaceId,sessionId:D.sessionId??null,turnId:D.turnId??null,artifactId:D.artifactId??null,verdict:D.verdict??"needs_review",findingsJson:D.findingsJson??[],risksJson:D.risksJson??[],createdAt:D.at??new Date().toISOString()}).run(),CA(D.id)}function CA(D){return z().select().from($r).where(d($r.id,D)).get()??null}function f2(D,u=200){let r=z().select().from($r);if(D)return r.where(d($r.workspaceId,D)).orderBy(JD($r.createdAt)).limit(u).all();return r.orderBy(JD($r.createdAt)).limit(u).all()}function xr(D){let u=D.at??new Date().toISOString();return z().insert(bu).values({id:D.id,workspaceId:D.workspaceId,sourceReviewId:D.sourceReviewId??null,statement:D.statement,evidenceJson:D.evidenceJson??[],status:D.status??"proposed",createdAt:u,updatedAt:u}).run(),qF(D.id)}function qF(D){return z().select().from(bu).where(d(bu.id,D)).get()??null}function HA(D,u,r=new Date().toISOString()){if(!qF(D))throw Error(`Lesson not found: ${D}`);return z().update(bu).set({status:u,updatedAt:r}).where(d(bu.id,D)).run(),qF(D)}function F2(D,u=200){let r=z().select().from(bu);if(D)return r.where(d(bu.workspaceId,D)).orderBy(JD(bu.updatedAt)).limit(u).all();return r.orderBy(JD(bu.updatedAt)).limit(u).all()}function JE(D){let u=D.at??new Date().toISOString(),r=O0(D.id),A=D.status??r?.status??"installed",f=D.enabledAt??(A==="enabled"?r?.enabledAt??u:r?.enabledAt??null),w=D.disabledAt??(A==="disabled"?u:r?.disabledAt??null);if(!r)z().insert(Bu).values({id:D.id,name:D.name,version:D.version,protocol:D.protocol,soulId:D.soulId,status:A,sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:D.manifestDigest,manifestJson:D.manifestJson,validationIssuesJson:D.validationIssuesJson??[],healthStatus:D.healthStatus??"unknown",healthMessage:D.healthMessage??null,installedAt:D.installedAt??u,enabledAt:f,disabledAt:w,lastHealthcheckAt:D.lastHealthcheckAt??null,createdAt:u,updatedAt:u}).run();else z().update(Bu).set({name:D.name,version:D.version,protocol:D.protocol,soulId:D.soulId,status:A,sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:D.manifestDigest,manifestJson:D.manifestJson,validationIssuesJson:D.validationIssuesJson??r.validationIssuesJson,healthStatus:D.healthStatus??r.healthStatus,healthMessage:Object.hasOwn(D,"healthMessage")?D.healthMessage??null:r.healthMessage,installedAt:D.installedAt??r.installedAt,enabledAt:f,disabledAt:w,lastHealthcheckAt:D.lastHealthcheckAt??r.lastHealthcheckAt,updatedAt:u}).where(d(Bu.id,D.id)).run();return O0(D.id)}function O0(D){return z().select().from(Bu).where(d(Bu.id,D)).get()??null}function vF(D=200){return z().select().from(Bu).orderBy(Bu.id).limit(D).all()}function w2(D){let u=O0(D.id);if(!u)throw Error(`Soul App not found: ${D.id}`);let r=D.at??new Date().toISOString();return z().update(Bu).set({disabledAt:D.status==="disabled"?r:u.disabledAt,enabledAt:D.status==="enabled"?r:u.enabledAt,healthMessage:Object.hasOwn(D,"healthMessage")?D.healthMessage??null:u.healthMessage,healthStatus:D.healthStatus??u.healthStatus,lastHealthcheckAt:D.lastHealthcheckAt??u.lastHealthcheckAt,status:D.status,updatedAt:r,validationIssuesJson:D.validationIssuesJson??u.validationIssuesJson}).where(d(Bu.id,D.id)).run(),O0(D.id)}function GE(D){let u=D.at??new Date().toISOString(),r=C8(D.appId,D.key);if(!r)z().insert(su).values({appId:D.appId,createdAt:u,id:OC(D.appId,D.key),key:D.key,namespace:D.namespace,operatorId:D.operatorId??null,sessionId:D.sessionId??null,updatedAt:u,valueJson:D.valueJson,workerId:D.workerId??null,workspaceId:D.workspaceId??null}).run();else z().update(su).set({namespace:D.namespace,operatorId:D.operatorId??r.operatorId,sessionId:D.sessionId??r.sessionId,updatedAt:u,valueJson:D.valueJson,workerId:D.workerId??r.workerId,workspaceId:D.workspaceId??r.workspaceId}).where(d(su.id,r.id)).run();return C8(D.appId,D.key)}function C8(D,u){return z().select().from(su).where(hr(d(su.appId,D),d(su.key,u))).get()??null}function CE(D,u=200){return z().select().from(su).where(d(su.appId,D)).orderBy(JD(su.updatedAt)).limit(u).all()}function HE(D){return z().insert(Er).values({action:D.action,appId:D.appId,createdAt:D.at??new Date().toISOString(),decision:D.decision,operatorId:D.operatorId??null,reason:D.reason,requestJson:D.requestJson??{},sessionId:D.sessionId??null,target:D.target,targetKind:D.targetKind,workerId:D.workerId??null,workspaceId:D.workspaceId??null}).run(),z().select().from(Er).where(d(Er.appId,D.appId)).orderBy(JD(Er.id)).limit(1).get()}function XE(D,u=500){let r=z().select().from(Er);if(D)return r.where(d(Er.appId,D)).orderBy(Er.id).limit(u).all();return r.orderBy(Er.id).limit(u).all()}function OC(D,u){return`${D}:${u}`}function fE(D){return z().select().from(Nr).where(d(Nr.key,D)).get()??null}function mr(){return z().select().from(Nr).orderBy(Nr.key).all()}function k0(D,u,r=new Date().toISOString()){if(!fE(D))z().insert(Nr).values({key:D,valueJson:u,updatedAt:r}).run();else z().update(Nr).set({valueJson:u,updatedAt:r}).where(d(Nr.key,D)).run();return fE(D)}var AE,bF,BA=null;var nr=W(()=>{c4();m5();uE();hF();hF();AE=NF.dirname(XC(import.meta.url));bF=UC("worker")});var DD,ZF,K,Br=(D)=>{switch(typeof D){case"undefined":return K.undefined;case"string":return K.string;case"number":return Number.isNaN(D)?K.nan:K.number;case"boolean":return K.boolean;case"function":return K.function;case"bigint":return K.bigint;case"symbol":return K.symbol;case"object":if(Array.isArray(D))return K.array;if(D===null)return K.null;if(D.then&&typeof D.then==="function"&&D.catch&&typeof D.catch==="function")return K.promise;if(typeof Map<"u"&&D instanceof Map)return K.map;if(typeof Set<"u"&&D instanceof Set)return K.set;if(typeof Date<"u"&&D instanceof Date)return K.date;return K.object;default:return K.unknown}};var XA=W(()=>{(function(D){D.assertEqual=(f)=>{};function u(f){}D.assertIs=u;function r(f){throw Error()}D.assertNever=r,D.arrayToEnum=(f)=>{let w={};for(let F of f)w[F]=F;return w},D.getValidEnumValues=(f)=>{let w=D.objectKeys(f).filter((E)=>typeof f[f[E]]!=="number"),F={};for(let E of w)F[E]=f[E];return D.objectValues(F)},D.objectValues=(f)=>{return D.objectKeys(f).map(function(w){return f[w]})},D.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{let w=[];for(let F in f)if(Object.prototype.hasOwnProperty.call(f,F))w.push(F);return w},D.find=(f,w)=>{for(let F of f)if(w(F))return F;return},D.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&Number.isFinite(f)&&Math.floor(f)===f;function A(f,w=" | "){return f.map((F)=>typeof F==="string"?`'${F}'`:F).join(w)}D.joinValues=A,D.jsonStringifyReplacer=(f,w)=>{if(typeof w==="bigint")return w.toString();return w}})(DD||(DD={}));(function(D){D.mergeShapes=(u,r)=>{return{...u,...r}}})(ZF||(ZF={}));K=DD.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var O,PC=(D)=>{return JSON.stringify(D,null,2).replace(/"([^"]+)":/g,"$1:")},$u;var H8=W(()=>{XA();O=DD.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);$u=class $u extends Error{get errors(){return this.issues}constructor(D){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let u=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,u);else this.__proto__=u;this.name="ZodError",this.issues=D}format(D){let u=D||function(f){return f.message},r={_errors:[]},A=(f)=>{for(let w of f.issues)if(w.code==="invalid_union")w.unionErrors.map(A);else if(w.code==="invalid_return_type")A(w.returnTypeError);else if(w.code==="invalid_arguments")A(w.argumentsError);else if(w.path.length===0)r._errors.push(u(w));else{let F=r,E=0;while(E<w.path.length){let $=w.path[E];if(E!==w.path.length-1)F[$]=F[$]||{_errors:[]};else F[$]=F[$]||{_errors:[]},F[$]._errors.push(u(w));F=F[$],E++}}};return A(this),r}static assert(D){if(!(D instanceof $u))throw Error(`Not a ZodError: ${D}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,DD.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(D=(u)=>u.message){let u={},r=[];for(let A of this.issues)if(A.path.length>0){let f=A.path[0];u[f]=u[f]||[],u[f].push(D(A))}else r.push(D(A));return{formErrors:r,fieldErrors:u}}get formErrors(){return this.flatten()}};$u.create=(D)=>{return new $u(D)}});var kC=(D,u)=>{let r;switch(D.code){case O.invalid_type:if(D.received===K.undefined)r="Required";else r=`Expected ${D.expected}, received ${D.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(D.expected,DD.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${DD.joinValues(D.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${DD.joinValues(D.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${DD.joinValues(D.options)}, received '${D.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:if(typeof D.validation==="object")if("includes"in D.validation){if(r=`Invalid input: must include "${D.validation.includes}"`,typeof D.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${D.validation.position}`}else if("startsWith"in D.validation)r=`Invalid input: must start with "${D.validation.startsWith}"`;else if("endsWith"in D.validation)r=`Invalid input: must end with "${D.validation.endsWith}"`;else DD.assertNever(D.validation);else if(D.validation!=="regex")r=`Invalid ${D.validation}`;else r="Invalid";break;case O.too_small:if(D.type==="array")r=`Array must contain ${D.exact?"exactly":D.inclusive?"at least":"more than"} ${D.minimum} element(s)`;else if(D.type==="string")r=`String must contain ${D.exact?"exactly":D.inclusive?"at least":"over"} ${D.minimum} character(s)`;else if(D.type==="number")r=`Number must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${D.minimum}`;else if(D.type==="bigint")r=`Number must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${D.minimum}`;else if(D.type==="date")r=`Date must be ${D.exact?"exactly equal to ":D.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(D.minimum))}`;else r="Invalid input";break;case O.too_big:if(D.type==="array")r=`Array must contain ${D.exact?"exactly":D.inclusive?"at most":"less than"} ${D.maximum} element(s)`;else if(D.type==="string")r=`String must contain ${D.exact?"exactly":D.inclusive?"at most":"under"} ${D.maximum} character(s)`;else if(D.type==="number")r=`Number must be ${D.exact?"exactly":D.inclusive?"less than or equal to":"less than"} ${D.maximum}`;else if(D.type==="bigint")r=`BigInt must be ${D.exact?"exactly":D.inclusive?"less than or equal to":"less than"} ${D.maximum}`;else if(D.type==="date")r=`Date must be ${D.exact?"exactly":D.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(D.maximum))}`;else r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${D.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=u.defaultError,DD.assertNever(D)}return{message:r}},Qr;var oF=W(()=>{H8();XA();Qr=kC});function IC(D){iE=D}function $2(){return iE}var iE;var X8=W(()=>{oF();iE=Qr});function Q(D,u){let r=$2(),A=iA({issueData:u,data:D.data,path:D.path,errorMaps:[D.common.contextualErrorMap,D.schemaErrorMap,r,r===Qr?void 0:Qr].filter((f)=>!!f)});D.common.issues.push(A)}class lD{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(D,u){let r=[];for(let A of u){if(A.status==="aborted")return o;if(A.status==="dirty")D.dirty();r.push(A.value)}return{status:D.value,value:r}}static async mergeObjectAsync(D,u){let r=[];for(let A of u){let f=await A.key,w=await A.value;r.push({key:f,value:w})}return lD.mergeObjectSync(D,r)}static mergeObjectSync(D,u){let r={};for(let A of u){let{key:f,value:w}=A;if(f.status==="aborted")return o;if(w.status==="aborted")return o;if(f.status==="dirty")D.dirty();if(w.status==="dirty")D.dirty();if(f.value!=="__proto__"&&(typeof w.value<"u"||A.alwaysSet))r[f.value]=w.value}return{status:D.value,value:r}}}var iA=(D)=>{let{data:u,path:r,errorMaps:A,issueData:f}=D,w=[...r,...f.path||[]],F={...f,path:w};if(f.message!==void 0)return{...f,path:w,message:f.message};let E="",$=A.filter((g)=>!!g).slice().reverse();for(let g of $)E=g(F,{data:u,defaultError:E}).message;return{...f,path:w,message:E}},VC,o,I0=(D)=>({status:"dirty",value:D}),mD=(D)=>({status:"valid",value:D}),i8=(D)=>D.status==="aborted",U8=(D)=>D.status==="dirty",ar=(D)=>D.status==="valid",E2=(D)=>typeof Promise<"u"&&D instanceof Promise;var dF=W(()=>{X8();oF();VC=[];o=Object.freeze({status:"aborted"})});var UE=()=>{};var j;var YE=W(()=>{(function(D){D.errToObj=(u)=>typeof u==="string"?{message:u}:u||{},D.toString=(u)=>typeof u==="string"?u:u?.message})(j||(j={}))});class Zu{constructor(D,u,r,A){this._cachedPath=[],this.parent=D,this.data=u,this._path=r,this._key=A}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function t(D){if(!D)return{};let{errorMap:u,invalid_type_error:r,required_error:A,description:f}=D;if(u&&(r||A))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(u)return{errorMap:u,description:f};return{errorMap:(F,E)=>{let{message:$}=D;if(F.code==="invalid_enum_value")return{message:$??E.defaultError};if(typeof E.data>"u")return{message:$??A??E.defaultError};if(F.code!=="invalid_type")return{message:E.defaultError};return{message:$??r??E.defaultError}},description:f}}class p{get description(){return this._def.description}_getType(D){return Br(D.data)}_getOrReturnCtx(D,u){return u||{common:D.parent.common,data:D.data,parsedType:Br(D.data),schemaErrorMap:this._def.errorMap,path:D.path,parent:D.parent}}_processInputParams(D){return{status:new lD,ctx:{common:D.parent.common,data:D.data,parsedType:Br(D.data),schemaErrorMap:this._def.errorMap,path:D.path,parent:D.parent}}}_parseSync(D){let u=this._parse(D);if(E2(u))throw Error("Synchronous parse encountered promise.");return u}_parseAsync(D){let u=this._parse(D);return Promise.resolve(u)}parse(D,u){let r=this.safeParse(D,u);if(r.success)return r.data;throw r.error}safeParse(D,u){let r={common:{issues:[],async:u?.async??!1,contextualErrorMap:u?.errorMap},path:u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)},A=this._parseSync({data:D,path:r.path,parent:r});return ME(r,A)}"~validate"(D){let u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)};if(!this["~standard"].async)try{let r=this._parseSync({data:D,path:[],parent:u});return ar(r)?{value:r.value}:{issues:u.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;u.common={issues:[],async:!0}}return this._parseAsync({data:D,path:[],parent:u}).then((r)=>ar(r)?{value:r.value}:{issues:u.common.issues})}async parseAsync(D,u){let r=await this.safeParseAsync(D,u);if(r.success)return r.data;throw r.error}async safeParseAsync(D,u){let r={common:{issues:[],contextualErrorMap:u?.errorMap,async:!0},path:u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:D,parsedType:Br(D)},A=this._parse({data:D,path:r.path,parent:r}),f=await(E2(A)?A:Promise.resolve(A));return ME(r,f)}refine(D,u){let r=(A)=>{if(typeof u==="string"||typeof u>"u")return{message:u};else if(typeof u==="function")return u(A);else return u};return this._refinement((A,f)=>{let w=D(A),F=()=>f.addIssue({code:O.custom,...r(A)});if(typeof Promise<"u"&&w instanceof Promise)return w.then((E)=>{if(!E)return F(),!1;else return!0});if(!w)return F(),!1;else return!0})}refinement(D,u){return this._refinement((r,A)=>{if(!D(r))return A.addIssue(typeof u==="function"?u(r,A):u),!1;else return!0})}_refinement(D){return new ou({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:D}})}superRefine(D){return this._refinement(D)}constructor(D){this.spa=this.safeParseAsync,this._def=D,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(u)=>this["~validate"](u)}}optional(){return vu.create(this,this._def)}nullable(){return qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tu.create(this)}promise(){return N0.create(this,this._def)}or(D){return B2.create([this,D],this._def)}and(D){return W2.create(this,D,this._def)}transform(D){return new ou({...t(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:D}})}default(D){let u=typeof D==="function"?D:()=>D;return new H2({...t(this._def),innerType:this,defaultValue:u,typeName:l.ZodDefault})}brand(){return new M8({typeName:l.ZodBranded,type:this,...t(this._def)})}catch(D){let u=typeof D==="function"?D:()=>D;return new X2({...t(this._def),innerType:this,catchValue:u,typeName:l.ZodCatch})}describe(D){return new this.constructor({...this._def,description:D})}pipe(D){return kA.create(this,D)}readonly(){return i2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function kE(D){let u="[0-5]\\d";if(D.precision)u=`${u}\\.\\d{${D.precision}}`;else if(D.precision==null)u=`${u}(\\.\\d+)?`;let r=D.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${u})${r}`}function yC(D){return new RegExp(`^${kE(D)}$`)}function IE(D){let u=`${PE}T${kE(D)}`,r=[];if(r.push(D.local?"Z?":"Z"),D.offset)r.push("([+-]\\d{2}:?\\d{2})");return u=`${u}(${r.join("|")})`,new RegExp(`^${u}$`)}function cC(D,u){if((u==="v4"||!u)&&jC.test(D))return!0;if((u==="v6"||!u)&&vC.test(D))return!0;return!1}function tC(D,u){if(!qC.test(D))return!1;try{let[r]=D.split(".");if(!r)return!1;let A=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),f=JSON.parse(atob(A));if(typeof f!=="object"||f===null)return!1;if("typ"in f&&f?.typ!=="JWT")return!1;if(!f.alg)return!1;if(u&&f.alg!==u)return!1;return!0}catch{return!1}}function pC(D,u){if((u==="v4"||!u)&&TC.test(D))return!0;if((u==="v6"||!u)&&ZC.test(D))return!0;return!1}function xC(D,u){let r=(D.toString().split(".")[1]||"").length,A=(u.toString().split(".")[1]||"").length,f=r>A?r:A,w=Number.parseInt(D.toFixed(f).replace(".","")),F=Number.parseInt(u.toFixed(f).replace(".",""));return w%F/10**f}function g2(D){if(D instanceof XD){let u={};for(let r in D.shape){let A=D.shape[r];u[r]=vu.create(g2(A))}return new XD({...D._def,shape:()=>u})}else if(D instanceof Tu)return new Tu({...D._def,type:g2(D.element)});else if(D instanceof vu)return vu.create(g2(D.unwrap()));else if(D instanceof qr)return qr.create(g2(D.unwrap()));else if(D instanceof Jr)return Jr.create(D.items.map((u)=>g2(u)));else return D}function yF(D,u){let r=Br(D),A=Br(u);if(D===u)return{valid:!0,data:D};else if(r===K.object&&A===K.object){let f=DD.objectKeys(u),w=DD.objectKeys(D).filter((E)=>f.indexOf(E)!==-1),F={...D,...u};for(let E of w){let $=yF(D[E],u[E]);if(!$.valid)return{valid:!1};F[E]=$.data}return{valid:!0,data:F}}else if(r===K.array&&A===K.array){if(D.length!==u.length)return{valid:!1};let f=[];for(let w=0;w<D.length;w++){let F=D[w],E=u[w],$=yF(F,E);if(!$.valid)return{valid:!1};f.push($.data)}return{valid:!0,data:f}}else if(r===K.date&&A===K.date&&+D===+u)return{valid:!0,data:D};else return{valid:!1}}function VE(D,u){return new r0({values:D,typeName:l.ZodEnum,...t(u)})}function OE(D,u){let r=typeof D==="function"?D(u):typeof D==="string"?{message:D}:D;return typeof r==="string"?{message:r}:r}function KE(D,u={},r){if(D)return K0.create().superRefine((A,f)=>{let w=D(A);if(w instanceof Promise)return w.then((F)=>{if(!F){let E=OE(u,A),$=E.fatal??r??!0;f.addIssue({code:"custom",...E,fatal:$})}});if(!w){let F=OE(u,A),E=F.fatal??r??!0;f.addIssue({code:"custom",...F,fatal:E})}return});return K0.create()}var ME=(D,u)=>{if(ar(u))return{success:!0,data:u.value};else{if(!D.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new $u(D.common.issues);return this._error=r,this._error}}}},KC,hC,NC,QC,LC,qC,bC,sC,zC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lF,jC,TC,vC,ZC,oC,dC,PE="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lC,ju,D0,u0,_2,V0,UA,R2,n2,K0,er,Wr,YA,Tu,XD,B2,Lr=(D)=>{if(D instanceof J2)return Lr(D.schema);else if(D instanceof ou)return Lr(D.innerType());else if(D instanceof G2)return[D.value];else if(D instanceof r0)return D.options;else if(D instanceof C2)return DD.objectValues(D.enum);else if(D instanceof H2)return Lr(D._def.innerType);else if(D instanceof R2)return[void 0];else if(D instanceof n2)return[null];else if(D instanceof vu)return[void 0,...Lr(D.unwrap())];else if(D instanceof qr)return[null,...Lr(D.unwrap())];else if(D instanceof M8)return Lr(D.unwrap());else if(D instanceof i2)return Lr(D.unwrap());else if(D instanceof X2)return Lr(D._def.innerType);else return[]},Y8,W2,Jr,MA,OA,h0,S2,J2,G2,r0,C2,N0,ou,vu,qr,H2,X2,PA,mC,M8,kA,i2,aC,l,eC=(D,u={message:`Input not instance of ${D.name}`})=>KE((r)=>r instanceof D,u),hE,NE,DH,uH,QE,rH,AH,fH,FH,wH,$H,EH,gH,SH,_H,RH,nH,BH,WH,JH,GH,CH,HH,XH,iH,UH,YH,MH,OH,PH,kH,IH,VH,KH,hH=()=>hE().optional(),NH=()=>NE().optional(),QH=()=>QE().optional(),LH,qH;var LE=W(()=>{H8();X8();YE();dF();XA();KC=/^c[^\s-]{8,}$/i,hC=/^[0-9a-z]+$/,NC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QC=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,LC=/^[a-z0-9_-]{21}$/i,qC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bC=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jC=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,TC=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,vC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ZC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,oC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lC=new RegExp(`^${PE}$`);ju=class ju extends p{_parse(D){if(this._def.coerce)D.data=String(D.data);if(this._getType(D)!==K.string){let f=this._getOrReturnCtx(D);return Q(f,{code:O.invalid_type,expected:K.string,received:f.parsedType}),o}let r=new lD,A=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(D.data.length<f.value)A=this._getOrReturnCtx(D,A),Q(A,{code:O.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),r.dirty()}else if(f.kind==="max"){if(D.data.length>f.value)A=this._getOrReturnCtx(D,A),Q(A,{code:O.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),r.dirty()}else if(f.kind==="length"){let w=D.data.length>f.value,F=D.data.length<f.value;if(w||F){if(A=this._getOrReturnCtx(D,A),w)Q(A,{code:O.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(F)Q(A,{code:O.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});r.dirty()}}else if(f.kind==="email"){if(!sC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"email",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="emoji"){if(!lF)lF=new RegExp(zC,"u");if(!lF.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"emoji",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="uuid"){if(!QC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"uuid",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="nanoid"){if(!LC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"nanoid",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cuid"){if(!KC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"cuid",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cuid2"){if(!hC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"cuid2",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="ulid"){if(!NC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"ulid",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="url")try{new URL(D.data)}catch{A=this._getOrReturnCtx(D,A),Q(A,{validation:"url",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"regex",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="trim")D.data=D.data.trim();else if(f.kind==="includes"){if(!D.data.includes(f.value,f.position))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),r.dirty()}else if(f.kind==="toLowerCase")D.data=D.data.toLowerCase();else if(f.kind==="toUpperCase")D.data=D.data.toUpperCase();else if(f.kind==="startsWith"){if(!D.data.startsWith(f.value))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:{startsWith:f.value},message:f.message}),r.dirty()}else if(f.kind==="endsWith"){if(!D.data.endsWith(f.value))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:{endsWith:f.value},message:f.message}),r.dirty()}else if(f.kind==="datetime"){if(!IE(f).test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:"datetime",message:f.message}),r.dirty()}else if(f.kind==="date"){if(!lC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:"date",message:f.message}),r.dirty()}else if(f.kind==="time"){if(!yC(f).test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{code:O.invalid_string,validation:"time",message:f.message}),r.dirty()}else if(f.kind==="duration"){if(!bC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"duration",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="ip"){if(!cC(D.data,f.version))A=this._getOrReturnCtx(D,A),Q(A,{validation:"ip",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="jwt"){if(!tC(D.data,f.alg))A=this._getOrReturnCtx(D,A),Q(A,{validation:"jwt",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="cidr"){if(!pC(D.data,f.version))A=this._getOrReturnCtx(D,A),Q(A,{validation:"cidr",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="base64"){if(!oC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"base64",code:O.invalid_string,message:f.message}),r.dirty()}else if(f.kind==="base64url"){if(!dC.test(D.data))A=this._getOrReturnCtx(D,A),Q(A,{validation:"base64url",code:O.invalid_string,message:f.message}),r.dirty()}else DD.assertNever(f);return{status:r.value,value:D.data}}_regex(D,u,r){return this.refinement((A)=>D.test(A),{validation:u,code:O.invalid_string,...j.errToObj(r)})}_addCheck(D){return new ju({...this._def,checks:[...this._def.checks,D]})}email(D){return this._addCheck({kind:"email",...j.errToObj(D)})}url(D){return this._addCheck({kind:"url",...j.errToObj(D)})}emoji(D){return this._addCheck({kind:"emoji",...j.errToObj(D)})}uuid(D){return this._addCheck({kind:"uuid",...j.errToObj(D)})}nanoid(D){return this._addCheck({kind:"nanoid",...j.errToObj(D)})}cuid(D){return this._addCheck({kind:"cuid",...j.errToObj(D)})}cuid2(D){return this._addCheck({kind:"cuid2",...j.errToObj(D)})}ulid(D){return this._addCheck({kind:"ulid",...j.errToObj(D)})}base64(D){return this._addCheck({kind:"base64",...j.errToObj(D)})}base64url(D){return this._addCheck({kind:"base64url",...j.errToObj(D)})}jwt(D){return this._addCheck({kind:"jwt",...j.errToObj(D)})}ip(D){return this._addCheck({kind:"ip",...j.errToObj(D)})}cidr(D){return this._addCheck({kind:"cidr",...j.errToObj(D)})}datetime(D){if(typeof D==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:D});return this._addCheck({kind:"datetime",precision:typeof D?.precision>"u"?null:D?.precision,offset:D?.offset??!1,local:D?.local??!1,...j.errToObj(D?.message)})}date(D){return this._addCheck({kind:"date",message:D})}time(D){if(typeof D==="string")return this._addCheck({kind:"time",precision:null,message:D});return this._addCheck({kind:"time",precision:typeof D?.precision>"u"?null:D?.precision,...j.errToObj(D?.message)})}duration(D){return this._addCheck({kind:"duration",...j.errToObj(D)})}regex(D,u){return this._addCheck({kind:"regex",regex:D,...j.errToObj(u)})}includes(D,u){return this._addCheck({kind:"includes",value:D,position:u?.position,...j.errToObj(u?.message)})}startsWith(D,u){return this._addCheck({kind:"startsWith",value:D,...j.errToObj(u)})}endsWith(D,u){return this._addCheck({kind:"endsWith",value:D,...j.errToObj(u)})}min(D,u){return this._addCheck({kind:"min",value:D,...j.errToObj(u)})}max(D,u){return this._addCheck({kind:"max",value:D,...j.errToObj(u)})}length(D,u){return this._addCheck({kind:"length",value:D,...j.errToObj(u)})}nonempty(D){return this.min(1,j.errToObj(D))}trim(){return new ju({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ju({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ju({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((D)=>D.kind==="datetime")}get isDate(){return!!this._def.checks.find((D)=>D.kind==="date")}get isTime(){return!!this._def.checks.find((D)=>D.kind==="time")}get isDuration(){return!!this._def.checks.find((D)=>D.kind==="duration")}get isEmail(){return!!this._def.checks.find((D)=>D.kind==="email")}get isURL(){return!!this._def.checks.find((D)=>D.kind==="url")}get isEmoji(){return!!this._def.checks.find((D)=>D.kind==="emoji")}get isUUID(){return!!this._def.checks.find((D)=>D.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((D)=>D.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((D)=>D.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((D)=>D.kind==="cuid2")}get isULID(){return!!this._def.checks.find((D)=>D.kind==="ulid")}get isIP(){return!!this._def.checks.find((D)=>D.kind==="ip")}get isCIDR(){return!!this._def.checks.find((D)=>D.kind==="cidr")}get isBase64(){return!!this._def.checks.find((D)=>D.kind==="base64")}get isBase64url(){return!!this._def.checks.find((D)=>D.kind==="base64url")}get minLength(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxLength(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}};ju.create=(D)=>{return new ju({checks:[],typeName:l.ZodString,coerce:D?.coerce??!1,...t(D)})};D0=class D0 extends p{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(D){if(this._def.coerce)D.data=Number(D.data);if(this._getType(D)!==K.number){let f=this._getOrReturnCtx(D);return Q(f,{code:O.invalid_type,expected:K.number,received:f.parsedType}),o}let r=void 0,A=new lD;for(let f of this._def.checks)if(f.kind==="int"){if(!DD.isInteger(D.data))r=this._getOrReturnCtx(D,r),Q(r,{code:O.invalid_type,expected:"integer",received:"float",message:f.message}),A.dirty()}else if(f.kind==="min"){if(f.inclusive?D.data<f.value:D.data<=f.value)r=this._getOrReturnCtx(D,r),Q(r,{code:O.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),A.dirty()}else if(f.kind==="max"){if(f.inclusive?D.data>f.value:D.data>=f.value)r=this._getOrReturnCtx(D,r),Q(r,{code:O.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),A.dirty()}else if(f.kind==="multipleOf"){if(xC(D.data,f.value)!==0)r=this._getOrReturnCtx(D,r),Q(r,{code:O.not_multiple_of,multipleOf:f.value,message:f.message}),A.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(D.data))r=this._getOrReturnCtx(D,r),Q(r,{code:O.not_finite,message:f.message}),A.dirty()}else DD.assertNever(f);return{status:A.value,value:D.data}}gte(D,u){return this.setLimit("min",D,!0,j.toString(u))}gt(D,u){return this.setLimit("min",D,!1,j.toString(u))}lte(D,u){return this.setLimit("max",D,!0,j.toString(u))}lt(D,u){return this.setLimit("max",D,!1,j.toString(u))}setLimit(D,u,r,A){return new D0({...this._def,checks:[...this._def.checks,{kind:D,value:u,inclusive:r,message:j.toString(A)}]})}_addCheck(D){return new D0({...this._def,checks:[...this._def.checks,D]})}int(D){return this._addCheck({kind:"int",message:j.toString(D)})}positive(D){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(D)})}negative(D){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(D)})}nonpositive(D){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(D)})}nonnegative(D){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(D)})}multipleOf(D,u){return this._addCheck({kind:"multipleOf",value:D,message:j.toString(u)})}finite(D){return this._addCheck({kind:"finite",message:j.toString(D)})}safe(D){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(D)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(D)})}get minValue(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxValue(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}get isInt(){return!!this._def.checks.find((D)=>D.kind==="int"||D.kind==="multipleOf"&&DD.isInteger(D.value))}get isFinite(){let D=null,u=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(u===null||r.value>u)u=r.value}else if(r.kind==="max"){if(D===null||r.value<D)D=r.value}return Number.isFinite(u)&&Number.isFinite(D)}};D0.create=(D)=>{return new D0({checks:[],typeName:l.ZodNumber,coerce:D?.coerce||!1,...t(D)})};u0=class u0 extends p{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(D){if(this._def.coerce)try{D.data=BigInt(D.data)}catch{return this._getInvalidInput(D)}if(this._getType(D)!==K.bigint)return this._getInvalidInput(D);let r=void 0,A=new lD;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?D.data<f.value:D.data<=f.value)r=this._getOrReturnCtx(D,r),Q(r,{code:O.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),A.dirty()}else if(f.kind==="max"){if(f.inclusive?D.data>f.value:D.data>=f.value)r=this._getOrReturnCtx(D,r),Q(r,{code:O.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),A.dirty()}else if(f.kind==="multipleOf"){if(D.data%f.value!==BigInt(0))r=this._getOrReturnCtx(D,r),Q(r,{code:O.not_multiple_of,multipleOf:f.value,message:f.message}),A.dirty()}else DD.assertNever(f);return{status:A.value,value:D.data}}_getInvalidInput(D){let u=this._getOrReturnCtx(D);return Q(u,{code:O.invalid_type,expected:K.bigint,received:u.parsedType}),o}gte(D,u){return this.setLimit("min",D,!0,j.toString(u))}gt(D,u){return this.setLimit("min",D,!1,j.toString(u))}lte(D,u){return this.setLimit("max",D,!0,j.toString(u))}lt(D,u){return this.setLimit("max",D,!1,j.toString(u))}setLimit(D,u,r,A){return new u0({...this._def,checks:[...this._def.checks,{kind:D,value:u,inclusive:r,message:j.toString(A)}]})}_addCheck(D){return new u0({...this._def,checks:[...this._def.checks,D]})}positive(D){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(D)})}negative(D){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(D)})}nonpositive(D){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(D)})}nonnegative(D){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(D)})}multipleOf(D,u){return this._addCheck({kind:"multipleOf",value:D,message:j.toString(u)})}get minValue(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D}get maxValue(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D}};u0.create=(D)=>{return new u0({checks:[],typeName:l.ZodBigInt,coerce:D?.coerce??!1,...t(D)})};_2=class _2 extends p{_parse(D){if(this._def.coerce)D.data=Boolean(D.data);if(this._getType(D)!==K.boolean){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.boolean,received:r.parsedType}),o}return mD(D.data)}};_2.create=(D)=>{return new _2({typeName:l.ZodBoolean,coerce:D?.coerce||!1,...t(D)})};V0=class V0 extends p{_parse(D){if(this._def.coerce)D.data=new Date(D.data);if(this._getType(D)!==K.date){let f=this._getOrReturnCtx(D);return Q(f,{code:O.invalid_type,expected:K.date,received:f.parsedType}),o}if(Number.isNaN(D.data.getTime())){let f=this._getOrReturnCtx(D);return Q(f,{code:O.invalid_date}),o}let r=new lD,A=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(D.data.getTime()<f.value)A=this._getOrReturnCtx(D,A),Q(A,{code:O.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),r.dirty()}else if(f.kind==="max"){if(D.data.getTime()>f.value)A=this._getOrReturnCtx(D,A),Q(A,{code:O.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),r.dirty()}else DD.assertNever(f);return{status:r.value,value:new Date(D.data.getTime())}}_addCheck(D){return new V0({...this._def,checks:[...this._def.checks,D]})}min(D,u){return this._addCheck({kind:"min",value:D.getTime(),message:j.toString(u)})}max(D,u){return this._addCheck({kind:"max",value:D.getTime(),message:j.toString(u)})}get minDate(){let D=null;for(let u of this._def.checks)if(u.kind==="min"){if(D===null||u.value>D)D=u.value}return D!=null?new Date(D):null}get maxDate(){let D=null;for(let u of this._def.checks)if(u.kind==="max"){if(D===null||u.value<D)D=u.value}return D!=null?new Date(D):null}};V0.create=(D)=>{return new V0({checks:[],coerce:D?.coerce||!1,typeName:l.ZodDate,...t(D)})};UA=class UA extends p{_parse(D){if(this._getType(D)!==K.symbol){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.symbol,received:r.parsedType}),o}return mD(D.data)}};UA.create=(D)=>{return new UA({typeName:l.ZodSymbol,...t(D)})};R2=class R2 extends p{_parse(D){if(this._getType(D)!==K.undefined){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.undefined,received:r.parsedType}),o}return mD(D.data)}};R2.create=(D)=>{return new R2({typeName:l.ZodUndefined,...t(D)})};n2=class n2 extends p{_parse(D){if(this._getType(D)!==K.null){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.null,received:r.parsedType}),o}return mD(D.data)}};n2.create=(D)=>{return new n2({typeName:l.ZodNull,...t(D)})};K0=class K0 extends p{constructor(){super(...arguments);this._any=!0}_parse(D){return mD(D.data)}};K0.create=(D)=>{return new K0({typeName:l.ZodAny,...t(D)})};er=class er extends p{constructor(){super(...arguments);this._unknown=!0}_parse(D){return mD(D.data)}};er.create=(D)=>{return new er({typeName:l.ZodUnknown,...t(D)})};Wr=class Wr extends p{_parse(D){let u=this._getOrReturnCtx(D);return Q(u,{code:O.invalid_type,expected:K.never,received:u.parsedType}),o}};Wr.create=(D)=>{return new Wr({typeName:l.ZodNever,...t(D)})};YA=class YA extends p{_parse(D){if(this._getType(D)!==K.undefined){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.void,received:r.parsedType}),o}return mD(D.data)}};YA.create=(D)=>{return new YA({typeName:l.ZodVoid,...t(D)})};Tu=class Tu extends p{_parse(D){let{ctx:u,status:r}=this._processInputParams(D),A=this._def;if(u.parsedType!==K.array)return Q(u,{code:O.invalid_type,expected:K.array,received:u.parsedType}),o;if(A.exactLength!==null){let w=u.data.length>A.exactLength.value,F=u.data.length<A.exactLength.value;if(w||F)Q(u,{code:w?O.too_big:O.too_small,minimum:F?A.exactLength.value:void 0,maximum:w?A.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:A.exactLength.message}),r.dirty()}if(A.minLength!==null){if(u.data.length<A.minLength.value)Q(u,{code:O.too_small,minimum:A.minLength.value,type:"array",inclusive:!0,exact:!1,message:A.minLength.message}),r.dirty()}if(A.maxLength!==null){if(u.data.length>A.maxLength.value)Q(u,{code:O.too_big,maximum:A.maxLength.value,type:"array",inclusive:!0,exact:!1,message:A.maxLength.message}),r.dirty()}if(u.common.async)return Promise.all([...u.data].map((w,F)=>{return A.type._parseAsync(new Zu(u,w,u.path,F))})).then((w)=>{return lD.mergeArray(r,w)});let f=[...u.data].map((w,F)=>{return A.type._parseSync(new Zu(u,w,u.path,F))});return lD.mergeArray(r,f)}get element(){return this._def.type}min(D,u){return new Tu({...this._def,minLength:{value:D,message:j.toString(u)}})}max(D,u){return new Tu({...this._def,maxLength:{value:D,message:j.toString(u)}})}length(D,u){return new Tu({...this._def,exactLength:{value:D,message:j.toString(u)}})}nonempty(D){return this.min(1,D)}};Tu.create=(D,u)=>{return new Tu({type:D,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...t(u)})};XD=class XD extends p{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let D=this._def.shape(),u=DD.objectKeys(D);return this._cached={shape:D,keys:u},this._cached}_parse(D){if(this._getType(D)!==K.object){let $=this._getOrReturnCtx(D);return Q($,{code:O.invalid_type,expected:K.object,received:$.parsedType}),o}let{status:r,ctx:A}=this._processInputParams(D),{shape:f,keys:w}=this._getCached(),F=[];if(!(this._def.catchall instanceof Wr&&this._def.unknownKeys==="strip")){for(let $ in A.data)if(!w.includes($))F.push($)}let E=[];for(let $ of w){let g=f[$],_=A.data[$];E.push({key:{status:"valid",value:$},value:g._parse(new Zu(A,_,A.path,$)),alwaysSet:$ in A.data})}if(this._def.catchall instanceof Wr){let $=this._def.unknownKeys;if($==="passthrough")for(let g of F)E.push({key:{status:"valid",value:g},value:{status:"valid",value:A.data[g]}});else if($==="strict"){if(F.length>0)Q(A,{code:O.unrecognized_keys,keys:F}),r.dirty()}else if($==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let $=this._def.catchall;for(let g of F){let _=A.data[g];E.push({key:{status:"valid",value:g},value:$._parse(new Zu(A,_,A.path,g)),alwaysSet:g in A.data})}}if(A.common.async)return Promise.resolve().then(async()=>{let $=[];for(let g of E){let _=await g.key,R=await g.value;$.push({key:_,value:R,alwaysSet:g.alwaysSet})}return $}).then(($)=>{return lD.mergeObjectSync(r,$)});else return lD.mergeObjectSync(r,E)}get shape(){return this._def.shape()}strict(D){return j.errToObj,new XD({...this._def,unknownKeys:"strict",...D!==void 0?{errorMap:(u,r)=>{let A=this._def.errorMap?.(u,r).message??r.defaultError;if(u.code==="unrecognized_keys")return{message:j.errToObj(D).message??A};return{message:A}}}:{}})}strip(){return new XD({...this._def,unknownKeys:"strip"})}passthrough(){return new XD({...this._def,unknownKeys:"passthrough"})}extend(D){return new XD({...this._def,shape:()=>({...this._def.shape(),...D})})}merge(D){return new XD({unknownKeys:D._def.unknownKeys,catchall:D._def.catchall,shape:()=>({...this._def.shape(),...D._def.shape()}),typeName:l.ZodObject})}setKey(D,u){return this.augment({[D]:u})}catchall(D){return new XD({...this._def,catchall:D})}pick(D){let u={};for(let r of DD.objectKeys(D))if(D[r]&&this.shape[r])u[r]=this.shape[r];return new XD({...this._def,shape:()=>u})}omit(D){let u={};for(let r of DD.objectKeys(this.shape))if(!D[r])u[r]=this.shape[r];return new XD({...this._def,shape:()=>u})}deepPartial(){return g2(this)}partial(D){let u={};for(let r of DD.objectKeys(this.shape)){let A=this.shape[r];if(D&&!D[r])u[r]=A;else u[r]=A.optional()}return new XD({...this._def,shape:()=>u})}required(D){let u={};for(let r of DD.objectKeys(this.shape))if(D&&!D[r])u[r]=this.shape[r];else{let f=this.shape[r];while(f instanceof vu)f=f._def.innerType;u[r]=f}return new XD({...this._def,shape:()=>u})}keyof(){return VE(DD.objectKeys(this.shape))}};XD.create=(D,u)=>{return new XD({shape:()=>D,unknownKeys:"strip",catchall:Wr.create(),typeName:l.ZodObject,...t(u)})};XD.strictCreate=(D,u)=>{return new XD({shape:()=>D,unknownKeys:"strict",catchall:Wr.create(),typeName:l.ZodObject,...t(u)})};XD.lazycreate=(D,u)=>{return new XD({shape:D,unknownKeys:"strip",catchall:Wr.create(),typeName:l.ZodObject,...t(u)})};B2=class B2 extends p{_parse(D){let{ctx:u}=this._processInputParams(D),r=this._def.options;function A(f){for(let F of f)if(F.result.status==="valid")return F.result;for(let F of f)if(F.result.status==="dirty")return u.common.issues.push(...F.ctx.common.issues),F.result;let w=f.map((F)=>new $u(F.ctx.common.issues));return Q(u,{code:O.invalid_union,unionErrors:w}),o}if(u.common.async)return Promise.all(r.map(async(f)=>{let w={...u,common:{...u.common,issues:[]},parent:null};return{result:await f._parseAsync({data:u.data,path:u.path,parent:w}),ctx:w}})).then(A);else{let f=void 0,w=[];for(let E of r){let $={...u,common:{...u.common,issues:[]},parent:null},g=E._parseSync({data:u.data,path:u.path,parent:$});if(g.status==="valid")return g;else if(g.status==="dirty"&&!f)f={result:g,ctx:$};if($.common.issues.length)w.push($.common.issues)}if(f)return u.common.issues.push(...f.ctx.common.issues),f.result;let F=w.map((E)=>new $u(E));return Q(u,{code:O.invalid_union,unionErrors:F}),o}}get options(){return this._def.options}};B2.create=(D,u)=>{return new B2({options:D,typeName:l.ZodUnion,...t(u)})};Y8=class Y8 extends p{_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.object)return Q(u,{code:O.invalid_type,expected:K.object,received:u.parsedType}),o;let r=this.discriminator,A=u.data[r],f=this.optionsMap.get(A);if(!f)return Q(u,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),o;if(u.common.async)return f._parseAsync({data:u.data,path:u.path,parent:u});else return f._parseSync({data:u.data,path:u.path,parent:u})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(D,u,r){let A=new Map;for(let f of u){let w=Lr(f.shape[D]);if(!w.length)throw Error(`A discriminator value for key \`${D}\` could not be extracted from all schema options`);for(let F of w){if(A.has(F))throw Error(`Discriminator property ${String(D)} has duplicate value ${String(F)}`);A.set(F,f)}}return new Y8({typeName:l.ZodDiscriminatedUnion,discriminator:D,options:u,optionsMap:A,...t(r)})}};W2=class W2 extends p{_parse(D){let{status:u,ctx:r}=this._processInputParams(D),A=(f,w)=>{if(i8(f)||i8(w))return o;let F=yF(f.value,w.value);if(!F.valid)return Q(r,{code:O.invalid_intersection_types}),o;if(U8(f)||U8(w))u.dirty();return{status:u.value,value:F.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([f,w])=>A(f,w));else return A(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};W2.create=(D,u,r)=>{return new W2({left:D,right:u,typeName:l.ZodIntersection,...t(r)})};Jr=class Jr extends p{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.array)return Q(r,{code:O.invalid_type,expected:K.array,received:r.parsedType}),o;if(r.data.length<this._def.items.length)return Q(r,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),o;if(!this._def.rest&&r.data.length>this._def.items.length)Q(r,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u.dirty();let f=[...r.data].map((w,F)=>{let E=this._def.items[F]||this._def.rest;if(!E)return null;return E._parse(new Zu(r,w,r.path,F))}).filter((w)=>!!w);if(r.common.async)return Promise.all(f).then((w)=>{return lD.mergeArray(u,w)});else return lD.mergeArray(u,f)}get items(){return this._def.items}rest(D){return new Jr({...this._def,rest:D})}};Jr.create=(D,u)=>{if(!Array.isArray(D))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jr({items:D,typeName:l.ZodTuple,rest:null,...t(u)})};MA=class MA extends p{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.object)return Q(r,{code:O.invalid_type,expected:K.object,received:r.parsedType}),o;let A=[],f=this._def.keyType,w=this._def.valueType;for(let F in r.data)A.push({key:f._parse(new Zu(r,F,r.path,F)),value:w._parse(new Zu(r,r.data[F],r.path,F)),alwaysSet:F in r.data});if(r.common.async)return lD.mergeObjectAsync(u,A);else return lD.mergeObjectSync(u,A)}get element(){return this._def.valueType}static create(D,u,r){if(u instanceof p)return new MA({keyType:D,valueType:u,typeName:l.ZodRecord,...t(r)});return new MA({keyType:ju.create(),valueType:D,typeName:l.ZodRecord,...t(u)})}};OA=class OA extends p{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.map)return Q(r,{code:O.invalid_type,expected:K.map,received:r.parsedType}),o;let A=this._def.keyType,f=this._def.valueType,w=[...r.data.entries()].map(([F,E],$)=>{return{key:A._parse(new Zu(r,F,r.path,[$,"key"])),value:f._parse(new Zu(r,E,r.path,[$,"value"]))}});if(r.common.async){let F=new Map;return Promise.resolve().then(async()=>{for(let E of w){let $=await E.key,g=await E.value;if($.status==="aborted"||g.status==="aborted")return o;if($.status==="dirty"||g.status==="dirty")u.dirty();F.set($.value,g.value)}return{status:u.value,value:F}})}else{let F=new Map;for(let E of w){let{key:$,value:g}=E;if($.status==="aborted"||g.status==="aborted")return o;if($.status==="dirty"||g.status==="dirty")u.dirty();F.set($.value,g.value)}return{status:u.value,value:F}}}};OA.create=(D,u,r)=>{return new OA({valueType:u,keyType:D,typeName:l.ZodMap,...t(r)})};h0=class h0 extends p{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.parsedType!==K.set)return Q(r,{code:O.invalid_type,expected:K.set,received:r.parsedType}),o;let A=this._def;if(A.minSize!==null){if(r.data.size<A.minSize.value)Q(r,{code:O.too_small,minimum:A.minSize.value,type:"set",inclusive:!0,exact:!1,message:A.minSize.message}),u.dirty()}if(A.maxSize!==null){if(r.data.size>A.maxSize.value)Q(r,{code:O.too_big,maximum:A.maxSize.value,type:"set",inclusive:!0,exact:!1,message:A.maxSize.message}),u.dirty()}let f=this._def.valueType;function w(E){let $=new Set;for(let g of E){if(g.status==="aborted")return o;if(g.status==="dirty")u.dirty();$.add(g.value)}return{status:u.value,value:$}}let F=[...r.data.values()].map((E,$)=>f._parse(new Zu(r,E,r.path,$)));if(r.common.async)return Promise.all(F).then((E)=>w(E));else return w(F)}min(D,u){return new h0({...this._def,minSize:{value:D,message:j.toString(u)}})}max(D,u){return new h0({...this._def,maxSize:{value:D,message:j.toString(u)}})}size(D,u){return this.min(D,u).max(D,u)}nonempty(D){return this.min(1,D)}};h0.create=(D,u)=>{return new h0({valueType:D,minSize:null,maxSize:null,typeName:l.ZodSet,...t(u)})};S2=class S2 extends p{constructor(){super(...arguments);this.validate=this.implement}_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.function)return Q(u,{code:O.invalid_type,expected:K.function,received:u.parsedType}),o;function r(F,E){return iA({data:F,path:u.path,errorMaps:[u.common.contextualErrorMap,u.schemaErrorMap,$2(),Qr].filter(($)=>!!$),issueData:{code:O.invalid_arguments,argumentsError:E}})}function A(F,E){return iA({data:F,path:u.path,errorMaps:[u.common.contextualErrorMap,u.schemaErrorMap,$2(),Qr].filter(($)=>!!$),issueData:{code:O.invalid_return_type,returnTypeError:E}})}let f={errorMap:u.common.contextualErrorMap},w=u.data;if(this._def.returns instanceof N0){let F=this;return mD(async function(...E){let $=new $u([]),g=await F._def.args.parseAsync(E,f).catch((n)=>{throw $.addIssue(r(E,n)),$}),_=await Reflect.apply(w,this,g);return await F._def.returns._def.type.parseAsync(_,f).catch((n)=>{throw $.addIssue(A(_,n)),$})})}else{let F=this;return mD(function(...E){let $=F._def.args.safeParse(E,f);if(!$.success)throw new $u([r(E,$.error)]);let g=Reflect.apply(w,this,$.data),_=F._def.returns.safeParse(g,f);if(!_.success)throw new $u([A(g,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...D){return new S2({...this._def,args:Jr.create(D).rest(er.create())})}returns(D){return new S2({...this._def,returns:D})}implement(D){return this.parse(D)}strictImplement(D){return this.parse(D)}static create(D,u,r){return new S2({args:D?D:Jr.create([]).rest(er.create()),returns:u||er.create(),typeName:l.ZodFunction,...t(r)})}};J2=class J2 extends p{get schema(){return this._def.getter()}_parse(D){let{ctx:u}=this._processInputParams(D);return this._def.getter()._parse({data:u.data,path:u.path,parent:u})}};J2.create=(D,u)=>{return new J2({getter:D,typeName:l.ZodLazy,...t(u)})};G2=class G2 extends p{_parse(D){if(D.data!==this._def.value){let u=this._getOrReturnCtx(D);return Q(u,{received:u.data,code:O.invalid_literal,expected:this._def.value}),o}return{status:"valid",value:D.data}}get value(){return this._def.value}};G2.create=(D,u)=>{return new G2({value:D,typeName:l.ZodLiteral,...t(u)})};r0=class r0 extends p{_parse(D){if(typeof D.data!=="string"){let u=this._getOrReturnCtx(D),r=this._def.values;return Q(u,{expected:DD.joinValues(r),received:u.parsedType,code:O.invalid_type}),o}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(D.data)){let u=this._getOrReturnCtx(D),r=this._def.values;return Q(u,{received:u.data,code:O.invalid_enum_value,options:r}),o}return mD(D.data)}get options(){return this._def.values}get enum(){let D={};for(let u of this._def.values)D[u]=u;return D}get Values(){let D={};for(let u of this._def.values)D[u]=u;return D}get Enum(){let D={};for(let u of this._def.values)D[u]=u;return D}extract(D,u=this._def){return r0.create(D,{...this._def,...u})}exclude(D,u=this._def){return r0.create(this.options.filter((r)=>!D.includes(r)),{...this._def,...u})}};r0.create=VE;C2=class C2 extends p{_parse(D){let u=DD.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(D);if(r.parsedType!==K.string&&r.parsedType!==K.number){let A=DD.objectValues(u);return Q(r,{expected:DD.joinValues(A),received:r.parsedType,code:O.invalid_type}),o}if(!this._cache)this._cache=new Set(DD.getValidEnumValues(this._def.values));if(!this._cache.has(D.data)){let A=DD.objectValues(u);return Q(r,{received:r.data,code:O.invalid_enum_value,options:A}),o}return mD(D.data)}get enum(){return this._def.values}};C2.create=(D,u)=>{return new C2({values:D,typeName:l.ZodNativeEnum,...t(u)})};N0=class N0 extends p{unwrap(){return this._def.type}_parse(D){let{ctx:u}=this._processInputParams(D);if(u.parsedType!==K.promise&&u.common.async===!1)return Q(u,{code:O.invalid_type,expected:K.promise,received:u.parsedType}),o;let r=u.parsedType===K.promise?u.data:Promise.resolve(u.data);return mD(r.then((A)=>{return this._def.type.parseAsync(A,{path:u.path,errorMap:u.common.contextualErrorMap})}))}};N0.create=(D,u)=>{return new N0({type:D,typeName:l.ZodPromise,...t(u)})};ou=class ou extends p{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(D){let{status:u,ctx:r}=this._processInputParams(D),A=this._def.effect||null,f={addIssue:(w)=>{if(Q(r,w),w.fatal)u.abort();else u.dirty()},get path(){return r.path}};if(f.addIssue=f.addIssue.bind(f),A.type==="preprocess"){let w=A.transform(r.data,f);if(r.common.async)return Promise.resolve(w).then(async(F)=>{if(u.value==="aborted")return o;let E=await this._def.schema._parseAsync({data:F,path:r.path,parent:r});if(E.status==="aborted")return o;if(E.status==="dirty")return I0(E.value);if(u.value==="dirty")return I0(E.value);return E});else{if(u.value==="aborted")return o;let F=this._def.schema._parseSync({data:w,path:r.path,parent:r});if(F.status==="aborted")return o;if(F.status==="dirty")return I0(F.value);if(u.value==="dirty")return I0(F.value);return F}}if(A.type==="refinement"){let w=(F)=>{let E=A.refinement(F,f);if(r.common.async)return Promise.resolve(E);if(E instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return F};if(r.common.async===!1){let F=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(F.status==="aborted")return o;if(F.status==="dirty")u.dirty();return w(F.value),{status:u.value,value:F.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((F)=>{if(F.status==="aborted")return o;if(F.status==="dirty")u.dirty();return w(F.value).then(()=>{return{status:u.value,value:F.value}})})}if(A.type==="transform")if(r.common.async===!1){let w=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ar(w))return o;let F=A.transform(w.value,f);if(F instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:u.value,value:F}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((w)=>{if(!ar(w))return o;return Promise.resolve(A.transform(w.value,f)).then((F)=>({status:u.value,value:F}))});DD.assertNever(A)}};ou.create=(D,u,r)=>{return new ou({schema:D,typeName:l.ZodEffects,effect:u,...t(r)})};ou.createWithPreprocess=(D,u,r)=>{return new ou({schema:u,effect:{type:"preprocess",transform:D},typeName:l.ZodEffects,...t(r)})};vu=class vu extends p{_parse(D){if(this._getType(D)===K.undefined)return mD(void 0);return this._def.innerType._parse(D)}unwrap(){return this._def.innerType}};vu.create=(D,u)=>{return new vu({innerType:D,typeName:l.ZodOptional,...t(u)})};qr=class qr extends p{_parse(D){if(this._getType(D)===K.null)return mD(null);return this._def.innerType._parse(D)}unwrap(){return this._def.innerType}};qr.create=(D,u)=>{return new qr({innerType:D,typeName:l.ZodNullable,...t(u)})};H2=class H2 extends p{_parse(D){let{ctx:u}=this._processInputParams(D),r=u.data;if(u.parsedType===K.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:u.path,parent:u})}removeDefault(){return this._def.innerType}};H2.create=(D,u)=>{return new H2({innerType:D,typeName:l.ZodDefault,defaultValue:typeof u.default==="function"?u.default:()=>u.default,...t(u)})};X2=class X2 extends p{_parse(D){let{ctx:u}=this._processInputParams(D),r={...u,common:{...u.common,issues:[]}},A=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(E2(A))return A.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new $u(r.common.issues)},input:r.data})}});else return{status:"valid",value:A.status==="valid"?A.value:this._def.catchValue({get error(){return new $u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};X2.create=(D,u)=>{return new X2({innerType:D,typeName:l.ZodCatch,catchValue:typeof u.catch==="function"?u.catch:()=>u.catch,...t(u)})};PA=class PA extends p{_parse(D){if(this._getType(D)!==K.nan){let r=this._getOrReturnCtx(D);return Q(r,{code:O.invalid_type,expected:K.nan,received:r.parsedType}),o}return{status:"valid",value:D.data}}};PA.create=(D)=>{return new PA({typeName:l.ZodNaN,...t(D)})};mC=Symbol("zod_brand");M8=class M8 extends p{_parse(D){let{ctx:u}=this._processInputParams(D),r=u.data;return this._def.type._parse({data:r,path:u.path,parent:u})}unwrap(){return this._def.type}};kA=class kA extends p{_parse(D){let{status:u,ctx:r}=this._processInputParams(D);if(r.common.async)return(async()=>{let f=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(f.status==="aborted")return o;if(f.status==="dirty")return u.dirty(),I0(f.value);else return this._def.out._parseAsync({data:f.value,path:r.path,parent:r})})();else{let A=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(A.status==="aborted")return o;if(A.status==="dirty")return u.dirty(),{status:"dirty",value:A.value};else return this._def.out._parseSync({data:A.value,path:r.path,parent:r})}}static create(D,u){return new kA({in:D,out:u,typeName:l.ZodPipeline})}};i2=class i2 extends p{_parse(D){let u=this._def.innerType._parse(D),r=(A)=>{if(ar(A))A.value=Object.freeze(A.value);return A};return E2(u)?u.then((A)=>r(A)):r(u)}unwrap(){return this._def.innerType}};i2.create=(D,u)=>{return new i2({innerType:D,typeName:l.ZodReadonly,...t(u)})};aC={object:XD.lazycreate};(function(D){D.ZodString="ZodString",D.ZodNumber="ZodNumber",D.ZodNaN="ZodNaN",D.ZodBigInt="ZodBigInt",D.ZodBoolean="ZodBoolean",D.ZodDate="ZodDate",D.ZodSymbol="ZodSymbol",D.ZodUndefined="ZodUndefined",D.ZodNull="ZodNull",D.ZodAny="ZodAny",D.ZodUnknown="ZodUnknown",D.ZodNever="ZodNever",D.ZodVoid="ZodVoid",D.ZodArray="ZodArray",D.ZodObject="ZodObject",D.ZodUnion="ZodUnion",D.ZodDiscriminatedUnion="ZodDiscriminatedUnion",D.ZodIntersection="ZodIntersection",D.ZodTuple="ZodTuple",D.ZodRecord="ZodRecord",D.ZodMap="ZodMap",D.ZodSet="ZodSet",D.ZodFunction="ZodFunction",D.ZodLazy="ZodLazy",D.ZodLiteral="ZodLiteral",D.ZodEnum="ZodEnum",D.ZodEffects="ZodEffects",D.ZodNativeEnum="ZodNativeEnum",D.ZodOptional="ZodOptional",D.ZodNullable="ZodNullable",D.ZodDefault="ZodDefault",D.ZodCatch="ZodCatch",D.ZodPromise="ZodPromise",D.ZodBranded="ZodBranded",D.ZodPipeline="ZodPipeline",D.ZodReadonly="ZodReadonly"})(l||(l={}));hE=ju.create,NE=D0.create,DH=PA.create,uH=u0.create,QE=_2.create,rH=V0.create,AH=UA.create,fH=R2.create,FH=n2.create,wH=K0.create,$H=er.create,EH=Wr.create,gH=YA.create,SH=Tu.create,_H=XD.create,RH=XD.strictCreate,nH=B2.create,BH=Y8.create,WH=W2.create,JH=Jr.create,GH=MA.create,CH=OA.create,HH=h0.create,XH=S2.create,iH=J2.create,UH=G2.create,YH=r0.create,MH=C2.create,OH=N0.create,PH=ou.create,kH=vu.create,IH=qr.create,VH=ou.createWithPreprocess,KH=kA.create,LH={string:(D)=>ju.create({...D,coerce:!0}),number:(D)=>D0.create({...D,coerce:!0}),boolean:(D)=>_2.create({...D,coerce:!0}),bigint:(D)=>u0.create({...D,coerce:!0}),date:(D)=>V0.create({...D,coerce:!0})},qH=o});var S={};t1(S,{void:()=>gH,util:()=>DD,unknown:()=>$H,union:()=>nH,undefined:()=>fH,tuple:()=>JH,transformer:()=>PH,symbol:()=>AH,string:()=>hE,strictObject:()=>RH,setErrorMap:()=>IC,set:()=>HH,record:()=>GH,quotelessJson:()=>PC,promise:()=>OH,preprocess:()=>VH,pipeline:()=>KH,ostring:()=>hH,optional:()=>kH,onumber:()=>NH,oboolean:()=>QH,objectUtil:()=>ZF,object:()=>_H,number:()=>NE,nullable:()=>IH,null:()=>FH,never:()=>EH,nativeEnum:()=>MH,nan:()=>DH,map:()=>CH,makeIssue:()=>iA,literal:()=>UH,lazy:()=>iH,late:()=>aC,isValid:()=>ar,isDirty:()=>U8,isAsync:()=>E2,isAborted:()=>i8,intersection:()=>WH,instanceof:()=>eC,getParsedType:()=>Br,getErrorMap:()=>$2,function:()=>XH,enum:()=>YH,effect:()=>PH,discriminatedUnion:()=>BH,defaultErrorMap:()=>Qr,datetimeRegex:()=>IE,date:()=>rH,custom:()=>KE,coerce:()=>LH,boolean:()=>QE,bigint:()=>uH,array:()=>SH,any:()=>wH,addIssueToContext:()=>Q,ZodVoid:()=>YA,ZodUnknown:()=>er,ZodUnion:()=>B2,ZodUndefined:()=>R2,ZodType:()=>p,ZodTuple:()=>Jr,ZodTransformer:()=>ou,ZodSymbol:()=>UA,ZodString:()=>ju,ZodSet:()=>h0,ZodSchema:()=>p,ZodRecord:()=>MA,ZodReadonly:()=>i2,ZodPromise:()=>N0,ZodPipeline:()=>kA,ZodParsedType:()=>K,ZodOptional:()=>vu,ZodObject:()=>XD,ZodNumber:()=>D0,ZodNullable:()=>qr,ZodNull:()=>n2,ZodNever:()=>Wr,ZodNativeEnum:()=>C2,ZodNaN:()=>PA,ZodMap:()=>OA,ZodLiteral:()=>G2,ZodLazy:()=>J2,ZodIssueCode:()=>O,ZodIntersection:()=>W2,ZodFunction:()=>S2,ZodFirstPartyTypeKind:()=>l,ZodError:()=>$u,ZodEnum:()=>r0,ZodEffects:()=>ou,ZodDiscriminatedUnion:()=>Y8,ZodDefault:()=>H2,ZodDate:()=>V0,ZodCatch:()=>X2,ZodBranded:()=>M8,ZodBoolean:()=>_2,ZodBigInt:()=>u0,ZodArray:()=>Tu,ZodAny:()=>K0,Schema:()=>p,ParseStatus:()=>lD,OK:()=>mD,NEVER:()=>qH,INVALID:()=>o,EMPTY_PATH:()=>VC,DIRTY:()=>I0,BRAND:()=>mC});var cF=W(()=>{X8();dF();UE();XA();LE();H8()});var YD=W(()=>{cF();cF()});import qE from"path";import bH from"process";function du(){if(O8)return O8;return O8=Object.freeze(sH.parse(bH.env)),O8}var sH,O8=null,U2;var bE=W(()=>{Q3();nr();YD();sH=S.object({PORT:S.coerce.number().int().min(1).default(9217),AIWORKER_WORKER_HOST:S.string().min(1).default("127.0.0.1"),WORKER_DB_PATH:S.string().default(()=>qE.join(N3(),"aiworker.db")),WORKER_MIGRATIONS_FOLDER:S.string().default(()=>bF),WORKER_WORKSPACE_ROOT:S.string().default(()=>qE.join(N3(),"workers")),AIWORKER_LOCAL_TOKEN:S.string().min(16).optional()});U2=new Proxy({},{get(D,u){return du()[u]},has(D,u){return u in du()},ownKeys(){return Reflect.ownKeys(du())},getOwnPropertyDescriptor(D,u){return Reflect.getOwnPropertyDescriptor(du(),u)}})});import{Buffer as sE}from"buffer";import{timingSafeEqual as zH}from"crypto";function tF(D={}){let u=D.token??null,r=D.operatorId??"operator-local";return{authenticate(A){if(!u)return{status:"anonymous"};let f=`Bearer ${u}`;if(!jH(A.authorization??"",f))return{reason:"Missing or invalid local bearer token.",status:"denied"};return{identity:{authMethod:"local-bearer",grants:[{action:"access",kind:"host",target:"api/local"}],operatorId:r,providerId:"local-bearer",subject:`local:${r}`},status:"authenticated"}},id:"local-bearer",kind:"local-bearer"}}function jH(D,u){let r=sE.from(D),A=sE.from(u);return r.length===A.length&&zH(r,A)}var zE=()=>{};var pF=()=>{};var TH,vH,TE,IA,P8,Y2,xF,mF,aF,k8,vE,ZE,oE,ZH,dE,oH,lE;var eF=W(()=>{YD();pF();TH=/^[a-z0-9][a-z0-9._-]*$/,vH=/^[a-z][a-z0-9-]*$/,TE=/^[a-z][a-z0-9-]*$/,IA=S.string().min(1).regex(TH,"admission id must be lowercase alphanumeric with . _ -"),P8=S.string().min(1).regex(vH,"admission kind must be kebab-case"),Y2=S.enum(["low","medium","high"]),xF=S.enum(["pending","approved","rejected","applied","failed"]),mF=S.enum(["approved","rejected","applied","failed"]),aF=S.enum(["conversation","message","tool-call","observation","artifact","memory","log"]),k8=S.object({at:S.string().min(1),kind:aF,summary:S.string().max(500).optional(),notes:S.string().max(2000).optional(),ref:S.string().min(1)}),vE=S.object({confidence:S.number().min(0).max(1),createdAt:S.string().min(1),evidence:S.array(k8).readonly(),id:IA,kind:P8,payload:S.record(S.string(),S.unknown()).optional(),risk:Y2,rollback:S.string().min(1),scopeId:S.string().min(1).optional(),soulId:S.string().min(1).regex(TE),status:xF,summary:S.string().min(1).max(2000),target:S.string().min(1),updatedAt:S.string().min(1)}),ZE=S.object({confidence:S.number().min(0).max(1),evidence:S.array(k8).readonly().optional(),id:IA,kind:P8,payload:S.record(S.string(),S.unknown()).optional(),risk:Y2.default("high"),rollback:S.string().min(1),scopeId:S.string().min(1).optional(),soulId:S.string().min(1).regex(TE),summary:S.string().min(1).max(2000),target:S.string().min(1)}),oE=S.object({appliedAt:S.string().min(1).optional(),decidedAt:S.string().min(1),decidedBy:S.string().min(1),decision:mF,failureReason:S.string().max(4000).optional(),id:S.number().int().positive(),proposalId:IA,reason:S.string().max(2000).optional()}),ZH=/^[a-z0-9][a-z0-9._-]*$/,dE=S.object({body:S.string().min(1).max(20000),topic:S.string().min(1).regex(ZH).optional(),indexEntry:S.string().min(1).max(280).optional()}),oH=/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/,lE=S.object({body:S.string().min(1).max(20000),skillId:S.string().min(1).regex(oH),overwrite:S.boolean().optional()})});var dH,lH,I8,V8,K8,h8,N8,yE,cE;var tE=W(()=>{YD();dH=/^[a-z0-9][a-z0-9._-]*$/,lH=/^[a-z][a-z0-9-]*$/,I8=S.string().min(1).regex(dH,"artifact id must be lowercase alphanumeric with . _ -"),V8=S.string().min(1).regex(lH,"artifact type must be kebab-case"),K8=S.enum(["public","internal","confidential","secret"]),h8=S.enum(["active","archived","removed"]),N8=S.enum(["operator","brain-runtime","executor","channel-import"]),yE=S.object({createdAt:S.string().min(1),evidenceRefs:S.array(S.string().min(1)).readonly(),hash:S.string().regex(/^[a-f0-9]{64}$/).optional(),id:I8,metadata:S.record(S.string(),S.unknown()).optional(),ref:S.string().min(1),retention:S.string().min(1).optional(),scopeId:S.string().min(1).optional(),sensitivity:K8,source:N8,status:h8,summary:S.string().max(2000).optional(),type:V8,updatedAt:S.string().min(1)}),cE=S.object({evidenceRefs:S.array(S.string().min(1)).readonly().optional(),hash:S.string().regex(/^[a-f0-9]{64}$/).optional(),id:I8,metadata:S.record(S.string(),S.unknown()).optional(),ref:S.string().min(1),retention:S.string().min(1).optional(),scopeId:S.string().min(1).optional(),sensitivity:K8.default("internal"),source:N8,status:h8.default("active"),summary:S.string().max(2000).optional(),type:V8})});var yH,Q8,D6,u6,r6,pE,xE;var mE=W(()=>{YD();eF();yH=/^[a-z][a-z0-9-]*$/,Q8=S.string().min(1).regex(yH,"brief section id must be kebab-case"),D6=S.enum(["soul-doc","memory-doc","rollup-doc","risk-policy","admission-summary","artifact-summary","scope-manifest","soul-skeleton"]),u6=S.object({body:S.string().min(1),id:Q8,protected:S.boolean(),source:D6,tokens:S.number().int().nonnegative()}),r6=S.object({estimatedTokens:S.number().int().nonnegative(),id:Q8,reason:S.string().min(1)}),pE=S.object({artifactRefs:S.array(S.unknown()).transform((D)=>D.filter((u)=>typeof u==="string").map((u)=>u.trim()).filter((u)=>u.length>0)).pipe(S.array(S.string().min(1)).readonly()).optional(),executor:S.string().min(1).optional(),risk:Y2.optional(),scopeId:S.string().min(1).optional(),soulId:S.string().min(1).optional(),task:S.string().min(1).max(4000),tokenBudget:S.number().int().min(200).max(50000).optional()}),xE=S.object({compiledAt:S.string().min(1),droppedSections:S.array(r6).readonly(),executor:S.string().min(1).optional(),scopeId:S.string().min(1).optional(),sections:S.array(u6).readonly(),soulId:S.string().min(1),task:S.string().min(1),tokensBudget:S.number().int().positive(),tokensUsed:S.number().int().nonnegative(),warnings:S.array(S.string().min(1)).readonly()})});var AD=L((DX)=>{var A6=Symbol.for("yaml.alias"),aE=Symbol.for("yaml.document"),L8=Symbol.for("yaml.map"),eE=Symbol.for("yaml.pair"),f6=Symbol.for("yaml.scalar"),q8=Symbol.for("yaml.seq"),br=Symbol.for("yaml.node.type"),cH=(D)=>!!D&&typeof D==="object"&&D[br]===A6,tH=(D)=>!!D&&typeof D==="object"&&D[br]===aE,pH=(D)=>!!D&&typeof D==="object"&&D[br]===L8,xH=(D)=>!!D&&typeof D==="object"&&D[br]===eE,Dg=(D)=>!!D&&typeof D==="object"&&D[br]===f6,mH=(D)=>!!D&&typeof D==="object"&&D[br]===q8;function ug(D){if(D&&typeof D==="object")switch(D[br]){case L8:case q8:return!0}return!1}function aH(D){if(D&&typeof D==="object")switch(D[br]){case A6:case L8:case f6:case q8:return!0}return!1}var eH=(D)=>(Dg(D)||ug(D))&&!!D.anchor;DX.ALIAS=A6;DX.DOC=aE;DX.MAP=L8;DX.NODE_TYPE=br;DX.PAIR=eE;DX.SCALAR=f6;DX.SEQ=q8;DX.hasAnchor=eH;DX.isAlias=cH;DX.isCollection=ug;DX.isDocument=tH;DX.isMap=pH;DX.isNode=aH;DX.isPair=xH;DX.isScalar=Dg;DX.isSeq=mH});var VA=L((GX)=>{var QD=AD(),Eu=Symbol("break visit"),rg=Symbol("skip children"),Gr=Symbol("remove node");function b8(D,u){let r=Ag(u);if(QD.isDocument(D)){if(M2(null,D.contents,r,Object.freeze([D]))===Gr)D.contents=null}else M2(null,D,r,Object.freeze([]))}b8.BREAK=Eu;b8.SKIP=rg;b8.REMOVE=Gr;function M2(D,u,r,A){let f=fg(D,u,r,A);if(QD.isNode(f)||QD.isPair(f))return Fg(D,A,f),M2(D,f,r,A);if(typeof f!=="symbol"){if(QD.isCollection(u)){A=Object.freeze(A.concat(u));for(let w=0;w<u.items.length;++w){let F=M2(w,u.items[w],r,A);if(typeof F==="number")w=F-1;else if(F===Eu)return Eu;else if(F===Gr)u.items.splice(w,1),w-=1}}else if(QD.isPair(u)){A=Object.freeze(A.concat(u));let w=M2("key",u.key,r,A);if(w===Eu)return Eu;else if(w===Gr)u.key=null;let F=M2("value",u.value,r,A);if(F===Eu)return Eu;else if(F===Gr)u.value=null}}return f}async function s8(D,u){let r=Ag(u);if(QD.isDocument(D)){if(await O2(null,D.contents,r,Object.freeze([D]))===Gr)D.contents=null}else await O2(null,D,r,Object.freeze([]))}s8.BREAK=Eu;s8.SKIP=rg;s8.REMOVE=Gr;async function O2(D,u,r,A){let f=await fg(D,u,r,A);if(QD.isNode(f)||QD.isPair(f))return Fg(D,A,f),O2(D,f,r,A);if(typeof f!=="symbol"){if(QD.isCollection(u)){A=Object.freeze(A.concat(u));for(let w=0;w<u.items.length;++w){let F=await O2(w,u.items[w],r,A);if(typeof F==="number")w=F-1;else if(F===Eu)return Eu;else if(F===Gr)u.items.splice(w,1),w-=1}}else if(QD.isPair(u)){A=Object.freeze(A.concat(u));let w=await O2("key",u.key,r,A);if(w===Eu)return Eu;else if(w===Gr)u.key=null;let F=await O2("value",u.value,r,A);if(F===Eu)return Eu;else if(F===Gr)u.value=null}}return f}function Ag(D){if(typeof D==="object"&&(D.Collection||D.Node||D.Value))return Object.assign({Alias:D.Node,Map:D.Node,Scalar:D.Node,Seq:D.Node},D.Value&&{Map:D.Value,Scalar:D.Value,Seq:D.Value},D.Collection&&{Map:D.Collection,Seq:D.Collection},D);return D}function fg(D,u,r,A){if(typeof r==="function")return r(D,u,A);if(QD.isMap(u))return r.Map?.(D,u,A);if(QD.isSeq(u))return r.Seq?.(D,u,A);if(QD.isPair(u))return r.Pair?.(D,u,A);if(QD.isScalar(u))return r.Scalar?.(D,u,A);if(QD.isAlias(u))return r.Alias?.(D,u,A);return}function Fg(D,u,r){let A=u[u.length-1];if(QD.isCollection(A))A.items[D]=r;else if(QD.isPair(A))if(D==="key")A.key=r;else A.value=r;else if(QD.isDocument(A))A.contents=r;else{let f=QD.isAlias(A)?"alias":"scalar";throw Error(`Cannot replace node with ${f} parent`)}}GX.visit=b8;GX.visitAsync=s8});var F6=L((YX)=>{var wg=AD(),XX=VA(),iX={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},UX=(D)=>D.replace(/[!,[\]{}]/g,(u)=>iX[u]);class iu{constructor(D,u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},iu.defaultYaml,D),this.tags=Object.assign({},iu.defaultTags,u)}clone(){let D=new iu(this.yaml,this.tags);return D.docStart=this.docStart,D}atDocument(){let D=new iu(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:iu.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},iu.defaultTags);break}return D}add(D,u){if(this.atNextDocument)this.yaml={explicit:iu.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},iu.defaultTags),this.atNextDocument=!1;let r=D.trim().split(/[ \t]+/),A=r.shift();switch(A){case"%TAG":{if(r.length!==2){if(u(0,"%TAG directive should contain exactly two parts"),r.length<2)return!1}let[f,w]=r;return this.tags[f]=w,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return u(0,"%YAML directive should contain exactly one part"),!1;let[f]=r;if(f==="1.1"||f==="1.2")return this.yaml.version=f,!0;else{let w=/^\d+\.\d+$/.test(f);return u(6,`Unsupported YAML version ${f}`,w),!1}}default:return u(0,`Unknown directive ${A}`,!0),!1}}tagName(D,u){if(D==="!")return"!";if(D[0]!=="!")return u(`Not a valid tag: ${D}`),null;if(D[1]==="<"){let w=D.slice(2,-1);if(w==="!"||w==="!!")return u(`Verbatim tags aren't resolved, so ${D} is invalid.`),null;if(D[D.length-1]!==">")u("Verbatim tags must end with a >");return w}let[,r,A]=D.match(/^(.*!)([^!]*)$/s);if(!A)u(`The ${D} tag has no suffix`);let f=this.tags[r];if(f)try{return f+decodeURIComponent(A)}catch(w){return u(String(w)),null}if(r==="!")return D;return u(`Could not resolve tag: ${D}`),null}tagString(D){for(let[u,r]of Object.entries(this.tags))if(D.startsWith(r))return u+UX(D.substring(r.length));return D[0]==="!"?D:`!<${D}>`}toString(D){let u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),A;if(D&&r.length>0&&wg.isNode(D.contents)){let f={};XX.visit(D.contents,(w,F)=>{if(wg.isNode(F)&&F.tag)f[F.tag]=!0}),A=Object.keys(f)}else A=[];for(let[f,w]of r){if(f==="!!"&&w==="tag:yaml.org,2002:")continue;if(!D||A.some((F)=>F.startsWith(w)))u.push(`%TAG ${f} ${w}`)}return u.join(`
11
+ `)}}iu.defaultYaml={explicit:!1,version:"1.2"};iu.defaultTags={"!!":"tag:yaml.org,2002:"};YX.Directives=iu});var z8=L((IX)=>{var $g=AD(),OX=VA();function PX(D){if(/[\x00-\x19\s,[\]{}]/.test(D)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(D)}`;throw Error(r)}return!0}function Eg(D){let u=new Set;return OX.visit(D,{Value(r,A){if(A.anchor)u.add(A.anchor)}}),u}function gg(D,u){for(let r=1;;++r){let A=`${D}${r}`;if(!u.has(A))return A}}function kX(D,u){let r=[],A=new Map,f=null;return{onAnchor:(w)=>{r.push(w),f??(f=Eg(D));let F=gg(u,f);return f.add(F),F},setAnchors:()=>{for(let w of r){let F=A.get(w);if(typeof F==="object"&&F.anchor&&($g.isScalar(F.node)||$g.isCollection(F.node)))F.node.anchor=F.anchor;else{let E=Error("Failed to resolve repeated object (this should not happen)");throw E.source=w,E}}},sourceObjects:A}}IX.anchorIsValid=PX;IX.anchorNames=Eg;IX.createNodeAnchors=kX;IX.findNewAnchor=gg});var w6=L((QX)=>{function KA(D,u,r,A){if(A&&typeof A==="object")if(Array.isArray(A))for(let f=0,w=A.length;f<w;++f){let F=A[f],E=KA(D,A,String(f),F);if(E===void 0)delete A[f];else if(E!==F)A[f]=E}else if(A instanceof Map)for(let f of Array.from(A.keys())){let w=A.get(f),F=KA(D,A,f,w);if(F===void 0)A.delete(f);else if(F!==w)A.set(f,F)}else if(A instanceof Set)for(let f of Array.from(A)){let w=KA(D,A,f,f);if(w===void 0)A.delete(f);else if(w!==f)A.delete(f),A.add(w)}else for(let[f,w]of Object.entries(A)){let F=KA(D,A,f,w);if(F===void 0)delete A[f];else if(F!==w)A[f]=F}return D.call(u,r,A)}QX.applyReviver=KA});var A0=L((bX)=>{var qX=AD();function Sg(D,u,r){if(Array.isArray(D))return D.map((A,f)=>Sg(A,String(f),r));if(D&&typeof D.toJSON==="function"){if(!r||!qX.hasAnchor(D))return D.toJSON(u,r);let A={aliasCount:0,count:1,res:void 0};r.anchors.set(D,A),r.onCreate=(w)=>{A.res=w,delete r.onCreate};let f=D.toJSON(u,r);if(r.onCreate)r.onCreate(f);return f}if(typeof D==="bigint"&&!r?.keep)return Number(D);return D}bX.toJS=Sg});var j8=L((TX)=>{var zX=w6(),_g=AD(),jX=A0();class Rg{constructor(D){Object.defineProperty(this,_g.NODE_TYPE,{value:D})}clone(){let D=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)D.range=this.range.slice();return D}toJS(D,{mapAsMap:u,maxAliasCount:r,onAnchor:A,reviver:f}={}){if(!_g.isDocument(D))throw TypeError("A document argument is required");let w={anchors:new Map,doc:D,keep:!0,mapAsMap:u===!0,mapKeyWarned:!1,maxAliasCount:typeof r==="number"?r:100},F=jX.toJS(this,"",w);if(typeof A==="function")for(let{count:E,res:$}of w.anchors.values())A($,E);return typeof f==="function"?zX.applyReviver(f,{"":F},"",F):F}}TX.NodeBase=Rg});var hA=L((yX)=>{var ZX=z8(),oX=VA(),P2=AD(),dX=j8(),lX=A0();class ng extends dX.NodeBase{constructor(D){super(P2.ALIAS);this.source=D,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(D,u){let r;if(u?.aliasResolveCache)r=u.aliasResolveCache;else if(r=[],oX.visit(D,{Node:(f,w)=>{if(P2.isAlias(w)||P2.hasAnchor(w))r.push(w)}}),u)u.aliasResolveCache=r;let A=void 0;for(let f of r){if(f===this)break;if(f.anchor===this.source)A=f}return A}toJSON(D,u){if(!u)return{source:this.source};let{anchors:r,doc:A,maxAliasCount:f}=u,w=this.resolve(A,u);if(!w){let E=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(E)}let F=r.get(w);if(!F)lX.toJS(w,null,u),F=r.get(w);if(F?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(f>=0){if(F.count+=1,F.aliasCount===0)F.aliasCount=T8(A,w,r);if(F.count*F.aliasCount>f)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return F.res}toString(D,u,r){let A=`*${this.source}`;if(D){if(ZX.anchorIsValid(this.source),D.options.verifyAliasOrder&&!D.anchors.has(this.source)){let f=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(f)}if(D.implicitKey)return`${A} `}return A}}function T8(D,u,r){if(P2.isAlias(u)){let A=u.resolve(D),f=r&&A&&r.get(A);return f?f.count*f.aliasCount:0}else if(P2.isCollection(u)){let A=0;for(let f of u.items){let w=T8(D,f,r);if(w>A)A=w}return A}else if(P2.isPair(u)){let A=T8(D,u.key,r),f=T8(D,u.value,r);return Math.max(A,f)}return 1}yX.Alias=ng});var VD=L((aX)=>{var tX=AD(),pX=j8(),xX=A0(),mX=(D)=>!D||typeof D!=="function"&&typeof D!=="object";class Q0 extends pX.NodeBase{constructor(D){super(tX.SCALAR);this.value=D}toJSON(D,u){return u?.keep?this.value:xX.toJS(this.value,D,u)}toString(){return String(this.value)}}Q0.BLOCK_FOLDED="BLOCK_FOLDED";Q0.BLOCK_LITERAL="BLOCK_LITERAL";Q0.PLAIN="PLAIN";Q0.QUOTE_DOUBLE="QUOTE_DOUBLE";Q0.QUOTE_SINGLE="QUOTE_SINGLE";aX.Scalar=Q0;aX.isScalarValue=mX});var NA=L((Fi)=>{var ui=hA(),L0=AD(),Bg=VD(),ri="tag:yaml.org,2002:";function Ai(D,u,r){if(u){let A=r.filter((w)=>w.tag===u),f=A.find((w)=>!w.format)??A[0];if(!f)throw Error(`Tag ${u} not found`);return f}return r.find((A)=>A.identify?.(D)&&!A.format)}function fi(D,u,r){if(L0.isDocument(D))D=D.contents;if(L0.isNode(D))return D;if(L0.isPair(D)){let R=r.schema[L0.MAP].createNode?.(r.schema,null,r);return R.items.push(D),R}if(D instanceof String||D instanceof Number||D instanceof Boolean||typeof BigInt<"u"&&D instanceof BigInt)D=D.valueOf();let{aliasDuplicateObjects:A,onAnchor:f,onTagObj:w,schema:F,sourceObjects:E}=r,$=void 0;if(A&&D&&typeof D==="object")if($=E.get(D),$)return $.anchor??($.anchor=f(D)),new ui.Alias($.anchor);else $={anchor:null,node:null},E.set(D,$);if(u?.startsWith("!!"))u=ri+u.slice(2);let g=Ai(D,u,F.tags);if(!g){if(D&&typeof D.toJSON==="function")D=D.toJSON();if(!D||typeof D!=="object"){let R=new Bg.Scalar(D);if($)$.node=R;return R}g=D instanceof Map?F[L0.MAP]:(Symbol.iterator in Object(D))?F[L0.SEQ]:F[L0.MAP]}if(w)w(g),delete r.onTagObj;let _=g?.createNode?g.createNode(r.schema,D,r):typeof g?.nodeClass?.from==="function"?g.nodeClass.from(r.schema,D,r):new Bg.Scalar(D);if(u)_.tag=u;else if(!g.default)_.tag=g.tag;if($)$.node=_;return _}Fi.createNode=fi});var v8=L((gi)=>{var $i=NA(),Cr=AD(),Ei=j8();function $6(D,u,r){let A=r;for(let f=u.length-1;f>=0;--f){let w=u[f];if(typeof w==="number"&&Number.isInteger(w)&&w>=0){let F=[];F[w]=A,A=F}else A=new Map([[w,A]])}return $i.createNode(A,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:D,sourceObjects:new Map})}var Wg=(D)=>D==null||typeof D==="object"&&!!D[Symbol.iterator]().next().done;class Jg extends Ei.NodeBase{constructor(D,u){super(D);Object.defineProperty(this,"schema",{value:u,configurable:!0,enumerable:!1,writable:!0})}clone(D){let u=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(D)u.schema=D;if(u.items=u.items.map((r)=>Cr.isNode(r)||Cr.isPair(r)?r.clone(D):r),this.range)u.range=this.range.slice();return u}addIn(D,u){if(Wg(D))this.add(u);else{let[r,...A]=D,f=this.get(r,!0);if(Cr.isCollection(f))f.addIn(A,u);else if(f===void 0&&this.schema)this.set(r,$6(this.schema,A,u));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${A}`)}}deleteIn(D){let[u,...r]=D;if(r.length===0)return this.delete(u);let A=this.get(u,!0);if(Cr.isCollection(A))return A.deleteIn(r);else throw Error(`Expected YAML collection at ${u}. Remaining path: ${r}`)}getIn(D,u){let[r,...A]=D,f=this.get(r,!0);if(A.length===0)return!u&&Cr.isScalar(f)?f.value:f;else return Cr.isCollection(f)?f.getIn(A,u):void 0}hasAllNullValues(D){return this.items.every((u)=>{if(!Cr.isPair(u))return!1;let r=u.value;return r==null||D&&Cr.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(D){let[u,...r]=D;if(r.length===0)return this.has(u);let A=this.get(u,!0);return Cr.isCollection(A)?A.hasIn(r):!1}setIn(D,u){let[r,...A]=D;if(A.length===0)this.set(r,u);else{let f=this.get(r,!0);if(Cr.isCollection(f))f.setIn(A,u);else if(f===void 0&&this.schema)this.set(r,$6(this.schema,A,u));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${A}`)}}}gi.Collection=Jg;gi.collectionFromPath=$6;gi.isEmptyPath=Wg});var QA=L((Wi)=>{var ni=(D)=>D.replace(/^(?!$)(?: $)?/gm,"#");function E6(D,u){if(/^\n+$/.test(D))return D.substring(1);return u?D.replace(/^(?! *$)/gm,u):D}var Bi=(D,u,r)=>D.endsWith(`
12
+ `)?E6(r,u):r.includes(`
13
13
  `)?`
14
- `+r6(r,u):(D.endsWith(" ")?"":" ")+r;cU.indentComment=r6;cU.lineComment=lU;cU.stringifyComment=yU});var ug=Q((aU)=>{function pU(D,u,r="flow",{indentAtStart:A,lineWidth:f=80,minContentWidth:w=20,onFold:F,onOverflow:E}={}){if(!f||f<0)return D;if(f<w)w=0;let $=Math.max(1+w,1+f-u.length);if(D.length<=$)return D;let g=[],R={},S=f-u.length;if(typeof A==="number")if(A>f-Math.max(2,w))g.push(0);else S=f-A;let B=void 0,J=void 0,H=!1,G=-1,U=-1,O=-1;if(r==="block"){if(G=Dg(D,G,u.length),G!==-1)S=G+$}for(let k;k=D[G+=1];){if(r==="quoted"&&k==="\\"){switch(U=G,D[G+1]){case"x":G+=3;break;case"u":G+=5;break;case"U":G+=9;break;default:G+=1}O=G}if(k===`
15
- `){if(r==="block")G=Dg(D,G,u.length);S=G+u.length+$,B=void 0}else{if(k===" "&&J&&J!==" "&&J!==`
16
- `&&J!=="\t"){let z=D[G+1];if(z&&z!==" "&&z!==`
17
- `&&z!=="\t")B=G}if(G>=S)if(B)g.push(B),S=B+$,B=void 0;else if(r==="quoted"){while(J===" "||J==="\t")J=k,k=D[G+=1],H=!0;let z=G>O+1?G-2:U-1;if(R[z])return D;g.push(z),R[z]=!0,S=z+$,B=void 0}else H=!0}J=k}if(H&&E)E();if(g.length===0)return D;if(F)F();let i=D.slice(0,g[0]);for(let k=0;k<g.length;++k){let z=g[k],q=g[k+1]||D.length;if(z===0)i=`
18
- ${u}${D.slice(0,q)}`;else{if(r==="quoted"&&R[z])i+=`${D[z]}\\`;i+=`
19
- ${u}${D.slice(z+1,q)}`}}return i}function Dg(D,u,r){let A=u,f=u+1,w=D[f];while(w===" "||w==="\t")if(u<f+r)w=D[++u];else{do w=D[++u];while(w&&w!==`
20
- `);A=u,f=u+1,w=D[f]}return A}aU.FOLD_BLOCK="block";aU.FOLD_FLOW="flow";aU.FOLD_QUOTED="quoted";aU.foldFlowLines=pU});var q1=Q((wX)=>{var ou=ID(),f0=ug(),T8=(D,u)=>({indentAtStart:u?D.indent.length:D.indentAtStart,lineWidth:D.options.lineWidth,minContentWidth:D.options.minContentWidth}),v8=(D)=>/^(%|---|\.\.\.)/m.test(D);function AX(D,u,r){if(!u||u<0)return!1;let A=u-r,f=D.length;if(f<=A)return!1;for(let w=0,F=0;w<f;++w)if(D[w]===`
21
- `){if(w-F>A)return!0;if(F=w+1,f-F<=A)return!1}return!0}function L1(D,u){let r=JSON.stringify(D);if(u.options.doubleQuotedAsJSON)return r;let{implicitKey:A}=u,f=u.options.doubleQuotedMinMultiLineLength,w=u.indent||(v8(D)?" ":""),F="",E=0;for(let $=0,g=r[$];g;g=r[++$]){if(g===" "&&r[$+1]==="\\"&&r[$+2]==="n")F+=r.slice(E,$)+"\\ ",$+=1,E=$,g="\\";if(g==="\\")switch(r[$+1]){case"u":{F+=r.slice(E,$);let R=r.substr($+2,4);switch(R){case"0000":F+="\\0";break;case"0007":F+="\\a";break;case"000b":F+="\\v";break;case"001b":F+="\\e";break;case"0085":F+="\\N";break;case"00a0":F+="\\_";break;case"2028":F+="\\L";break;case"2029":F+="\\P";break;default:if(R.substr(0,2)==="00")F+="\\x"+R.substr(2);else F+=r.substr($,6)}$+=5,E=$+1}break;case"n":if(A||r[$+2]==='"'||r.length<f)$+=1;else{F+=r.slice(E,$)+`
14
+ `+E6(r,u):(D.endsWith(" ")?"":" ")+r;Wi.indentComment=E6;Wi.lineComment=Bi;Wi.stringifyComment=ni});var Cg=L((Xi)=>{function Hi(D,u,r="flow",{indentAtStart:A,lineWidth:f=80,minContentWidth:w=20,onFold:F,onOverflow:E}={}){if(!f||f<0)return D;if(f<w)w=0;let $=Math.max(1+w,1+f-u.length);if(D.length<=$)return D;let g=[],_={},R=f-u.length;if(typeof A==="number")if(A>f-Math.max(2,w))g.push(0);else R=f-A;let n=void 0,B=void 0,C=!1,J=-1,X=-1,M=-1;if(r==="block"){if(J=Gg(D,J,u.length),J!==-1)R=J+$}for(let k;k=D[J+=1];){if(r==="quoted"&&k==="\\"){switch(X=J,D[J+1]){case"x":J+=3;break;case"u":J+=5;break;case"U":J+=9;break;default:J+=1}M=J}if(k===`
15
+ `){if(r==="block")J=Gg(D,J,u.length);R=J+u.length+$,n=void 0}else{if(k===" "&&B&&B!==" "&&B!==`
16
+ `&&B!=="\t"){let s=D[J+1];if(s&&s!==" "&&s!==`
17
+ `&&s!=="\t")n=J}if(J>=R)if(n)g.push(n),R=n+$,n=void 0;else if(r==="quoted"){while(B===" "||B==="\t")B=k,k=D[J+=1],C=!0;let s=J>M+1?J-2:X-1;if(_[s])return D;g.push(s),_[s]=!0,R=s+$,n=void 0}else C=!0}B=k}if(C&&E)E();if(g.length===0)return D;if(F)F();let P=D.slice(0,g[0]);for(let k=0;k<g.length;++k){let s=g[k],q=g[k+1]||D.length;if(s===0)P=`
18
+ ${u}${D.slice(0,q)}`;else{if(r==="quoted"&&_[s])P+=`${D[s]}\\`;P+=`
19
+ ${u}${D.slice(s+1,q)}`}}return P}function Gg(D,u,r){let A=u,f=u+1,w=D[f];while(w===" "||w==="\t")if(u<f+r)w=D[++u];else{do w=D[++u];while(w&&w!==`
20
+ `);A=u,f=u+1,w=D[f]}return A}Xi.FOLD_BLOCK="block";Xi.FOLD_FLOW="flow";Xi.FOLD_QUOTED="quoted";Xi.foldFlowLines=Hi});var qA=L((Ii)=>{var lu=VD(),f0=Cg(),o8=(D,u)=>({indentAtStart:u?D.indent.length:D.indentAtStart,lineWidth:D.options.lineWidth,minContentWidth:D.options.minContentWidth}),d8=(D)=>/^(%|---|\.\.\.)/m.test(D);function Oi(D,u,r){if(!u||u<0)return!1;let A=u-r,f=D.length;if(f<=A)return!1;for(let w=0,F=0;w<f;++w)if(D[w]===`
21
+ `){if(w-F>A)return!0;if(F=w+1,f-F<=A)return!1}return!0}function LA(D,u){let r=JSON.stringify(D);if(u.options.doubleQuotedAsJSON)return r;let{implicitKey:A}=u,f=u.options.doubleQuotedMinMultiLineLength,w=u.indent||(d8(D)?" ":""),F="",E=0;for(let $=0,g=r[$];g;g=r[++$]){if(g===" "&&r[$+1]==="\\"&&r[$+2]==="n")F+=r.slice(E,$)+"\\ ",$+=1,E=$,g="\\";if(g==="\\")switch(r[$+1]){case"u":{F+=r.slice(E,$);let _=r.substr($+2,4);switch(_){case"0000":F+="\\0";break;case"0007":F+="\\a";break;case"000b":F+="\\v";break;case"001b":F+="\\e";break;case"0085":F+="\\N";break;case"00a0":F+="\\_";break;case"2028":F+="\\L";break;case"2029":F+="\\P";break;default:if(_.substr(0,2)==="00")F+="\\x"+_.substr(2);else F+=r.substr($,6)}$+=5,E=$+1}break;case"n":if(A||r[$+2]==='"'||r.length<f)$+=1;else{F+=r.slice(E,$)+`
22
22
 
23
23
  `;while(r[$+2]==="\\"&&r[$+3]==="n"&&r[$+4]!=='"')F+=`
24
- `,$+=2;if(F+=w,r[$+2]===" ")F+="\\";$+=1,E=$+1}break;default:$+=1}}return F=E?F+r.slice(E):r,A?F:f0.foldFlowLines(F,w,f0.FOLD_QUOTED,T8(u,!1))}function A6(D,u){if(u.options.singleQuote===!1||u.implicitKey&&D.includes(`
25
- `)||/[ \t]\n|\n[ \t]/.test(D))return L1(D,u);let r=u.indent||(v8(D)?" ":""),A="'"+D.replace(/'/g,"''").replace(/\n+/g,`$&
26
- ${r}`)+"'";return u.implicitKey?A:f0.foldFlowLines(A,r,f0.FOLD_FLOW,T8(u,!1))}function i2(D,u){let{singleQuote:r}=u.options,A;if(r===!1)A=L1;else{let f=D.includes('"'),w=D.includes("'");if(f&&!w)A=A6;else if(w&&!f)A=L1;else A=r?A6:L1}return A(D,u)}var f6;try{f6=new RegExp(`(^|(?<!
24
+ `,$+=2;if(F+=w,r[$+2]===" ")F+="\\";$+=1,E=$+1}break;default:$+=1}}return F=E?F+r.slice(E):r,A?F:f0.foldFlowLines(F,w,f0.FOLD_QUOTED,o8(u,!1))}function g6(D,u){if(u.options.singleQuote===!1||u.implicitKey&&D.includes(`
25
+ `)||/[ \t]\n|\n[ \t]/.test(D))return LA(D,u);let r=u.indent||(d8(D)?" ":""),A="'"+D.replace(/'/g,"''").replace(/\n+/g,`$&
26
+ ${r}`)+"'";return u.implicitKey?A:f0.foldFlowLines(A,r,f0.FOLD_FLOW,o8(u,!1))}function k2(D,u){let{singleQuote:r}=u.options,A;if(r===!1)A=LA;else{let f=D.includes('"'),w=D.includes("'");if(f&&!w)A=g6;else if(w&&!f)A=LA;else A=r?g6:LA}return A(D,u)}var S6;try{S6=new RegExp(`(^|(?<!
27
27
  ))
28
28
  +(?!
29
- |$)`,"g")}catch{f6=/\n+(?!\n|$)/g}function j8({comment:D,type:u,value:r},A,f,w){let{blockQuote:F,commentString:E,lineWidth:$}=A.options;if(!F||/\n[\t ]+$/.test(r))return i2(r,A);let g=A.indent||(A.forceBlockIndent||v8(r)?" ":""),R=F==="literal"?!0:F==="folded"||u===ou.Scalar.BLOCK_FOLDED?!1:u===ou.Scalar.BLOCK_LITERAL?!0:!AX(r,$,g.length);if(!r)return R?`|
29
+ |$)`,"g")}catch{S6=/\n+(?!\n|$)/g}function Z8({comment:D,type:u,value:r},A,f,w){let{blockQuote:F,commentString:E,lineWidth:$}=A.options;if(!F||/\n[\t ]+$/.test(r))return k2(r,A);let g=A.indent||(A.forceBlockIndent||d8(r)?" ":""),_=F==="literal"?!0:F==="folded"||u===lu.Scalar.BLOCK_FOLDED?!1:u===lu.Scalar.BLOCK_LITERAL?!0:!Oi(r,$,g.length);if(!r)return _?`|
30
30
  `:`>
31
- `;let S,B;for(B=r.length;B>0;--B){let q=r[B-1];if(q!==`
32
- `&&q!=="\t"&&q!==" ")break}let J=r.substring(B),H=J.indexOf(`
33
- `);if(H===-1)S="-";else if(r===J||H!==J.length-1){if(S="+",w)w()}else S="";if(J){if(r=r.slice(0,-J.length),J[J.length-1]===`
34
- `)J=J.slice(0,-1);J=J.replace(f6,`$&${g}`)}let G=!1,U,O=-1;for(U=0;U<r.length;++U){let q=r[U];if(q===" ")G=!0;else if(q===`
35
- `)O=U;else break}let i=r.substring(0,O<U?O+1:U);if(i)r=r.substring(i.length),i=i.replace(/\n+/g,`$&${g}`);let z=(G?g?"2":"1":"")+S;if(D){if(z+=" "+E(D.replace(/ ?[\r\n]+/g," ")),f)f()}if(!R){let q=r.replace(/\n+/g,`
36
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${g}`),M=!1,s=T8(A,!0);if(F!=="folded"&&u!==ou.Scalar.BLOCK_FOLDED)s.onOverflow=()=>{M=!0};let h=f0.foldFlowLines(`${i}${q}${J}`,g,f0.FOLD_BLOCK,s);if(!M)return`>${z}
37
- ${g}${h}`}return r=r.replace(/\n+/g,`$&${g}`),`|${z}
38
- ${g}${i}${r}${J}`}function fX(D,u,r,A){let{type:f,value:w}=D,{actualString:F,implicitKey:E,indent:$,indentStep:g,inFlow:R}=u;if(E&&w.includes(`
39
- `)||R&&/[[\]{},]/.test(w))return i2(w,u);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(w))return E||R||!w.includes(`
40
- `)?i2(w,u):j8(D,u,r,A);if(!E&&!R&&f!==ou.Scalar.PLAIN&&w.includes(`
41
- `))return j8(D,u,r,A);if(v8(w)){if($==="")return u.forceBlockIndent=!0,j8(D,u,r,A);else if(E&&$===g)return i2(w,u)}let S=w.replace(/\n+/g,`$&
42
- ${$}`);if(F){let B=(G)=>G.default&&G.tag!=="tag:yaml.org,2002:str"&&G.test?.test(S),{compat:J,tags:H}=u.doc.schema;if(H.some(B)||J?.some(B))return i2(w,u)}return E?S:f0.foldFlowLines(S,$,f0.FOLD_FLOW,T8(u,!1))}function FX(D,u,r,A){let{implicitKey:f,inFlow:w}=u,F=typeof D.value==="string"?D:Object.assign({},D,{value:String(D.value)}),{type:E}=D;if(E!==ou.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(F.value))E=ou.Scalar.QUOTE_DOUBLE}let $=(R)=>{switch(R){case ou.Scalar.BLOCK_FOLDED:case ou.Scalar.BLOCK_LITERAL:return f||w?i2(F.value,u):j8(F,u,r,A);case ou.Scalar.QUOTE_DOUBLE:return L1(F.value,u);case ou.Scalar.QUOTE_SINGLE:return A6(F.value,u);case ou.Scalar.PLAIN:return fX(F,u,r,A);default:return null}},g=$(E);if(g===null){let{defaultKeyType:R,defaultStringType:S}=u.options,B=f&&R||S;if(g=$(B),g===null)throw Error(`Unsupported default string type ${B}`)}return g}wX.stringifyString=FX});var b1=Q((WX)=>{var EX=L8(),F0=AD(),gX=Q1(),_X=q1();function RX(D,u){let r=Object.assign({blockQuote:!0,commentString:gX.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},D.schema.toStringOptions,u),A;switch(r.collectionStyle){case"block":A=!1;break;case"flow":A=!0;break;default:A=null}return{anchors:new Set,doc:D,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent==="number"?" ".repeat(r.indent):" ",inFlow:A,options:r}}function SX(D,u){if(u.tag){let f=D.filter((w)=>w.tag===u.tag);if(f.length>0)return f.find((w)=>w.format===u.format)??f[0]}let r=void 0,A;if(F0.isScalar(u)){A=u.value;let f=D.filter((w)=>w.identify?.(A));if(f.length>1){let w=f.filter((F)=>F.test);if(w.length>0)f=w}r=f.find((w)=>w.format===u.format)??f.find((w)=>!w.format)}else A=u,r=D.find((f)=>f.nodeClass&&A instanceof f.nodeClass);if(!r){let f=A?.constructor?.name??(A===null?"null":typeof A);throw Error(`Tag not resolved for ${f} value`)}return r}function BX(D,u,{anchors:r,doc:A}){if(!A.directives)return"";let f=[],w=(F0.isScalar(D)||F0.isCollection(D))&&D.anchor;if(w&&EX.anchorIsValid(w))r.add(w),f.push(`&${w}`);let F=D.tag??(u.default?null:u.tag);if(F)f.push(A.directives.tagString(F));return f.join(" ")}function JX(D,u,r,A){if(F0.isPair(D))return D.toString(u,r,A);if(F0.isAlias(D)){if(u.doc.directives)return D.toString(u);if(u.resolvedAliases?.has(D))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(u.resolvedAliases)u.resolvedAliases.add(D);else u.resolvedAliases=new Set([D]);D=D.resolve(u.doc)}}let f=void 0,w=F0.isNode(D)?D:u.doc.createNode(D,{onTagObj:($)=>f=$});f??(f=SX(u.doc.schema.tags,w));let F=BX(w,f,u);if(F.length>0)u.indentAtStart=(u.indentAtStart??0)+F.length+1;let E=typeof f.stringify==="function"?f.stringify(w,u,r,A):F0.isScalar(w)?_X.stringifyString(w,u,r,A):w.toString(u,r,A);if(!F)return E;return F0.isScalar(w)||E[0]==="{"||E[0]==="["?`${F} ${E}`:`${F}
43
- ${u.indent}${E}`}WX.createStringifyContext=RX;WX.stringify=JX});var fg=Q((nX)=>{var br=AD(),rg=ID(),Ag=b1(),z1=Q1();function HX({key:D,value:u},r,A,f){let{allNullValues:w,doc:F,indent:E,indentStep:$,options:{commentString:g,indentSeq:R,simpleKeys:S}}=r,B=br.isNode(D)&&D.comment||null;if(S){if(B)throw Error("With simple keys, key nodes cannot have comments");if(br.isCollection(D)||!br.isNode(D)&&typeof D==="object")throw Error("With simple keys, collection cannot be used as a key value")}let J=!S&&(!D||B&&u==null&&!r.inFlow||br.isCollection(D)||(br.isScalar(D)?D.type===rg.Scalar.BLOCK_FOLDED||D.type===rg.Scalar.BLOCK_LITERAL:typeof D==="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!J&&(S||!w),indent:E+$});let H=!1,G=!1,U=Ag.stringify(D,r,()=>H=!0,()=>G=!0);if(!J&&!r.inFlow&&U.length>1024){if(S)throw Error("With simple keys, single line scalar must not span more than 1024 characters");J=!0}if(r.inFlow){if(w||u==null){if(H&&A)A();return U===""?"?":J?`? ${U}`:U}}else if(w&&!S||u==null&&J){if(U=`? ${U}`,B&&!H)U+=z1.lineComment(U,r.indent,g(B));else if(G&&f)f();return U}if(H)B=null;if(J){if(B)U+=z1.lineComment(U,r.indent,g(B));U=`? ${U}
44
- ${E}:`}else if(U=`${U}:`,B)U+=z1.lineComment(U,r.indent,g(B));let O,i,k;if(br.isNode(u))O=!!u.spaceBefore,i=u.commentBefore,k=u.comment;else if(O=!1,i=null,k=null,u&&typeof u==="object")u=F.createNode(u);if(r.implicitKey=!1,!J&&!B&&br.isScalar(u))r.indentAtStart=U.length+1;if(G=!1,!R&&$.length>=2&&!r.inFlow&&!J&&br.isSeq(u)&&!u.flow&&!u.tag&&!u.anchor)r.indent=r.indent.substring(2);let z=!1,q=Ag.stringify(u,r,()=>z=!0,()=>G=!0),M=" ";if(B||O||i){if(M=O?`
45
- `:"",i){let s=g(i);M+=`
46
- ${z1.indentComment(s,r.indent)}`}if(q===""&&!r.inFlow){if(M===`
47
- `&&k)M=`
48
-
49
- `}else M+=`
50
- ${r.indent}`}else if(!J&&br.isCollection(u)){let s=q[0],h=q.indexOf(`
51
- `),rD=h!==-1,_D=r.inFlow??u.flow??u.items.length===0;if(rD||!_D){let WD=!1;if(rD&&(s==="&"||s==="!")){let e=q.indexOf(" ");if(s==="&"&&e!==-1&&e<h&&q[e+1]==="!")e=q.indexOf(" ",e+1);if(e===-1||h<e)WD=!0}if(!WD)M=`
31
+ `;let R,n;for(n=r.length;n>0;--n){let q=r[n-1];if(q!==`
32
+ `&&q!=="\t"&&q!==" ")break}let B=r.substring(n),C=B.indexOf(`
33
+ `);if(C===-1)R="-";else if(r===B||C!==B.length-1){if(R="+",w)w()}else R="";if(B){if(r=r.slice(0,-B.length),B[B.length-1]===`
34
+ `)B=B.slice(0,-1);B=B.replace(S6,`$&${g}`)}let J=!1,X,M=-1;for(X=0;X<r.length;++X){let q=r[X];if(q===" ")J=!0;else if(q===`
35
+ `)M=X;else break}let P=r.substring(0,M<X?M+1:X);if(P)r=r.substring(P.length),P=P.replace(/\n+/g,`$&${g}`);let s=(J?g?"2":"1":"")+R;if(D){if(s+=" "+E(D.replace(/ ?[\r\n]+/g," ")),f)f()}if(!_){let q=r.replace(/\n+/g,`
36
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${g}`),Y=!1,v=o8(A,!0);if(F!=="folded"&&u!==lu.Scalar.BLOCK_FOLDED)v.onOverflow=()=>{Y=!0};let N=f0.foldFlowLines(`${P}${q}${B}`,g,f0.FOLD_BLOCK,v);if(!Y)return`>${s}
37
+ ${g}${N}`}return r=r.replace(/\n+/g,`$&${g}`),`|${s}
38
+ ${g}${P}${r}${B}`}function Pi(D,u,r,A){let{type:f,value:w}=D,{actualString:F,implicitKey:E,indent:$,indentStep:g,inFlow:_}=u;if(E&&w.includes(`
39
+ `)||_&&/[[\]{},]/.test(w))return k2(w,u);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(w))return E||_||!w.includes(`
40
+ `)?k2(w,u):Z8(D,u,r,A);if(!E&&!_&&f!==lu.Scalar.PLAIN&&w.includes(`
41
+ `))return Z8(D,u,r,A);if(d8(w)){if($==="")return u.forceBlockIndent=!0,Z8(D,u,r,A);else if(E&&$===g)return k2(w,u)}let R=w.replace(/\n+/g,`$&
42
+ ${$}`);if(F){let n=(J)=>J.default&&J.tag!=="tag:yaml.org,2002:str"&&J.test?.test(R),{compat:B,tags:C}=u.doc.schema;if(C.some(n)||B?.some(n))return k2(w,u)}return E?R:f0.foldFlowLines(R,$,f0.FOLD_FLOW,o8(u,!1))}function ki(D,u,r,A){let{implicitKey:f,inFlow:w}=u,F=typeof D.value==="string"?D:Object.assign({},D,{value:String(D.value)}),{type:E}=D;if(E!==lu.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(F.value))E=lu.Scalar.QUOTE_DOUBLE}let $=(_)=>{switch(_){case lu.Scalar.BLOCK_FOLDED:case lu.Scalar.BLOCK_LITERAL:return f||w?k2(F.value,u):Z8(F,u,r,A);case lu.Scalar.QUOTE_DOUBLE:return LA(F.value,u);case lu.Scalar.QUOTE_SINGLE:return g6(F.value,u);case lu.Scalar.PLAIN:return Pi(F,u,r,A);default:return null}},g=$(E);if(g===null){let{defaultKeyType:_,defaultStringType:R}=u.options,n=f&&_||R;if(g=$(n),g===null)throw Error(`Unsupported default string type ${n}`)}return g}Ii.stringifyString=ki});var bA=L((si)=>{var Ki=z8(),F0=AD(),hi=QA(),Ni=qA();function Qi(D,u){let r=Object.assign({blockQuote:!0,commentString:hi.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},D.schema.toStringOptions,u),A;switch(r.collectionStyle){case"block":A=!1;break;case"flow":A=!0;break;default:A=null}return{anchors:new Set,doc:D,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent==="number"?" ".repeat(r.indent):" ",inFlow:A,options:r}}function Li(D,u){if(u.tag){let f=D.filter((w)=>w.tag===u.tag);if(f.length>0)return f.find((w)=>w.format===u.format)??f[0]}let r=void 0,A;if(F0.isScalar(u)){A=u.value;let f=D.filter((w)=>w.identify?.(A));if(f.length>1){let w=f.filter((F)=>F.test);if(w.length>0)f=w}r=f.find((w)=>w.format===u.format)??f.find((w)=>!w.format)}else A=u,r=D.find((f)=>f.nodeClass&&A instanceof f.nodeClass);if(!r){let f=A?.constructor?.name??(A===null?"null":typeof A);throw Error(`Tag not resolved for ${f} value`)}return r}function qi(D,u,{anchors:r,doc:A}){if(!A.directives)return"";let f=[],w=(F0.isScalar(D)||F0.isCollection(D))&&D.anchor;if(w&&Ki.anchorIsValid(w))r.add(w),f.push(`&${w}`);let F=D.tag??(u.default?null:u.tag);if(F)f.push(A.directives.tagString(F));return f.join(" ")}function bi(D,u,r,A){if(F0.isPair(D))return D.toString(u,r,A);if(F0.isAlias(D)){if(u.doc.directives)return D.toString(u);if(u.resolvedAliases?.has(D))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(u.resolvedAliases)u.resolvedAliases.add(D);else u.resolvedAliases=new Set([D]);D=D.resolve(u.doc)}}let f=void 0,w=F0.isNode(D)?D:u.doc.createNode(D,{onTagObj:($)=>f=$});f??(f=Li(u.doc.schema.tags,w));let F=qi(w,f,u);if(F.length>0)u.indentAtStart=(u.indentAtStart??0)+F.length+1;let E=typeof f.stringify==="function"?f.stringify(w,u,r,A):F0.isScalar(w)?Ni.stringifyString(w,u,r,A):w.toString(u,r,A);if(!F)return E;return F0.isScalar(w)||E[0]==="{"||E[0]==="["?`${F} ${E}`:`${F}
43
+ ${u.indent}${E}`}si.createStringifyContext=Qi;si.stringify=bi});var ig=L((vi)=>{var sr=AD(),Hg=VD(),Xg=bA(),sA=QA();function Ti({key:D,value:u},r,A,f){let{allNullValues:w,doc:F,indent:E,indentStep:$,options:{commentString:g,indentSeq:_,simpleKeys:R}}=r,n=sr.isNode(D)&&D.comment||null;if(R){if(n)throw Error("With simple keys, key nodes cannot have comments");if(sr.isCollection(D)||!sr.isNode(D)&&typeof D==="object")throw Error("With simple keys, collection cannot be used as a key value")}let B=!R&&(!D||n&&u==null&&!r.inFlow||sr.isCollection(D)||(sr.isScalar(D)?D.type===Hg.Scalar.BLOCK_FOLDED||D.type===Hg.Scalar.BLOCK_LITERAL:typeof D==="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!B&&(R||!w),indent:E+$});let C=!1,J=!1,X=Xg.stringify(D,r,()=>C=!0,()=>J=!0);if(!B&&!r.inFlow&&X.length>1024){if(R)throw Error("With simple keys, single line scalar must not span more than 1024 characters");B=!0}if(r.inFlow){if(w||u==null){if(C&&A)A();return X===""?"?":B?`? ${X}`:X}}else if(w&&!R||u==null&&B){if(X=`? ${X}`,n&&!C)X+=sA.lineComment(X,r.indent,g(n));else if(J&&f)f();return X}if(C)n=null;if(B){if(n)X+=sA.lineComment(X,r.indent,g(n));X=`? ${X}
44
+ ${E}:`}else if(X=`${X}:`,n)X+=sA.lineComment(X,r.indent,g(n));let M,P,k;if(sr.isNode(u))M=!!u.spaceBefore,P=u.commentBefore,k=u.comment;else if(M=!1,P=null,k=null,u&&typeof u==="object")u=F.createNode(u);if(r.implicitKey=!1,!B&&!n&&sr.isScalar(u))r.indentAtStart=X.length+1;if(J=!1,!_&&$.length>=2&&!r.inFlow&&!B&&sr.isSeq(u)&&!u.flow&&!u.tag&&!u.anchor)r.indent=r.indent.substring(2);let s=!1,q=Xg.stringify(u,r,()=>s=!0,()=>J=!0),Y=" ";if(n||M||P){if(Y=M?`
45
+ `:"",P){let v=g(P);Y+=`
46
+ ${sA.indentComment(v,r.indent)}`}if(q===""&&!r.inFlow){if(Y===`
47
+ `&&k)Y=`
48
+
49
+ `}else Y+=`
50
+ ${r.indent}`}else if(!B&&sr.isCollection(u)){let v=q[0],N=q.indexOf(`
51
+ `),rD=N!==-1,_D=r.inFlow??u.flow??u.items.length===0;if(rD||!_D){let WD=!1;if(rD&&(v==="&"||v==="!")){let e=q.indexOf(" ");if(v==="&"&&e!==-1&&e<N&&q[e+1]==="!")e=q.indexOf(" ",e+1);if(e===-1||N<e)WD=!0}if(!WD)Y=`
52
52
  ${r.indent}`}}else if(q===""||q[0]===`
53
- `)M="";if(U+=M+q,r.inFlow){if(z&&A)A()}else if(k&&!z)U+=z1.lineComment(U,r.indent,g(k));else if(G&&f)f();return U}nX.stringifyPair=HX});var F6=Q((MX)=>{var Fg=yA("process");function XX(D,...u){if(D==="debug")console.log(...u)}function YX(D,u){if(D==="debug"||D==="warn")if(typeof Fg.emitWarning==="function")Fg.emitWarning(u);else console.warn(u)}MX.debug=XX;MX.warn=YX});var o8=Q((kX)=>{var j1=AD(),wg=ID(),s8="<<",Z8={identify:(D)=>D===s8||typeof D==="symbol"&&D.description===s8,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wg.Scalar(Symbol(s8)),{addToJSMap:$g}),stringify:()=>s8},iX=(D,u)=>(Z8.identify(u)||j1.isScalar(u)&&(!u.type||u.type===wg.Scalar.PLAIN)&&Z8.identify(u.value))&&D?.doc.schema.tags.some((r)=>r.tag===Z8.tag&&r.default);function $g(D,u,r){if(r=D&&j1.isAlias(r)?r.resolve(D.doc):r,j1.isSeq(r))for(let A of r.items)w6(D,u,A);else if(Array.isArray(r))for(let A of r)w6(D,u,A);else w6(D,u,r)}function w6(D,u,r){let A=D&&j1.isAlias(r)?r.resolve(D.doc):r;if(!j1.isMap(A))throw Error("Merge sources must be maps or map aliases");let f=A.toJSON(null,D,Map);for(let[w,F]of f)if(u instanceof Map){if(!u.has(w))u.set(w,F)}else if(u instanceof Set)u.add(w);else if(!Object.prototype.hasOwnProperty.call(u,w))Object.defineProperty(u,w,{value:F,writable:!0,enumerable:!0,configurable:!0});return u}kX.addMergeToJSMap=$g;kX.isMergeKey=iX;kX.merge=Z8});var E6=Q((qX)=>{var hX=F6(),Eg=o8(),NX=b1(),gg=AD(),$6=A0();function QX(D,u,{key:r,value:A}){if(gg.isNode(r)&&r.addToJSMap)r.addToJSMap(D,u,A);else if(Eg.isMergeKey(D,r))Eg.addMergeToJSMap(D,u,A);else{let f=$6.toJS(r,"",D);if(u instanceof Map)u.set(f,$6.toJS(A,f,D));else if(u instanceof Set)u.add(f);else{let w=LX(r,f,D),F=$6.toJS(A,w,D);if(w in u)Object.defineProperty(u,w,{value:F,writable:!0,enumerable:!0,configurable:!0});else u[w]=F}}return u}function LX(D,u,r){if(u===null)return"";if(typeof u!=="object")return String(u);if(gg.isNode(D)&&r?.doc){let A=NX.createStringifyContext(r.doc,{});A.anchors=new Set;for(let w of r.anchors.keys())A.anchors.add(w.anchor);A.inFlow=!0,A.inStringifyKey=!0;let f=D.toString(A);if(!r.mapKeyWarned){let w=JSON.stringify(f);if(w.length>40)w=w.substring(0,36)+'..."';hX.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${w}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return f}return JSON.stringify(u)}qX.addPairToJSMap=QX});var w0=Q((vX)=>{var _g=N1(),zX=fg(),jX=E6(),d8=AD();function TX(D,u,r){let A=_g.createNode(D,void 0,r),f=_g.createNode(u,void 0,r);return new y8(A,f)}class y8{constructor(D,u=null){Object.defineProperty(this,d8.NODE_TYPE,{value:d8.PAIR}),this.key=D,this.value=u}clone(D){let{key:u,value:r}=this;if(d8.isNode(u))u=u.clone(D);if(d8.isNode(r))r=r.clone(D);return new y8(u,r)}toJSON(D,u){let r=u?.mapAsMap?new Map:{};return jX.addPairToJSMap(u,r,this)}toString(D,u,r){return D?.doc?zX.stringifyPair(this,D,u,r):JSON.stringify(this)}}vX.Pair=y8;vX.createPair=TX});var g6=Q((lX)=>{var q0=AD(),Rg=b1(),l8=Q1();function oX(D,u,r){return(u.inFlow??D.flow?yX:dX)(D,u,r)}function dX({comment:D,items:u},r,{blockItemPrefix:A,flowChars:f,itemIndent:w,onChompKeep:F,onComment:E}){let{indent:$,options:{commentString:g}}=r,R=Object.assign({},r,{indent:w,type:null}),S=!1,B=[];for(let H=0;H<u.length;++H){let G=u[H],U=null;if(q0.isNode(G)){if(!S&&G.spaceBefore)B.push("");if(c8(r,B,G.commentBefore,S),G.comment)U=G.comment}else if(q0.isPair(G)){let i=q0.isNode(G.key)?G.key:null;if(i){if(!S&&i.spaceBefore)B.push("");c8(r,B,i.commentBefore,S)}}S=!1;let O=Rg.stringify(G,R,()=>U=null,()=>S=!0);if(U)O+=l8.lineComment(O,w,g(U));if(S&&U)S=!1;B.push(A+O)}let J;if(B.length===0)J=f.start+f.end;else{J=B[0];for(let H=1;H<B.length;++H){let G=B[H];J+=G?`
54
- ${$}${G}`:`
55
- `}}if(D){if(J+=`
56
- `+l8.indentComment(g(D),$),E)E()}else if(S&&F)F();return J}function yX({items:D},u,{flowChars:r,itemIndent:A}){let{indent:f,indentStep:w,flowCollectionPadding:F,options:{commentString:E}}=u;A+=w;let $=Object.assign({},u,{indent:A,inFlow:!0,type:null}),g=!1,R=0,S=[];for(let H=0;H<D.length;++H){let G=D[H],U=null;if(q0.isNode(G)){if(G.spaceBefore)S.push("");if(c8(u,S,G.commentBefore,!1),G.comment)U=G.comment}else if(q0.isPair(G)){let i=q0.isNode(G.key)?G.key:null;if(i){if(i.spaceBefore)S.push("");if(c8(u,S,i.commentBefore,!1),i.comment)g=!0}let k=q0.isNode(G.value)?G.value:null;if(k){if(k.comment)U=k.comment;if(k.commentBefore)g=!0}else if(G.value==null&&i?.comment)U=i.comment}if(U)g=!0;let O=Rg.stringify(G,$,()=>U=null);if(g||(g=S.length>R||O.includes(`
57
- `)),H<D.length-1)O+=",";else if(u.options.trailingComma){if(u.options.lineWidth>0)g||(g=S.reduce((i,k)=>i+k.length+2,2)+(O.length+2)>u.options.lineWidth);if(g)O+=","}if(U)O+=l8.lineComment(O,A,E(U));S.push(O),R=S.length}let{start:B,end:J}=r;if(S.length===0)return B+J;else{if(!g){let H=S.reduce((G,U)=>G+U.length+2,2);g=u.options.lineWidth>0&&H>u.options.lineWidth}if(g){let H=B;for(let G of S)H+=G?`
58
- ${w}${f}${G}`:`
59
- `;return`${H}
60
- ${f}${J}`}else return`${B}${F}${S.join(" ")}${F}${J}`}}function c8({indent:D,options:{commentString:u}},r,A,f){if(A&&f)A=A.replace(/^\n+/,"");if(A){let w=l8.indentComment(u(A),D);r.push(w.trimStart())}}lX.stringifyCollection=oX});var E0=Q((aX)=>{var tX=g6(),xX=E6(),mX=z8(),$0=AD(),t8=w0(),pX=ID();function T1(D,u){let r=$0.isScalar(u)?u.value:u;for(let A of D)if($0.isPair(A)){if(A.key===u||A.key===r)return A;if($0.isScalar(A.key)&&A.key.value===r)return A}return}class Sg extends mX.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(D){super($0.MAP,D);this.items=[]}static from(D,u,r){let{keepUndefined:A,replacer:f}=r,w=new this(D),F=(E,$)=>{if(typeof f==="function")$=f.call(u,E,$);else if(Array.isArray(f)&&!f.includes(E))return;if($!==void 0||A)w.items.push(t8.createPair(E,$,r))};if(u instanceof Map)for(let[E,$]of u)F(E,$);else if(u&&typeof u==="object")for(let E of Object.keys(u))F(E,u[E]);if(typeof D.sortMapEntries==="function")w.items.sort(D.sortMapEntries);return w}add(D,u){let r;if($0.isPair(D))r=D;else if(!D||typeof D!=="object"||!("key"in D))r=new t8.Pair(D,D?.value);else r=new t8.Pair(D.key,D.value);let A=T1(this.items,r.key),f=this.schema?.sortMapEntries;if(A){if(!u)throw Error(`Key ${r.key} already set`);if($0.isScalar(A.value)&&pX.isScalarValue(r.value))A.value.value=r.value;else A.value=r.value}else if(f){let w=this.items.findIndex((F)=>f(r,F)<0);if(w===-1)this.items.push(r);else this.items.splice(w,0,r)}else this.items.push(r)}delete(D){let u=T1(this.items,D);if(!u)return!1;return this.items.splice(this.items.indexOf(u),1).length>0}get(D,u){let A=T1(this.items,D)?.value;return(!u&&$0.isScalar(A)?A.value:A)??void 0}has(D){return!!T1(this.items,D)}set(D,u){this.add(new t8.Pair(D,u),!0)}toJSON(D,u,r){let A=r?new r:u?.mapAsMap?new Map:{};if(u?.onCreate)u.onCreate(A);for(let f of this.items)xX.addPairToJSMap(u,A,f);return A}toString(D,u,r){if(!D)return JSON.stringify(this);for(let A of this.items)if(!$0.isPair(A))throw Error(`Map items must all be pairs; found ${JSON.stringify(A)} instead`);if(!D.allNullValues&&this.hasAllNullValues(!1))D=Object.assign({},D,{allNullValues:!0});return tX.stringifyCollection(this,D,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:D.indent||"",onChompKeep:r,onComment:u})}}aX.YAMLMap=Sg;aX.findPair=T1});var k2=Q((AY)=>{var uY=AD(),Bg=E0(),rY={collection:"map",default:!0,nodeClass:Bg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(D,u){if(!uY.isMap(D))u("Expected a mapping for this tag");return D},createNode:(D,u,r)=>Bg.YAMLMap.from(D,u,r)};AY.map=rY});var g0=Q((_Y)=>{var FY=N1(),wY=g6(),$Y=z8(),m8=AD(),EY=ID(),gY=A0();class Jg extends $Y.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(D){super(m8.SEQ,D);this.items=[]}add(D){this.items.push(D)}delete(D){let u=x8(D);if(typeof u!=="number")return!1;return this.items.splice(u,1).length>0}get(D,u){let r=x8(D);if(typeof r!=="number")return;let A=this.items[r];return!u&&m8.isScalar(A)?A.value:A}has(D){let u=x8(D);return typeof u==="number"&&u<this.items.length}set(D,u){let r=x8(D);if(typeof r!=="number")throw Error(`Expected a valid index, not ${D}.`);let A=this.items[r];if(m8.isScalar(A)&&EY.isScalarValue(u))A.value=u;else this.items[r]=u}toJSON(D,u){let r=[];if(u?.onCreate)u.onCreate(r);let A=0;for(let f of this.items)r.push(gY.toJS(f,String(A++),u));return r}toString(D,u,r){if(!D)return JSON.stringify(this);return wY.stringifyCollection(this,D,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(D.indent||"")+" ",onChompKeep:r,onComment:u})}static from(D,u,r){let{replacer:A}=r,f=new this(D);if(u&&Symbol.iterator in Object(u)){let w=0;for(let F of u){if(typeof A==="function"){let E=u instanceof Set?F:String(w++);F=A.call(u,E,F)}f.items.push(FY.createNode(F,void 0,r))}}return f}}function x8(D){let u=m8.isScalar(D)?D.value:D;if(u&&typeof u==="string")u=Number(u);return typeof u==="number"&&Number.isInteger(u)&&u>=0?u:null}_Y.YAMLSeq=Jg});var I2=Q((JY)=>{var SY=AD(),Wg=g0(),BY={collection:"seq",default:!0,nodeClass:Wg.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(D,u){if(!SY.isSeq(D))u("Expected a sequence for this tag");return D},createNode:(D,u,r)=>Wg.YAMLSeq.from(D,u,r)};JY.seq=BY});var v1=Q((HY)=>{var GY=q1(),CY={identify:(D)=>typeof D==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(D)=>D,stringify(D,u,r,A){return u=Object.assign({actualString:!0},u),GY.stringifyString(D,u,r,A)}};HY.string=CY});var p8=Q((UY)=>{var Gg=ID(),Cg={identify:(D)=>D==null,createNode:()=>new Gg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Gg.Scalar(null),stringify:({source:D},u)=>typeof D==="string"&&Cg.test.test(D)?D:u.options.nullStr};UY.nullTag=Cg});var _6=Q((MY)=>{var YY=ID(),Hg={identify:(D)=>typeof D==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(D)=>new YY.Scalar(D[0]==="t"||D[0]==="T"),stringify({source:D,value:u},r){if(D&&Hg.test.test(D)){let A=D[0]==="t"||D[0]==="T";if(u===A)return D}return u?r.options.trueStr:r.options.falseStr}};MY.boolTag=Hg});var V2=Q((iY)=>{function PY({format:D,minFractionDigits:u,tag:r,value:A}){if(typeof A==="bigint")return String(A);let f=typeof A==="number"?A:Number(A);if(!isFinite(f))return isNaN(f)?".nan":f<0?"-.inf":".inf";let w=Object.is(A,-0)?"-0":JSON.stringify(A);if(!D&&u&&(!r||r==="tag:yaml.org,2002:float")&&/^\d/.test(w)){let F=w.indexOf(".");if(F<0)F=w.length,w+=".";let E=u-(w.length-F-1);while(E-- >0)w+="0"}return w}iY.stringifyNumber=PY});var S6=Q((NY)=>{var IY=ID(),R6=V2(),VY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(D)=>D.slice(-3).toLowerCase()==="nan"?NaN:D[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:R6.stringifyNumber},KY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(D)=>parseFloat(D),stringify(D){let u=Number(D.value);return isFinite(u)?u.toExponential():R6.stringifyNumber(D)}},hY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(D){let u=new IY.Scalar(parseFloat(D)),r=D.indexOf(".");if(r!==-1&&D[D.length-1]==="0")u.minFractionDigits=D.length-r-1;return u},stringify:R6.stringifyNumber};NY.float=hY;NY.floatExp=KY;NY.floatNaN=VY});var J6=Q((TY)=>{var ng=V2(),a8=(D)=>typeof D==="bigint"||Number.isInteger(D),B6=(D,u,r,{intAsBigInt:A})=>A?BigInt(D):parseInt(D.substring(u),r);function Ug(D,u,r){let{value:A}=D;if(a8(A)&&A>=0)return r+A.toString(u);return ng.stringifyNumber(D)}var bY={identify:(D)=>a8(D)&&D>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(D,u,r)=>B6(D,2,8,r),stringify:(D)=>Ug(D,8,"0o")},zY={identify:a8,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(D,u,r)=>B6(D,0,10,r),stringify:ng.stringifyNumber},jY={identify:(D)=>a8(D)&&D>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(D,u,r)=>B6(D,2,16,r),stringify:(D)=>Ug(D,16,"0x")};TY.int=zY;TY.intHex=jY;TY.intOct=bY});var Xg=Q((xY)=>{var oY=k2(),dY=p8(),yY=I2(),lY=v1(),cY=_6(),W6=S6(),G6=J6(),tY=[oY.map,yY.seq,lY.string,dY.nullTag,cY.boolTag,G6.intOct,G6.int,G6.intHex,W6.floatNaN,W6.floatExp,W6.float];xY.schema=tY});var Mg=Q((AM)=>{var pY=ID(),aY=k2(),eY=I2();function Yg(D){return typeof D==="bigint"||Number.isInteger(D)}var e8=({value:D})=>JSON.stringify(D),DM=[{identify:(D)=>typeof D==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(D)=>D,stringify:e8},{identify:(D)=>D==null,createNode:()=>new pY.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:e8},{identify:(D)=>typeof D==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(D)=>D==="true",stringify:e8},{identify:Yg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(D,u,{intAsBigInt:r})=>r?BigInt(D):parseInt(D,10),stringify:({value:D})=>Yg(D)?D.toString():JSON.stringify(D)},{identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(D)=>parseFloat(D),stringify:e8}],uM={default:!0,tag:"",test:/^/,resolve(D,u){return u(`Unresolved plain scalar ${JSON.stringify(D)}`),D}},rM=[aY.map,eY.seq].concat(DM,uM);AM.schema=rM});var H6=Q(($M)=>{var s1=yA("buffer"),C6=ID(),FM=q1(),wM={identify:(D)=>D instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(D,u){if(typeof s1.Buffer==="function")return s1.Buffer.from(D,"base64");else if(typeof atob==="function"){let r=atob(D.replace(/[\n\r]/g,"")),A=new Uint8Array(r.length);for(let f=0;f<r.length;++f)A[f]=r.charCodeAt(f);return A}else return u("This environment does not support reading binary tags; either Buffer or atob is required"),D},stringify({comment:D,type:u,value:r},A,f,w){if(!r)return"";let F=r,E;if(typeof s1.Buffer==="function")E=F instanceof s1.Buffer?F.toString("base64"):s1.Buffer.from(F.buffer).toString("base64");else if(typeof btoa==="function"){let $="";for(let g=0;g<F.length;++g)$+=String.fromCharCode(F[g]);E=btoa($)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(u??(u=C6.Scalar.BLOCK_LITERAL),u!==C6.Scalar.QUOTE_DOUBLE){let $=Math.max(A.options.lineWidth-A.indent.length,A.options.minContentWidth),g=Math.ceil(E.length/$),R=Array(g);for(let S=0,B=0;S<g;++S,B+=$)R[S]=E.substr(B,$);E=R.join(u===C6.Scalar.BLOCK_LITERAL?`
61
- `:" ")}return FM.stringifyString({comment:D,type:u,value:E},A,f,w)}};$M.binary=wM});var uf=Q((SM)=>{var Df=AD(),n6=w0(),gM=ID(),_M=g0();function Og(D,u){if(Df.isSeq(D))for(let r=0;r<D.items.length;++r){let A=D.items[r];if(Df.isPair(A))continue;else if(Df.isMap(A)){if(A.items.length>1)u("Each pair must have its own sequence indicator");let f=A.items[0]||new n6.Pair(new gM.Scalar(null));if(A.commentBefore)f.key.commentBefore=f.key.commentBefore?`${A.commentBefore}
53
+ `)Y="";if(X+=Y+q,r.inFlow){if(s&&A)A()}else if(k&&!s)X+=sA.lineComment(X,r.indent,g(k));else if(J&&f)f();return X}vi.stringifyPair=Ti});var _6=L((li)=>{var Ug=p1("process");function oi(D,...u){if(D==="debug")console.log(...u)}function di(D,u){if(D==="debug"||D==="warn")if(typeof Ug.emitWarning==="function")Ug.emitWarning(u);else console.warn(u)}li.debug=oi;li.warn=di});var c8=L((pi)=>{var zA=AD(),Yg=VD(),l8="<<",y8={identify:(D)=>D===l8||typeof D==="symbol"&&D.description===l8,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Yg.Scalar(Symbol(l8)),{addToJSMap:Mg}),stringify:()=>l8},ti=(D,u)=>(y8.identify(u)||zA.isScalar(u)&&(!u.type||u.type===Yg.Scalar.PLAIN)&&y8.identify(u.value))&&D?.doc.schema.tags.some((r)=>r.tag===y8.tag&&r.default);function Mg(D,u,r){if(r=D&&zA.isAlias(r)?r.resolve(D.doc):r,zA.isSeq(r))for(let A of r.items)R6(D,u,A);else if(Array.isArray(r))for(let A of r)R6(D,u,A);else R6(D,u,r)}function R6(D,u,r){let A=D&&zA.isAlias(r)?r.resolve(D.doc):r;if(!zA.isMap(A))throw Error("Merge sources must be maps or map aliases");let f=A.toJSON(null,D,Map);for(let[w,F]of f)if(u instanceof Map){if(!u.has(w))u.set(w,F)}else if(u instanceof Set)u.add(w);else if(!Object.prototype.hasOwnProperty.call(u,w))Object.defineProperty(u,w,{value:F,writable:!0,enumerable:!0,configurable:!0});return u}pi.addMergeToJSMap=Mg;pi.isMergeKey=ti;pi.merge=y8});var B6=L((AU)=>{var ei=_6(),Og=c8(),DU=bA(),Pg=AD(),n6=A0();function uU(D,u,{key:r,value:A}){if(Pg.isNode(r)&&r.addToJSMap)r.addToJSMap(D,u,A);else if(Og.isMergeKey(D,r))Og.addMergeToJSMap(D,u,A);else{let f=n6.toJS(r,"",D);if(u instanceof Map)u.set(f,n6.toJS(A,f,D));else if(u instanceof Set)u.add(f);else{let w=rU(r,f,D),F=n6.toJS(A,w,D);if(w in u)Object.defineProperty(u,w,{value:F,writable:!0,enumerable:!0,configurable:!0});else u[w]=F}}return u}function rU(D,u,r){if(u===null)return"";if(typeof u!=="object")return String(u);if(Pg.isNode(D)&&r?.doc){let A=DU.createStringifyContext(r.doc,{});A.anchors=new Set;for(let w of r.anchors.keys())A.anchors.add(w.anchor);A.inFlow=!0,A.inStringifyKey=!0;let f=D.toString(A);if(!r.mapKeyWarned){let w=JSON.stringify(f);if(w.length>40)w=w.substring(0,36)+'..."';ei.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${w}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return f}return JSON.stringify(u)}AU.addPairToJSMap=uU});var w0=L((EU)=>{var kg=NA(),FU=ig(),wU=B6(),t8=AD();function $U(D,u,r){let A=kg.createNode(D,void 0,r),f=kg.createNode(u,void 0,r);return new p8(A,f)}class p8{constructor(D,u=null){Object.defineProperty(this,t8.NODE_TYPE,{value:t8.PAIR}),this.key=D,this.value=u}clone(D){let{key:u,value:r}=this;if(t8.isNode(u))u=u.clone(D);if(t8.isNode(r))r=r.clone(D);return new p8(u,r)}toJSON(D,u){let r=u?.mapAsMap?new Map:{};return wU.addPairToJSMap(u,r,this)}toString(D,u,r){return D?.doc?FU.stringifyPair(this,D,u,r):JSON.stringify(this)}}EU.Pair=p8;EU.createPair=$U});var W6=L((BU)=>{var q0=AD(),Ig=bA(),x8=QA();function _U(D,u,r){return(u.inFlow??D.flow?nU:RU)(D,u,r)}function RU({comment:D,items:u},r,{blockItemPrefix:A,flowChars:f,itemIndent:w,onChompKeep:F,onComment:E}){let{indent:$,options:{commentString:g}}=r,_=Object.assign({},r,{indent:w,type:null}),R=!1,n=[];for(let C=0;C<u.length;++C){let J=u[C],X=null;if(q0.isNode(J)){if(!R&&J.spaceBefore)n.push("");if(m8(r,n,J.commentBefore,R),J.comment)X=J.comment}else if(q0.isPair(J)){let P=q0.isNode(J.key)?J.key:null;if(P){if(!R&&P.spaceBefore)n.push("");m8(r,n,P.commentBefore,R)}}R=!1;let M=Ig.stringify(J,_,()=>X=null,()=>R=!0);if(X)M+=x8.lineComment(M,w,g(X));if(R&&X)R=!1;n.push(A+M)}let B;if(n.length===0)B=f.start+f.end;else{B=n[0];for(let C=1;C<n.length;++C){let J=n[C];B+=J?`
54
+ ${$}${J}`:`
55
+ `}}if(D){if(B+=`
56
+ `+x8.indentComment(g(D),$),E)E()}else if(R&&F)F();return B}function nU({items:D},u,{flowChars:r,itemIndent:A}){let{indent:f,indentStep:w,flowCollectionPadding:F,options:{commentString:E}}=u;A+=w;let $=Object.assign({},u,{indent:A,inFlow:!0,type:null}),g=!1,_=0,R=[];for(let C=0;C<D.length;++C){let J=D[C],X=null;if(q0.isNode(J)){if(J.spaceBefore)R.push("");if(m8(u,R,J.commentBefore,!1),J.comment)X=J.comment}else if(q0.isPair(J)){let P=q0.isNode(J.key)?J.key:null;if(P){if(P.spaceBefore)R.push("");if(m8(u,R,P.commentBefore,!1),P.comment)g=!0}let k=q0.isNode(J.value)?J.value:null;if(k){if(k.comment)X=k.comment;if(k.commentBefore)g=!0}else if(J.value==null&&P?.comment)X=P.comment}if(X)g=!0;let M=Ig.stringify(J,$,()=>X=null);if(g||(g=R.length>_||M.includes(`
57
+ `)),C<D.length-1)M+=",";else if(u.options.trailingComma){if(u.options.lineWidth>0)g||(g=R.reduce((P,k)=>P+k.length+2,2)+(M.length+2)>u.options.lineWidth);if(g)M+=","}if(X)M+=x8.lineComment(M,A,E(X));R.push(M),_=R.length}let{start:n,end:B}=r;if(R.length===0)return n+B;else{if(!g){let C=R.reduce((J,X)=>J+X.length+2,2);g=u.options.lineWidth>0&&C>u.options.lineWidth}if(g){let C=n;for(let J of R)C+=J?`
58
+ ${w}${f}${J}`:`
59
+ `;return`${C}
60
+ ${f}${B}`}else return`${n}${F}${R.join(" ")}${F}${B}`}}function m8({indent:D,options:{commentString:u}},r,A,f){if(A&&f)A=A.replace(/^\n+/,"");if(A){let w=x8.indentComment(u(A),D);r.push(w.trimStart())}}BU.stringifyCollection=_U});var E0=L((XU)=>{var JU=W6(),GU=B6(),CU=v8(),$0=AD(),a8=w0(),HU=VD();function jA(D,u){let r=$0.isScalar(u)?u.value:u;for(let A of D)if($0.isPair(A)){if(A.key===u||A.key===r)return A;if($0.isScalar(A.key)&&A.key.value===r)return A}return}class Vg extends CU.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(D){super($0.MAP,D);this.items=[]}static from(D,u,r){let{keepUndefined:A,replacer:f}=r,w=new this(D),F=(E,$)=>{if(typeof f==="function")$=f.call(u,E,$);else if(Array.isArray(f)&&!f.includes(E))return;if($!==void 0||A)w.items.push(a8.createPair(E,$,r))};if(u instanceof Map)for(let[E,$]of u)F(E,$);else if(u&&typeof u==="object")for(let E of Object.keys(u))F(E,u[E]);if(typeof D.sortMapEntries==="function")w.items.sort(D.sortMapEntries);return w}add(D,u){let r;if($0.isPair(D))r=D;else if(!D||typeof D!=="object"||!("key"in D))r=new a8.Pair(D,D?.value);else r=new a8.Pair(D.key,D.value);let A=jA(this.items,r.key),f=this.schema?.sortMapEntries;if(A){if(!u)throw Error(`Key ${r.key} already set`);if($0.isScalar(A.value)&&HU.isScalarValue(r.value))A.value.value=r.value;else A.value=r.value}else if(f){let w=this.items.findIndex((F)=>f(r,F)<0);if(w===-1)this.items.push(r);else this.items.splice(w,0,r)}else this.items.push(r)}delete(D){let u=jA(this.items,D);if(!u)return!1;return this.items.splice(this.items.indexOf(u),1).length>0}get(D,u){let A=jA(this.items,D)?.value;return(!u&&$0.isScalar(A)?A.value:A)??void 0}has(D){return!!jA(this.items,D)}set(D,u){this.add(new a8.Pair(D,u),!0)}toJSON(D,u,r){let A=r?new r:u?.mapAsMap?new Map:{};if(u?.onCreate)u.onCreate(A);for(let f of this.items)GU.addPairToJSMap(u,A,f);return A}toString(D,u,r){if(!D)return JSON.stringify(this);for(let A of this.items)if(!$0.isPair(A))throw Error(`Map items must all be pairs; found ${JSON.stringify(A)} instead`);if(!D.allNullValues&&this.hasAllNullValues(!1))D=Object.assign({},D,{allNullValues:!0});return JU.stringifyCollection(this,D,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:D.indent||"",onChompKeep:r,onComment:u})}}XU.YAMLMap=Vg;XU.findPair=jA});var I2=L((OU)=>{var YU=AD(),Kg=E0(),MU={collection:"map",default:!0,nodeClass:Kg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(D,u){if(!YU.isMap(D))u("Expected a mapping for this tag");return D},createNode:(D,u,r)=>Kg.YAMLMap.from(D,u,r)};OU.map=MU});var g0=L((NU)=>{var kU=NA(),IU=W6(),VU=v8(),Df=AD(),KU=VD(),hU=A0();class hg extends VU.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(D){super(Df.SEQ,D);this.items=[]}add(D){this.items.push(D)}delete(D){let u=e8(D);if(typeof u!=="number")return!1;return this.items.splice(u,1).length>0}get(D,u){let r=e8(D);if(typeof r!=="number")return;let A=this.items[r];return!u&&Df.isScalar(A)?A.value:A}has(D){let u=e8(D);return typeof u==="number"&&u<this.items.length}set(D,u){let r=e8(D);if(typeof r!=="number")throw Error(`Expected a valid index, not ${D}.`);let A=this.items[r];if(Df.isScalar(A)&&KU.isScalarValue(u))A.value=u;else this.items[r]=u}toJSON(D,u){let r=[];if(u?.onCreate)u.onCreate(r);let A=0;for(let f of this.items)r.push(hU.toJS(f,String(A++),u));return r}toString(D,u,r){if(!D)return JSON.stringify(this);return IU.stringifyCollection(this,D,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(D.indent||"")+" ",onChompKeep:r,onComment:u})}static from(D,u,r){let{replacer:A}=r,f=new this(D);if(u&&Symbol.iterator in Object(u)){let w=0;for(let F of u){if(typeof A==="function"){let E=u instanceof Set?F:String(w++);F=A.call(u,E,F)}f.items.push(kU.createNode(F,void 0,r))}}return f}}function e8(D){let u=Df.isScalar(D)?D.value:D;if(u&&typeof u==="string")u=Number(u);return typeof u==="number"&&Number.isInteger(u)&&u>=0?u:null}NU.YAMLSeq=hg});var V2=L((bU)=>{var LU=AD(),Ng=g0(),qU={collection:"seq",default:!0,nodeClass:Ng.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(D,u){if(!LU.isSeq(D))u("Expected a sequence for this tag");return D},createNode:(D,u,r)=>Ng.YAMLSeq.from(D,u,r)};bU.seq=qU});var TA=L((TU)=>{var zU=qA(),jU={identify:(D)=>typeof D==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(D)=>D,stringify(D,u,r,A){return u=Object.assign({actualString:!0},u),zU.stringifyString(D,u,r,A)}};TU.string=jU});var uf=L((ZU)=>{var Qg=VD(),Lg={identify:(D)=>D==null,createNode:()=>new Qg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Qg.Scalar(null),stringify:({source:D},u)=>typeof D==="string"&&Lg.test.test(D)?D:u.options.nullStr};ZU.nullTag=Lg});var J6=L((lU)=>{var dU=VD(),qg={identify:(D)=>typeof D==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(D)=>new dU.Scalar(D[0]==="t"||D[0]==="T"),stringify({source:D,value:u},r){if(D&&qg.test.test(D)){let A=D[0]==="t"||D[0]==="T";if(u===A)return D}return u?r.options.trueStr:r.options.falseStr}};lU.boolTag=qg});var K2=L((tU)=>{function cU({format:D,minFractionDigits:u,tag:r,value:A}){if(typeof A==="bigint")return String(A);let f=typeof A==="number"?A:Number(A);if(!isFinite(f))return isNaN(f)?".nan":f<0?"-.inf":".inf";let w=Object.is(A,-0)?"-0":JSON.stringify(A);if(!D&&u&&(!r||r==="tag:yaml.org,2002:float")&&/^\d/.test(w)){let F=w.indexOf(".");if(F<0)F=w.length,w+=".";let E=u-(w.length-F-1);while(E-- >0)w+="0"}return w}tU.stringifyNumber=cU});var C6=L((DY)=>{var xU=VD(),G6=K2(),mU={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(D)=>D.slice(-3).toLowerCase()==="nan"?NaN:D[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:G6.stringifyNumber},aU={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(D)=>parseFloat(D),stringify(D){let u=Number(D.value);return isFinite(u)?u.toExponential():G6.stringifyNumber(D)}},eU={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(D){let u=new xU.Scalar(parseFloat(D)),r=D.indexOf(".");if(r!==-1&&D[D.length-1]==="0")u.minFractionDigits=D.length-r-1;return u},stringify:G6.stringifyNumber};DY.float=eU;DY.floatExp=aU;DY.floatNaN=mU});var X6=L(($Y)=>{var bg=K2(),rf=(D)=>typeof D==="bigint"||Number.isInteger(D),H6=(D,u,r,{intAsBigInt:A})=>A?BigInt(D):parseInt(D.substring(u),r);function sg(D,u,r){let{value:A}=D;if(rf(A)&&A>=0)return r+A.toString(u);return bg.stringifyNumber(D)}var fY={identify:(D)=>rf(D)&&D>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(D,u,r)=>H6(D,2,8,r),stringify:(D)=>sg(D,8,"0o")},FY={identify:rf,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(D,u,r)=>H6(D,0,10,r),stringify:bg.stringifyNumber},wY={identify:(D)=>rf(D)&&D>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(D,u,r)=>H6(D,2,16,r),stringify:(D)=>sg(D,16,"0x")};$Y.int=FY;$Y.intHex=wY;$Y.intOct=fY});var zg=L((GY)=>{var _Y=I2(),RY=uf(),nY=V2(),BY=TA(),WY=J6(),i6=C6(),U6=X6(),JY=[_Y.map,nY.seq,BY.string,RY.nullTag,WY.boolTag,U6.intOct,U6.int,U6.intHex,i6.floatNaN,i6.floatExp,i6.float];GY.schema=JY});var Tg=L((OY)=>{var HY=VD(),XY=I2(),iY=V2();function jg(D){return typeof D==="bigint"||Number.isInteger(D)}var Af=({value:D})=>JSON.stringify(D),UY=[{identify:(D)=>typeof D==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(D)=>D,stringify:Af},{identify:(D)=>D==null,createNode:()=>new HY.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Af},{identify:(D)=>typeof D==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(D)=>D==="true",stringify:Af},{identify:jg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(D,u,{intAsBigInt:r})=>r?BigInt(D):parseInt(D,10),stringify:({value:D})=>jg(D)?D.toString():JSON.stringify(D)},{identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(D)=>parseFloat(D),stringify:Af}],YY={default:!0,tag:"",test:/^/,resolve(D,u){return u(`Unresolved plain scalar ${JSON.stringify(D)}`),D}},MY=[XY.map,iY.seq].concat(UY,YY);OY.schema=MY});var M6=L((VY)=>{var vA=p1("buffer"),Y6=VD(),kY=qA(),IY={identify:(D)=>D instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(D,u){if(typeof vA.Buffer==="function")return vA.Buffer.from(D,"base64");else if(typeof atob==="function"){let r=atob(D.replace(/[\n\r]/g,"")),A=new Uint8Array(r.length);for(let f=0;f<r.length;++f)A[f]=r.charCodeAt(f);return A}else return u("This environment does not support reading binary tags; either Buffer or atob is required"),D},stringify({comment:D,type:u,value:r},A,f,w){if(!r)return"";let F=r,E;if(typeof vA.Buffer==="function")E=F instanceof vA.Buffer?F.toString("base64"):vA.Buffer.from(F.buffer).toString("base64");else if(typeof btoa==="function"){let $="";for(let g=0;g<F.length;++g)$+=String.fromCharCode(F[g]);E=btoa($)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(u??(u=Y6.Scalar.BLOCK_LITERAL),u!==Y6.Scalar.QUOTE_DOUBLE){let $=Math.max(A.options.lineWidth-A.indent.length,A.options.minContentWidth),g=Math.ceil(E.length/$),_=Array(g);for(let R=0,n=0;R<g;++R,n+=$)_[R]=E.substr(n,$);E=_.join(u===Y6.Scalar.BLOCK_LITERAL?`
61
+ `:" ")}return kY.stringifyString({comment:D,type:u,value:E},A,f,w)}};VY.binary=IY});var Ff=L((LY)=>{var ff=AD(),O6=w0(),hY=VD(),NY=g0();function vg(D,u){if(ff.isSeq(D))for(let r=0;r<D.items.length;++r){let A=D.items[r];if(ff.isPair(A))continue;else if(ff.isMap(A)){if(A.items.length>1)u("Each pair must have its own sequence indicator");let f=A.items[0]||new O6.Pair(new hY.Scalar(null));if(A.commentBefore)f.key.commentBefore=f.key.commentBefore?`${A.commentBefore}
62
62
  ${f.key.commentBefore}`:A.commentBefore;if(A.comment){let w=f.value??f.key;w.comment=w.comment?`${A.comment}
63
- ${w.comment}`:A.comment}A=f}D.items[r]=Df.isPair(A)?A:new n6.Pair(A)}else u("Expected a sequence for this tag");return D}function Pg(D,u,r){let{replacer:A}=r,f=new _M.YAMLSeq(D);f.tag="tag:yaml.org,2002:pairs";let w=0;if(u&&Symbol.iterator in Object(u))for(let F of u){if(typeof A==="function")F=A.call(u,String(w++),F);let E,$;if(Array.isArray(F))if(F.length===2)E=F[0],$=F[1];else throw TypeError(`Expected [key, value] tuple: ${F}`);else if(F&&F instanceof Object){let g=Object.keys(F);if(g.length===1)E=g[0],$=F[E];else throw TypeError(`Expected tuple with one key, not ${g.length} keys`)}else E=F;f.items.push(n6.createPair(E,$,r))}return f}var RM={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Og,createNode:Pg};SM.createPairs=Pg;SM.pairs=RM;SM.resolvePairs=Og});var X6=Q((HM)=>{var ig=AD(),U6=A0(),Z1=E0(),GM=g0(),kg=uf();class b0 extends GM.YAMLSeq{constructor(){super();this.add=Z1.YAMLMap.prototype.add.bind(this),this.delete=Z1.YAMLMap.prototype.delete.bind(this),this.get=Z1.YAMLMap.prototype.get.bind(this),this.has=Z1.YAMLMap.prototype.has.bind(this),this.set=Z1.YAMLMap.prototype.set.bind(this),this.tag=b0.tag}toJSON(D,u){if(!u)return super.toJSON(D);let r=new Map;if(u?.onCreate)u.onCreate(r);for(let A of this.items){let f,w;if(ig.isPair(A))f=U6.toJS(A.key,"",u),w=U6.toJS(A.value,f,u);else f=U6.toJS(A,"",u);if(r.has(f))throw Error("Ordered maps must not include duplicate keys");r.set(f,w)}return r}static from(D,u,r){let A=kg.createPairs(D,u,r),f=new this;return f.items=A.items,f}}b0.tag="tag:yaml.org,2002:omap";var CM={collection:"seq",identify:(D)=>D instanceof Map,nodeClass:b0,default:!1,tag:"tag:yaml.org,2002:omap",resolve(D,u){let r=kg.resolvePairs(D,u),A=[];for(let{key:f}of r.items)if(ig.isScalar(f))if(A.includes(f.value))u(`Ordered maps must not include duplicate keys: ${f.value}`);else A.push(f.value);return Object.assign(new b0,r)},createNode:(D,u,r)=>b0.from(D,u,r)};HM.YAMLOMap=b0;HM.omap=CM});var Ng=Q((XM)=>{var Ig=ID();function Vg({value:D,source:u},r){if(u&&(D?Kg:hg).test.test(u))return u;return D?r.options.trueStr:r.options.falseStr}var Kg={identify:(D)=>D===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ig.Scalar(!0),stringify:Vg},hg={identify:(D)=>D===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ig.Scalar(!1),stringify:Vg};XM.falseTag=hg;XM.trueTag=Kg});var Qg=Q((IM)=>{var OM=ID(),Y6=V2(),PM={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(D)=>D.slice(-3).toLowerCase()==="nan"?NaN:D[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Y6.stringifyNumber},iM={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(D)=>parseFloat(D.replace(/_/g,"")),stringify(D){let u=Number(D.value);return isFinite(u)?u.toExponential():Y6.stringifyNumber(D)}},kM={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(D){let u=new OM.Scalar(parseFloat(D.replace(/_/g,""))),r=D.indexOf(".");if(r!==-1){let A=D.substring(r+1).replace(/_/g,"");if(A[A.length-1]==="0")u.minFractionDigits=A.length}return u},stringify:Y6.stringifyNumber};IM.float=kM;IM.floatExp=iM;IM.floatNaN=PM});var qg=Q((bM)=>{var Lg=V2(),o1=(D)=>typeof D==="bigint"||Number.isInteger(D);function rf(D,u,r,{intAsBigInt:A}){let f=D[0];if(f==="-"||f==="+")u+=1;if(D=D.substring(u).replace(/_/g,""),A){switch(r){case 2:D=`0b${D}`;break;case 8:D=`0o${D}`;break;case 16:D=`0x${D}`;break}let F=BigInt(D);return f==="-"?BigInt(-1)*F:F}let w=parseInt(D,r);return f==="-"?-1*w:w}function M6(D,u,r){let{value:A}=D;if(o1(A)){let f=A.toString(u);return A<0?"-"+r+f.substr(1):r+f}return Lg.stringifyNumber(D)}var NM={identify:o1,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(D,u,r)=>rf(D,2,2,r),stringify:(D)=>M6(D,2,"0b")},QM={identify:o1,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(D,u,r)=>rf(D,1,8,r),stringify:(D)=>M6(D,8,"0")},LM={identify:o1,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(D,u,r)=>rf(D,0,10,r),stringify:Lg.stringifyNumber},qM={identify:o1,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(D,u,r)=>rf(D,2,16,r),stringify:(D)=>M6(D,16,"0x")};bM.int=LM;bM.intBin=NM;bM.intHex=qM;bM.intOct=QM});var O6=Q((ZM)=>{var Ff=AD(),Af=w0(),ff=E0();class z0 extends ff.YAMLMap{constructor(D){super(D);this.tag=z0.tag}add(D){let u;if(Ff.isPair(D))u=D;else if(D&&typeof D==="object"&&"key"in D&&"value"in D&&D.value===null)u=new Af.Pair(D.key,null);else u=new Af.Pair(D,null);if(!ff.findPair(this.items,u.key))this.items.push(u)}get(D,u){let r=ff.findPair(this.items,D);return!u&&Ff.isPair(r)?Ff.isScalar(r.key)?r.key.value:r.key:r}set(D,u){if(typeof u!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof u}`);let r=ff.findPair(this.items,D);if(r&&!u)this.items.splice(this.items.indexOf(r),1);else if(!r&&u)this.items.push(new Af.Pair(D))}toJSON(D,u){return super.toJSON(D,u,Set)}toString(D,u,r){if(!D)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},D,{allNullValues:!0}),u,r);else throw Error("Set items must all have null values")}static from(D,u,r){let{replacer:A}=r,f=new this(D);if(u&&Symbol.iterator in Object(u))for(let w of u){if(typeof A==="function")w=A.call(u,w,w);f.items.push(Af.createPair(w,null,r))}return f}}z0.tag="tag:yaml.org,2002:set";var sM={collection:"map",identify:(D)=>D instanceof Set,nodeClass:z0,default:!1,tag:"tag:yaml.org,2002:set",createNode:(D,u,r)=>z0.from(D,u,r),resolve(D,u){if(Ff.isMap(D))if(D.hasAllNullValues(!0))return Object.assign(new z0,D);else u("Set items must all have null values");else u("Expected a mapping for this tag");return D}};ZM.YAMLSet=z0;ZM.set=sM});var i6=Q((tM)=>{var yM=V2();function P6(D,u){let r=D[0],A=r==="-"||r==="+"?D.substring(1):D,f=(F)=>u?BigInt(F):Number(F),w=A.replace(/_/g,"").split(":").reduce((F,E)=>F*f(60)+f(E),f(0));return r==="-"?f(-1)*w:w}function bg(D){let{value:u}=D,r=(F)=>F;if(typeof u==="bigint")r=(F)=>BigInt(F);else if(isNaN(u)||!isFinite(u))return yM.stringifyNumber(D);let A="";if(u<0)A="-",u*=r(-1);let f=r(60),w=[u%f];if(u<60)w.unshift(0);else if(u=(u-w[0])/f,w.unshift(u%f),u>=60)u=(u-w[0])/f,w.unshift(u);return A+w.map((F)=>String(F).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var lM={identify:(D)=>typeof D==="bigint"||Number.isInteger(D),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(D,u,{intAsBigInt:r})=>P6(D,r),stringify:bg},cM={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(D)=>P6(D,!1),stringify:bg},zg={identify:(D)=>D instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(D){let u=D.match(zg.test);if(!u)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,A,f,w,F,E]=u.map(Number),$=u[7]?Number((u[7]+"00").substr(1,3)):0,g=Date.UTC(r,A-1,f,w||0,F||0,E||0,$),R=u[8];if(R&&R!=="Z"){let S=P6(R,!1);if(Math.abs(S)<30)S*=60;g-=60000*S}return new Date(g)},stringify:({value:D})=>D?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};tM.floatTime=cM;tM.intTime=lM;tM.timestamp=zg});var Tg=Q((EO)=>{var aM=k2(),eM=p8(),DO=I2(),uO=v1(),rO=H6(),jg=Ng(),k6=Qg(),wf=qg(),AO=o8(),fO=X6(),FO=uf(),wO=O6(),I6=i6(),$O=[aM.map,DO.seq,uO.string,eM.nullTag,jg.trueTag,jg.falseTag,wf.intBin,wf.intOct,wf.int,wf.intHex,k6.floatNaN,k6.floatExp,k6.float,rO.binary,AO.merge,fO.omap,FO.pairs,wO.set,I6.intTime,I6.floatTime,I6.timestamp];EO.schema=$O});var xg=Q((CO)=>{var og=k2(),_O=p8(),dg=I2(),RO=v1(),SO=_6(),V6=S6(),K6=J6(),BO=Xg(),JO=Mg(),yg=H6(),d1=o8(),lg=X6(),cg=uf(),vg=Tg(),tg=O6(),$f=i6(),sg=new Map([["core",BO.schema],["failsafe",[og.map,dg.seq,RO.string]],["json",JO.schema],["yaml11",vg.schema],["yaml-1.1",vg.schema]]),Zg={binary:yg.binary,bool:SO.boolTag,float:V6.float,floatExp:V6.floatExp,floatNaN:V6.floatNaN,floatTime:$f.floatTime,int:K6.int,intHex:K6.intHex,intOct:K6.intOct,intTime:$f.intTime,map:og.map,merge:d1.merge,null:_O.nullTag,omap:lg.omap,pairs:cg.pairs,seq:dg.seq,set:tg.set,timestamp:$f.timestamp},WO={"tag:yaml.org,2002:binary":yg.binary,"tag:yaml.org,2002:merge":d1.merge,"tag:yaml.org,2002:omap":lg.omap,"tag:yaml.org,2002:pairs":cg.pairs,"tag:yaml.org,2002:set":tg.set,"tag:yaml.org,2002:timestamp":$f.timestamp};function GO(D,u,r){let A=sg.get(u);if(A&&!D)return r&&!A.includes(d1.merge)?A.concat(d1.merge):A.slice();let f=A;if(!f)if(Array.isArray(D))f=[];else{let w=Array.from(sg.keys()).filter((F)=>F!=="yaml11").map((F)=>JSON.stringify(F)).join(", ");throw Error(`Unknown schema "${u}"; use one of ${w} or define customTags array`)}if(Array.isArray(D))for(let w of D)f=f.concat(w);else if(typeof D==="function")f=D(f.slice());if(r)f=f.concat(d1.merge);return f.reduce((w,F)=>{let E=typeof F==="string"?Zg[F]:F;if(!E){let $=JSON.stringify(F),g=Object.keys(Zg).map((R)=>JSON.stringify(R)).join(", ");throw Error(`Unknown custom tag ${$}; use one of ${g}`)}if(!w.includes(E))w.push(E);return w},[])}CO.coreKnownTags=WO;CO.getTags=GO});var Q6=Q((OO)=>{var h6=AD(),UO=k2(),XO=I2(),YO=v1(),Ef=xg(),MO=(D,u)=>D.key<u.key?-1:D.key>u.key?1:0;class N6{constructor({compat:D,customTags:u,merge:r,resolveKnownTags:A,schema:f,sortMapEntries:w,toStringDefaults:F}){this.compat=Array.isArray(D)?Ef.getTags(D,"compat"):D?Ef.getTags(null,D):null,this.name=typeof f==="string"&&f||"core",this.knownTags=A?Ef.coreKnownTags:{},this.tags=Ef.getTags(u,this.name,r),this.toStringOptions=F??null,Object.defineProperty(this,h6.MAP,{value:UO.map}),Object.defineProperty(this,h6.SCALAR,{value:YO.string}),Object.defineProperty(this,h6.SEQ,{value:XO.seq}),this.sortMapEntries=typeof w==="function"?w:w===!0?MO:null}clone(){let D=Object.create(N6.prototype,Object.getOwnPropertyDescriptors(this));return D.tags=this.tags.slice(),D}}OO.Schema=N6});var mg=Q((IO)=>{var iO=AD(),L6=b1(),y1=Q1();function kO(D,u){let r=[],A=u.directives===!0;if(u.directives!==!1&&D.directives){let $=D.directives.toString(D);if($)r.push($),A=!0;else if(D.directives.docStart)A=!0}if(A)r.push("---");let f=L6.createStringifyContext(D,u),{commentString:w}=f.options;if(D.commentBefore){if(r.length!==1)r.unshift("");let $=w(D.commentBefore);r.unshift(y1.indentComment($,""))}let F=!1,E=null;if(D.contents){if(iO.isNode(D.contents)){if(D.contents.spaceBefore&&A)r.push("");if(D.contents.commentBefore){let R=w(D.contents.commentBefore);r.push(y1.indentComment(R,""))}f.forceBlockIndent=!!D.comment,E=D.contents.comment}let $=E?void 0:()=>F=!0,g=L6.stringify(D.contents,f,()=>E=null,$);if(E)g+=y1.lineComment(g,"",w(E));if((g[0]==="|"||g[0]===">")&&r[r.length-1]==="---")r[r.length-1]=`--- ${g}`;else r.push(g)}else r.push(L6.stringify(D.contents,f));if(D.directives?.docEnd)if(D.comment){let $=w(D.comment);if($.includes(`
64
- `))r.push("..."),r.push(y1.indentComment($,""));else r.push(`... ${$}`)}else r.push("...");else{let $=D.comment;if($&&F)$=$.replace(/^\n+/,"");if($){if((!F||E)&&r[r.length-1]!=="")r.push("");r.push(y1.indentComment(w($),""))}}return r.join(`
63
+ ${w.comment}`:A.comment}A=f}D.items[r]=ff.isPair(A)?A:new O6.Pair(A)}else u("Expected a sequence for this tag");return D}function Zg(D,u,r){let{replacer:A}=r,f=new NY.YAMLSeq(D);f.tag="tag:yaml.org,2002:pairs";let w=0;if(u&&Symbol.iterator in Object(u))for(let F of u){if(typeof A==="function")F=A.call(u,String(w++),F);let E,$;if(Array.isArray(F))if(F.length===2)E=F[0],$=F[1];else throw TypeError(`Expected [key, value] tuple: ${F}`);else if(F&&F instanceof Object){let g=Object.keys(F);if(g.length===1)E=g[0],$=F[E];else throw TypeError(`Expected tuple with one key, not ${g.length} keys`)}else E=F;f.items.push(O6.createPair(E,$,r))}return f}var QY={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vg,createNode:Zg};LY.createPairs=Zg;LY.pairs=QY;LY.resolvePairs=vg});var k6=L((TY)=>{var og=AD(),P6=A0(),ZA=E0(),zY=g0(),dg=Ff();class b0 extends zY.YAMLSeq{constructor(){super();this.add=ZA.YAMLMap.prototype.add.bind(this),this.delete=ZA.YAMLMap.prototype.delete.bind(this),this.get=ZA.YAMLMap.prototype.get.bind(this),this.has=ZA.YAMLMap.prototype.has.bind(this),this.set=ZA.YAMLMap.prototype.set.bind(this),this.tag=b0.tag}toJSON(D,u){if(!u)return super.toJSON(D);let r=new Map;if(u?.onCreate)u.onCreate(r);for(let A of this.items){let f,w;if(og.isPair(A))f=P6.toJS(A.key,"",u),w=P6.toJS(A.value,f,u);else f=P6.toJS(A,"",u);if(r.has(f))throw Error("Ordered maps must not include duplicate keys");r.set(f,w)}return r}static from(D,u,r){let A=dg.createPairs(D,u,r),f=new this;return f.items=A.items,f}}b0.tag="tag:yaml.org,2002:omap";var jY={collection:"seq",identify:(D)=>D instanceof Map,nodeClass:b0,default:!1,tag:"tag:yaml.org,2002:omap",resolve(D,u){let r=dg.resolvePairs(D,u),A=[];for(let{key:f}of r.items)if(og.isScalar(f))if(A.includes(f.value))u(`Ordered maps must not include duplicate keys: ${f.value}`);else A.push(f.value);return Object.assign(new b0,r)},createNode:(D,u,r)=>b0.from(D,u,r)};TY.YAMLOMap=b0;TY.omap=jY});var pg=L((oY)=>{var lg=VD();function yg({value:D,source:u},r){if(u&&(D?cg:tg).test.test(u))return u;return D?r.options.trueStr:r.options.falseStr}var cg={identify:(D)=>D===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new lg.Scalar(!0),stringify:yg},tg={identify:(D)=>D===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new lg.Scalar(!1),stringify:yg};oY.falseTag=tg;oY.trueTag=cg});var xg=L((xY)=>{var yY=VD(),I6=K2(),cY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(D)=>D.slice(-3).toLowerCase()==="nan"?NaN:D[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:I6.stringifyNumber},tY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(D)=>parseFloat(D.replace(/_/g,"")),stringify(D){let u=Number(D.value);return isFinite(u)?u.toExponential():I6.stringifyNumber(D)}},pY={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(D){let u=new yY.Scalar(parseFloat(D.replace(/_/g,""))),r=D.indexOf(".");if(r!==-1){let A=D.substring(r+1).replace(/_/g,"");if(A[A.length-1]==="0")u.minFractionDigits=A.length}return u},stringify:I6.stringifyNumber};xY.float=pY;xY.floatExp=tY;xY.floatNaN=cY});var ag=L((fM)=>{var mg=K2(),oA=(D)=>typeof D==="bigint"||Number.isInteger(D);function wf(D,u,r,{intAsBigInt:A}){let f=D[0];if(f==="-"||f==="+")u+=1;if(D=D.substring(u).replace(/_/g,""),A){switch(r){case 2:D=`0b${D}`;break;case 8:D=`0o${D}`;break;case 16:D=`0x${D}`;break}let F=BigInt(D);return f==="-"?BigInt(-1)*F:F}let w=parseInt(D,r);return f==="-"?-1*w:w}function V6(D,u,r){let{value:A}=D;if(oA(A)){let f=A.toString(u);return A<0?"-"+r+f.substr(1):r+f}return mg.stringifyNumber(D)}var DM={identify:oA,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(D,u,r)=>wf(D,2,2,r),stringify:(D)=>V6(D,2,"0b")},uM={identify:oA,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(D,u,r)=>wf(D,1,8,r),stringify:(D)=>V6(D,8,"0")},rM={identify:oA,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(D,u,r)=>wf(D,0,10,r),stringify:mg.stringifyNumber},AM={identify:oA,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(D,u,r)=>wf(D,2,16,r),stringify:(D)=>V6(D,16,"0x")};fM.int=rM;fM.intBin=DM;fM.intHex=AM;fM.intOct=uM});var K6=L((SM)=>{var gf=AD(),$f=w0(),Ef=E0();class s0 extends Ef.YAMLMap{constructor(D){super(D);this.tag=s0.tag}add(D){let u;if(gf.isPair(D))u=D;else if(D&&typeof D==="object"&&"key"in D&&"value"in D&&D.value===null)u=new $f.Pair(D.key,null);else u=new $f.Pair(D,null);if(!Ef.findPair(this.items,u.key))this.items.push(u)}get(D,u){let r=Ef.findPair(this.items,D);return!u&&gf.isPair(r)?gf.isScalar(r.key)?r.key.value:r.key:r}set(D,u){if(typeof u!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof u}`);let r=Ef.findPair(this.items,D);if(r&&!u)this.items.splice(this.items.indexOf(r),1);else if(!r&&u)this.items.push(new $f.Pair(D))}toJSON(D,u){return super.toJSON(D,u,Set)}toString(D,u,r){if(!D)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},D,{allNullValues:!0}),u,r);else throw Error("Set items must all have null values")}static from(D,u,r){let{replacer:A}=r,f=new this(D);if(u&&Symbol.iterator in Object(u))for(let w of u){if(typeof A==="function")w=A.call(u,w,w);f.items.push($f.createPair(w,null,r))}return f}}s0.tag="tag:yaml.org,2002:set";var gM={collection:"map",identify:(D)=>D instanceof Set,nodeClass:s0,default:!1,tag:"tag:yaml.org,2002:set",createNode:(D,u,r)=>s0.from(D,u,r),resolve(D,u){if(gf.isMap(D))if(D.hasAllNullValues(!0))return Object.assign(new s0,D);else u("Set items must all have null values");else u("Expected a mapping for this tag");return D}};SM.YAMLSet=s0;SM.set=gM});var N6=L((JM)=>{var nM=K2();function h6(D,u){let r=D[0],A=r==="-"||r==="+"?D.substring(1):D,f=(F)=>u?BigInt(F):Number(F),w=A.replace(/_/g,"").split(":").reduce((F,E)=>F*f(60)+f(E),f(0));return r==="-"?f(-1)*w:w}function eg(D){let{value:u}=D,r=(F)=>F;if(typeof u==="bigint")r=(F)=>BigInt(F);else if(isNaN(u)||!isFinite(u))return nM.stringifyNumber(D);let A="";if(u<0)A="-",u*=r(-1);let f=r(60),w=[u%f];if(u<60)w.unshift(0);else if(u=(u-w[0])/f,w.unshift(u%f),u>=60)u=(u-w[0])/f,w.unshift(u);return A+w.map((F)=>String(F).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var BM={identify:(D)=>typeof D==="bigint"||Number.isInteger(D),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(D,u,{intAsBigInt:r})=>h6(D,r),stringify:eg},WM={identify:(D)=>typeof D==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(D)=>h6(D,!1),stringify:eg},DS={identify:(D)=>D instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(D){let u=D.match(DS.test);if(!u)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,A,f,w,F,E]=u.map(Number),$=u[7]?Number((u[7]+"00").substr(1,3)):0,g=Date.UTC(r,A-1,f,w||0,F||0,E||0,$),_=u[8];if(_&&_!=="Z"){let R=h6(_,!1);if(Math.abs(R)<30)R*=60;g-=60000*R}return new Date(g)},stringify:({value:D})=>D?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};JM.floatTime=WM;JM.intTime=BM;JM.timestamp=DS});var rS=L((KM)=>{var XM=I2(),iM=uf(),UM=V2(),YM=TA(),MM=M6(),uS=pg(),Q6=xg(),Sf=ag(),OM=c8(),PM=k6(),kM=Ff(),IM=K6(),L6=N6(),VM=[XM.map,UM.seq,YM.string,iM.nullTag,uS.trueTag,uS.falseTag,Sf.intBin,Sf.intOct,Sf.int,Sf.intHex,Q6.floatNaN,Q6.floatExp,Q6.float,MM.binary,OM.merge,PM.omap,kM.pairs,IM.set,L6.intTime,L6.floatTime,L6.timestamp];KM.schema=VM});var RS=L((jM)=>{var wS=I2(),NM=uf(),$S=V2(),QM=TA(),LM=J6(),q6=C6(),b6=X6(),qM=zg(),bM=Tg(),ES=M6(),dA=c8(),gS=k6(),SS=Ff(),AS=rS(),_S=K6(),_f=N6(),fS=new Map([["core",qM.schema],["failsafe",[wS.map,$S.seq,QM.string]],["json",bM.schema],["yaml11",AS.schema],["yaml-1.1",AS.schema]]),FS={binary:ES.binary,bool:LM.boolTag,float:q6.float,floatExp:q6.floatExp,floatNaN:q6.floatNaN,floatTime:_f.floatTime,int:b6.int,intHex:b6.intHex,intOct:b6.intOct,intTime:_f.intTime,map:wS.map,merge:dA.merge,null:NM.nullTag,omap:gS.omap,pairs:SS.pairs,seq:$S.seq,set:_S.set,timestamp:_f.timestamp},sM={"tag:yaml.org,2002:binary":ES.binary,"tag:yaml.org,2002:merge":dA.merge,"tag:yaml.org,2002:omap":gS.omap,"tag:yaml.org,2002:pairs":SS.pairs,"tag:yaml.org,2002:set":_S.set,"tag:yaml.org,2002:timestamp":_f.timestamp};function zM(D,u,r){let A=fS.get(u);if(A&&!D)return r&&!A.includes(dA.merge)?A.concat(dA.merge):A.slice();let f=A;if(!f)if(Array.isArray(D))f=[];else{let w=Array.from(fS.keys()).filter((F)=>F!=="yaml11").map((F)=>JSON.stringify(F)).join(", ");throw Error(`Unknown schema "${u}"; use one of ${w} or define customTags array`)}if(Array.isArray(D))for(let w of D)f=f.concat(w);else if(typeof D==="function")f=D(f.slice());if(r)f=f.concat(dA.merge);return f.reduce((w,F)=>{let E=typeof F==="string"?FS[F]:F;if(!E){let $=JSON.stringify(F),g=Object.keys(FS).map((_)=>JSON.stringify(_)).join(", ");throw Error(`Unknown custom tag ${$}; use one of ${g}`)}if(!w.includes(E))w.push(E);return w},[])}jM.coreKnownTags=sM;jM.getTags=zM});var j6=L((yM)=>{var s6=AD(),ZM=I2(),oM=V2(),dM=TA(),Rf=RS(),lM=(D,u)=>D.key<u.key?-1:D.key>u.key?1:0;class z6{constructor({compat:D,customTags:u,merge:r,resolveKnownTags:A,schema:f,sortMapEntries:w,toStringDefaults:F}){this.compat=Array.isArray(D)?Rf.getTags(D,"compat"):D?Rf.getTags(null,D):null,this.name=typeof f==="string"&&f||"core",this.knownTags=A?Rf.coreKnownTags:{},this.tags=Rf.getTags(u,this.name,r),this.toStringOptions=F??null,Object.defineProperty(this,s6.MAP,{value:ZM.map}),Object.defineProperty(this,s6.SCALAR,{value:dM.string}),Object.defineProperty(this,s6.SEQ,{value:oM.seq}),this.sortMapEntries=typeof w==="function"?w:w===!0?lM:null}clone(){let D=Object.create(z6.prototype,Object.getOwnPropertyDescriptors(this));return D.tags=this.tags.slice(),D}}yM.Schema=z6});var nS=L((xM)=>{var tM=AD(),T6=bA(),lA=QA();function pM(D,u){let r=[],A=u.directives===!0;if(u.directives!==!1&&D.directives){let $=D.directives.toString(D);if($)r.push($),A=!0;else if(D.directives.docStart)A=!0}if(A)r.push("---");let f=T6.createStringifyContext(D,u),{commentString:w}=f.options;if(D.commentBefore){if(r.length!==1)r.unshift("");let $=w(D.commentBefore);r.unshift(lA.indentComment($,""))}let F=!1,E=null;if(D.contents){if(tM.isNode(D.contents)){if(D.contents.spaceBefore&&A)r.push("");if(D.contents.commentBefore){let _=w(D.contents.commentBefore);r.push(lA.indentComment(_,""))}f.forceBlockIndent=!!D.comment,E=D.contents.comment}let $=E?void 0:()=>F=!0,g=T6.stringify(D.contents,f,()=>E=null,$);if(E)g+=lA.lineComment(g,"",w(E));if((g[0]==="|"||g[0]===">")&&r[r.length-1]==="---")r[r.length-1]=`--- ${g}`;else r.push(g)}else r.push(T6.stringify(D.contents,f));if(D.directives?.docEnd)if(D.comment){let $=w(D.comment);if($.includes(`
64
+ `))r.push("..."),r.push(lA.indentComment($,""));else r.push(`... ${$}`)}else r.push("...");else{let $=D.comment;if($&&F)$=$.replace(/^\n+/,"");if($){if((!F||E)&&r[r.length-1]!=="")r.push("");r.push(lA.indentComment(w($),""))}}return r.join(`
65
65
  `)+`
66
- `}IO.stringifyDocument=kO});var l1=Q((zO)=>{var KO=h1(),K2=z8(),Xu=AD(),hO=w0(),NO=A0(),QO=Q6(),LO=mg(),q6=L8(),qO=D6(),bO=N1(),b6=eF();class z6{constructor(D,u,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Xu.NODE_TYPE,{value:Xu.DOC});let A=null;if(typeof u==="function"||Array.isArray(u))A=u;else if(r===void 0&&u)r=u,u=void 0;let f=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=f;let{version:w}=f;if(r?._directives){if(this.directives=r._directives.atDocument(),this.directives.yaml.explicit)w=this.directives.yaml.version}else this.directives=new b6.Directives({version:w});this.setSchema(w,r),this.contents=D===void 0?null:this.createNode(D,A,r)}clone(){let D=Object.create(z6.prototype,{[Xu.NODE_TYPE]:{value:Xu.DOC}});if(D.commentBefore=this.commentBefore,D.comment=this.comment,D.errors=this.errors.slice(),D.warnings=this.warnings.slice(),D.options=Object.assign({},this.options),this.directives)D.directives=this.directives.clone();if(D.schema=this.schema.clone(),D.contents=Xu.isNode(this.contents)?this.contents.clone(D.schema):this.contents,this.range)D.range=this.range.slice();return D}add(D){if(h2(this.contents))this.contents.add(D)}addIn(D,u){if(h2(this.contents))this.contents.addIn(D,u)}createAlias(D,u){if(!D.anchor){let r=q6.anchorNames(this);D.anchor=!u||r.has(u)?q6.findNewAnchor(u||"a",r):u}return new KO.Alias(D.anchor)}createNode(D,u,r){let A=void 0;if(typeof u==="function")D=u.call({"":D},"",D),A=u;else if(Array.isArray(u)){let G=(O)=>typeof O==="number"||O instanceof String||O instanceof Number,U=u.filter(G).map(String);if(U.length>0)u=u.concat(U);A=u}else if(r===void 0&&u)r=u,u=void 0;let{aliasDuplicateObjects:f,anchorPrefix:w,flow:F,keepUndefined:E,onTagObj:$,tag:g}=r??{},{onAnchor:R,setAnchors:S,sourceObjects:B}=q6.createNodeAnchors(this,w||"a"),J={aliasDuplicateObjects:f??!0,keepUndefined:E??!1,onAnchor:R,onTagObj:$,replacer:A,schema:this.schema,sourceObjects:B},H=bO.createNode(D,g,J);if(F&&Xu.isCollection(H))H.flow=!0;return S(),H}createPair(D,u,r={}){let A=this.createNode(D,null,r),f=this.createNode(u,null,r);return new hO.Pair(A,f)}delete(D){return h2(this.contents)?this.contents.delete(D):!1}deleteIn(D){if(K2.isEmptyPath(D)){if(this.contents==null)return!1;return this.contents=null,!0}return h2(this.contents)?this.contents.deleteIn(D):!1}get(D,u){return Xu.isCollection(this.contents)?this.contents.get(D,u):void 0}getIn(D,u){if(K2.isEmptyPath(D))return!u&&Xu.isScalar(this.contents)?this.contents.value:this.contents;return Xu.isCollection(this.contents)?this.contents.getIn(D,u):void 0}has(D){return Xu.isCollection(this.contents)?this.contents.has(D):!1}hasIn(D){if(K2.isEmptyPath(D))return this.contents!==void 0;return Xu.isCollection(this.contents)?this.contents.hasIn(D):!1}set(D,u){if(this.contents==null)this.contents=K2.collectionFromPath(this.schema,[D],u);else if(h2(this.contents))this.contents.set(D,u)}setIn(D,u){if(K2.isEmptyPath(D))this.contents=u;else if(this.contents==null)this.contents=K2.collectionFromPath(this.schema,Array.from(D),u);else if(h2(this.contents))this.contents.setIn(D,u)}setSchema(D,u={}){if(typeof D==="number")D=String(D);let r;switch(D){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new b6.Directives({version:"1.1"});r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=D;else this.directives=new b6.Directives({version:D});r={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;r=null;break;default:{let A=JSON.stringify(D);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${A}`)}}if(u.schema instanceof Object)this.schema=u.schema;else if(r)this.schema=new QO.Schema(Object.assign(r,u));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:D,jsonArg:u,mapAsMap:r,maxAliasCount:A,onAnchor:f,reviver:w}={}){let F={anchors:new Map,doc:this,keep:!D,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof A==="number"?A:100},E=NO.toJS(this.contents,u??"",F);if(typeof f==="function")for(let{count:$,res:g}of F.anchors.values())f(g,$);return typeof w==="function"?qO.applyReviver(w,{"":E},"",E):E}toJSON(D,u){return this.toJS({json:!0,jsonArg:D,mapAsMap:!1,onAnchor:u})}toString(D={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in D&&(!Number.isInteger(D.indent)||Number(D.indent)<=0)){let u=JSON.stringify(D.indent);throw Error(`"indent" option must be a positive integer, not ${u}`)}return LO.stringifyDocument(this,D)}}function h2(D){if(Xu.isCollection(D))return!0;throw Error("Expected a YAML collection as document contents")}zO.Document=z6});var c1=Q((vO)=>{class gf extends Error{constructor(D,u,r,A){super();this.name=D,this.code=r,this.message=A,this.pos=u}}class pg extends gf{constructor(D,u,r){super("YAMLParseError",D,u,r)}}class ag extends gf{constructor(D,u,r){super("YAMLWarning",D,u,r)}}var TO=(D,u)=>(r)=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map((E)=>u.linePos(E));let{line:A,col:f}=r.linePos[0];r.message+=` at line ${A}, column ${f}`;let w=f-1,F=D.substring(u.lineStarts[A-1],u.lineStarts[A]).replace(/[\n\r]+$/,"");if(w>=60&&F.length>80){let E=Math.min(w-39,F.length-79);F="\u2026"+F.substring(E),w-=E-1}if(F.length>80)F=F.substring(0,79)+"\u2026";if(A>1&&/^ *$/.test(F.substring(0,w))){let E=D.substring(u.lineStarts[A-2],u.lineStarts[A-1]);if(E.length>80)E=E.substring(0,79)+`\u2026
66
+ `}xM.stringifyDocument=pM});var yA=L((FO)=>{var aM=hA(),h2=v8(),Uu=AD(),eM=w0(),DO=A0(),uO=j6(),rO=nS(),v6=z8(),AO=w6(),fO=NA(),Z6=F6();class o6{constructor(D,u,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Uu.NODE_TYPE,{value:Uu.DOC});let A=null;if(typeof u==="function"||Array.isArray(u))A=u;else if(r===void 0&&u)r=u,u=void 0;let f=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=f;let{version:w}=f;if(r?._directives){if(this.directives=r._directives.atDocument(),this.directives.yaml.explicit)w=this.directives.yaml.version}else this.directives=new Z6.Directives({version:w});this.setSchema(w,r),this.contents=D===void 0?null:this.createNode(D,A,r)}clone(){let D=Object.create(o6.prototype,{[Uu.NODE_TYPE]:{value:Uu.DOC}});if(D.commentBefore=this.commentBefore,D.comment=this.comment,D.errors=this.errors.slice(),D.warnings=this.warnings.slice(),D.options=Object.assign({},this.options),this.directives)D.directives=this.directives.clone();if(D.schema=this.schema.clone(),D.contents=Uu.isNode(this.contents)?this.contents.clone(D.schema):this.contents,this.range)D.range=this.range.slice();return D}add(D){if(N2(this.contents))this.contents.add(D)}addIn(D,u){if(N2(this.contents))this.contents.addIn(D,u)}createAlias(D,u){if(!D.anchor){let r=v6.anchorNames(this);D.anchor=!u||r.has(u)?v6.findNewAnchor(u||"a",r):u}return new aM.Alias(D.anchor)}createNode(D,u,r){let A=void 0;if(typeof u==="function")D=u.call({"":D},"",D),A=u;else if(Array.isArray(u)){let J=(M)=>typeof M==="number"||M instanceof String||M instanceof Number,X=u.filter(J).map(String);if(X.length>0)u=u.concat(X);A=u}else if(r===void 0&&u)r=u,u=void 0;let{aliasDuplicateObjects:f,anchorPrefix:w,flow:F,keepUndefined:E,onTagObj:$,tag:g}=r??{},{onAnchor:_,setAnchors:R,sourceObjects:n}=v6.createNodeAnchors(this,w||"a"),B={aliasDuplicateObjects:f??!0,keepUndefined:E??!1,onAnchor:_,onTagObj:$,replacer:A,schema:this.schema,sourceObjects:n},C=fO.createNode(D,g,B);if(F&&Uu.isCollection(C))C.flow=!0;return R(),C}createPair(D,u,r={}){let A=this.createNode(D,null,r),f=this.createNode(u,null,r);return new eM.Pair(A,f)}delete(D){return N2(this.contents)?this.contents.delete(D):!1}deleteIn(D){if(h2.isEmptyPath(D)){if(this.contents==null)return!1;return this.contents=null,!0}return N2(this.contents)?this.contents.deleteIn(D):!1}get(D,u){return Uu.isCollection(this.contents)?this.contents.get(D,u):void 0}getIn(D,u){if(h2.isEmptyPath(D))return!u&&Uu.isScalar(this.contents)?this.contents.value:this.contents;return Uu.isCollection(this.contents)?this.contents.getIn(D,u):void 0}has(D){return Uu.isCollection(this.contents)?this.contents.has(D):!1}hasIn(D){if(h2.isEmptyPath(D))return this.contents!==void 0;return Uu.isCollection(this.contents)?this.contents.hasIn(D):!1}set(D,u){if(this.contents==null)this.contents=h2.collectionFromPath(this.schema,[D],u);else if(N2(this.contents))this.contents.set(D,u)}setIn(D,u){if(h2.isEmptyPath(D))this.contents=u;else if(this.contents==null)this.contents=h2.collectionFromPath(this.schema,Array.from(D),u);else if(N2(this.contents))this.contents.setIn(D,u)}setSchema(D,u={}){if(typeof D==="number")D=String(D);let r;switch(D){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new Z6.Directives({version:"1.1"});r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=D;else this.directives=new Z6.Directives({version:D});r={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;r=null;break;default:{let A=JSON.stringify(D);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${A}`)}}if(u.schema instanceof Object)this.schema=u.schema;else if(r)this.schema=new uO.Schema(Object.assign(r,u));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:D,jsonArg:u,mapAsMap:r,maxAliasCount:A,onAnchor:f,reviver:w}={}){let F={anchors:new Map,doc:this,keep:!D,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof A==="number"?A:100},E=DO.toJS(this.contents,u??"",F);if(typeof f==="function")for(let{count:$,res:g}of F.anchors.values())f(g,$);return typeof w==="function"?AO.applyReviver(w,{"":E},"",E):E}toJSON(D,u){return this.toJS({json:!0,jsonArg:D,mapAsMap:!1,onAnchor:u})}toString(D={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in D&&(!Number.isInteger(D.indent)||Number(D.indent)<=0)){let u=JSON.stringify(D.indent);throw Error(`"indent" option must be a positive integer, not ${u}`)}return rO.stringifyDocument(this,D)}}function N2(D){if(Uu.isCollection(D))return!0;throw Error("Expected a YAML collection as document contents")}FO.Document=o6});var cA=L((EO)=>{class nf extends Error{constructor(D,u,r,A){super();this.name=D,this.code=r,this.message=A,this.pos=u}}class BS extends nf{constructor(D,u,r){super("YAMLParseError",D,u,r)}}class WS extends nf{constructor(D,u,r){super("YAMLWarning",D,u,r)}}var $O=(D,u)=>(r)=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map((E)=>u.linePos(E));let{line:A,col:f}=r.linePos[0];r.message+=` at line ${A}, column ${f}`;let w=f-1,F=D.substring(u.lineStarts[A-1],u.lineStarts[A]).replace(/[\n\r]+$/,"");if(w>=60&&F.length>80){let E=Math.min(w-39,F.length-79);F="\u2026"+F.substring(E),w-=E-1}if(F.length>80)F=F.substring(0,79)+"\u2026";if(A>1&&/^ *$/.test(F.substring(0,w))){let E=D.substring(u.lineStarts[A-2],u.lineStarts[A-1]);if(E.length>80)E=E.substring(0,79)+`\u2026
67
67
  `;F=E+F}if(/[^ ]/.test(F)){let E=1,$=r.linePos[1];if($?.line===A&&$.col>f)E=Math.max(1,Math.min($.col-f,80-w));let g=" ".repeat(w)+"^".repeat(E);r.message+=`:
68
68
 
69
69
  ${F}
70
70
  ${g}
71
- `}};vO.YAMLError=gf;vO.YAMLParseError=pg;vO.YAMLWarning=ag;vO.prettifyError=TO});var t1=Q((lO)=>{function yO(D,{flow:u,indicator:r,next:A,offset:f,onError:w,parentIndent:F,startOnNewline:E}){let $=!1,g=E,R=E,S="",B="",J=!1,H=!1,G=null,U=null,O=null,i=null,k=null,z=null,q=null;for(let h of D){if(H){if(h.type!=="space"&&h.type!=="newline"&&h.type!=="comma")w(h.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");H=!1}if(G){if(g&&h.type!=="comment"&&h.type!=="newline")w(G,"TAB_AS_INDENT","Tabs are not allowed as indentation");G=null}switch(h.type){case"space":if(!u&&(r!=="doc-start"||A?.type!=="flow-collection")&&h.source.includes("\t"))G=h;R=!0;break;case"comment":{if(!R)w(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let rD=h.source.substring(1)||" ";if(!S)S=rD;else S+=B+rD;B="",g=!1;break}case"newline":if(g){if(S)S+=h.source;else if(!z||r!=="seq-item-ind")$=!0}else B+=h.source;if(g=!0,J=!0,U||O)i=h;R=!0;break;case"anchor":if(U)w(h,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(h.source.endsWith(":"))w(h.offset+h.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);U=h,q??(q=h.offset),g=!1,R=!1,H=!0;break;case"tag":{if(O)w(h,"MULTIPLE_TAGS","A node can have at most one tag");O=h,q??(q=h.offset),g=!1,R=!1,H=!0;break}case r:if(U||O)w(h,"BAD_PROP_ORDER",`Anchors and tags must be after the ${h.source} indicator`);if(z)w(h,"UNEXPECTED_TOKEN",`Unexpected ${h.source} in ${u??"collection"}`);z=h,g=r==="seq-item-ind"||r==="explicit-key-ind",R=!1;break;case"comma":if(u){if(k)w(h,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`);k=h,g=!1,R=!1;break}default:w(h,"UNEXPECTED_TOKEN",`Unexpected ${h.type} token`),g=!1,R=!1}}let M=D[D.length-1],s=M?M.offset+M.source.length:f;if(H&&A&&A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&(A.type!=="scalar"||A.source!==""))w(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(G&&(g&&G.indent<=F||A?.type==="block-map"||A?.type==="block-seq"))w(G,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:k,found:z,spaceBefore:$,comment:S,hasNewline:J,anchor:U,tag:O,newlineAfterProp:i,end:s,start:q??s}}lO.resolveProps=yO});var _f=Q((tO)=>{function j6(D){if(!D)return null;switch(D.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(D.source.includes(`
72
- `))return!0;if(D.end){for(let u of D.end)if(u.type==="newline")return!0}return!1;case"flow-collection":for(let u of D.items){for(let r of u.start)if(r.type==="newline")return!0;if(u.sep){for(let r of u.sep)if(r.type==="newline")return!0}if(j6(u.key)||j6(u.value))return!0}return!1;default:return!0}}tO.containsNewline=j6});var T6=Q((aO)=>{var mO=_f();function pO(D,u,r){if(u?.type==="flow-collection"){let A=u.end[0];if(A.indent===D&&(A.source==="]"||A.source==="}")&&mO.containsNewline(u))r(A,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}aO.flowIndentCheck=pO});var v6=Q((uP)=>{var eg=AD();function DP(D,u,r){let{uniqueKeys:A}=D.options;if(A===!1)return!1;let f=typeof A==="function"?A:(w,F)=>w===F||eg.isScalar(w)&&eg.isScalar(F)&&w.value===F.value;return u.some((w)=>f(w.key,r))}uP.mapIncludes=DP});var f_=Q(($P)=>{var D_=w0(),AP=E0(),u_=t1(),fP=_f(),r_=T6(),FP=v6(),A_="All mapping items must start at the same column";function wP({composeNode:D,composeEmptyNode:u},r,A,f,w){let E=new(w?.nodeClass??AP.YAMLMap)(r.schema);if(r.atRoot)r.atRoot=!1;let $=A.offset,g=null;for(let R of A.items){let{start:S,key:B,sep:J,value:H}=R,G=u_.resolveProps(S,{indicator:"explicit-key-ind",next:B??J?.[0],offset:$,onError:f,parentIndent:A.indent,startOnNewline:!0}),U=!G.found;if(U){if(B){if(B.type==="block-seq")f($,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in B&&B.indent!==A.indent)f($,"BAD_INDENT",A_)}if(!G.anchor&&!G.tag&&!J){if(g=G.end,G.comment)if(E.comment)E.comment+=`
73
- `+G.comment;else E.comment=G.comment;continue}if(G.newlineAfterProp||fP.containsNewline(B))f(B??S[S.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(G.found?.indent!==A.indent)f($,"BAD_INDENT",A_);r.atKey=!0;let O=G.end,i=B?D(r,B,G,f):u(r,O,S,null,G,f);if(r.schema.compat)r_.flowIndentCheck(A.indent,B,f);if(r.atKey=!1,FP.mapIncludes(r,E.items,i))f(O,"DUPLICATE_KEY","Map keys must be unique");let k=u_.resolveProps(J??[],{indicator:"map-value-ind",next:H,offset:i.range[2],onError:f,parentIndent:A.indent,startOnNewline:!B||B.type==="block-scalar"});if($=k.end,k.found){if(U){if(H?.type==="block-map"&&!k.hasNewline)f($,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(r.options.strict&&G.start<k.found.offset-1024)f(i.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let z=H?D(r,H,k,f):u(r,$,J,null,k,f);if(r.schema.compat)r_.flowIndentCheck(A.indent,H,f);$=z.range[2];let q=new D_.Pair(i,z);if(r.options.keepSourceTokens)q.srcToken=R;E.items.push(q)}else{if(U)f(i.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(k.comment)if(i.comment)i.comment+=`
74
- `+k.comment;else i.comment=k.comment;let z=new D_.Pair(i);if(r.options.keepSourceTokens)z.srcToken=R;E.items.push(z)}}if(g&&g<$)f(g,"IMPOSSIBLE","Map comment with trailing content");return E.range=[A.offset,$,g??$],E}$P.resolveBlockMap=wP});var F_=Q((BP)=>{var gP=g0(),_P=t1(),RP=T6();function SP({composeNode:D,composeEmptyNode:u},r,A,f,w){let E=new(w?.nodeClass??gP.YAMLSeq)(r.schema);if(r.atRoot)r.atRoot=!1;if(r.atKey)r.atKey=!1;let $=A.offset,g=null;for(let{start:R,value:S}of A.items){let B=_P.resolveProps(R,{indicator:"seq-item-ind",next:S,offset:$,onError:f,parentIndent:A.indent,startOnNewline:!0});if(!B.found)if(B.anchor||B.tag||S)if(S?.type==="block-seq")f(B.end,"BAD_INDENT","All sequence items must start at the same column");else f($,"MISSING_CHAR","Sequence item without - indicator");else{if(g=B.end,B.comment)E.comment=B.comment;continue}let J=S?D(r,S,B,f):u(r,B.end,R,null,B,f);if(r.schema.compat)RP.flowIndentCheck(A.indent,S,f);$=J.range[2],E.items.push(J)}return E.range=[A.offset,$,g??$],E}BP.resolveBlockSeq=SP});var N2=Q((GP)=>{function WP(D,u,r,A){let f="";if(D){let w=!1,F="";for(let E of D){let{source:$,type:g}=E;switch(g){case"space":w=!0;break;case"comment":{if(r&&!w)A(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=$.substring(1)||" ";if(!f)f=R;else f+=F+R;F="";break}case"newline":if(f)F+=$;w=!0;break;default:A(E,"UNEXPECTED_TOKEN",`Unexpected ${g} at node end`)}u+=$.length}}return{comment:f,offset:u}}GP.resolveEnd=WP});var E_=Q((PP)=>{var HP=AD(),nP=w0(),w_=E0(),UP=g0(),XP=N2(),$_=t1(),YP=_f(),MP=v6(),s6="Block collections are not allowed within flow collections",Z6=(D)=>D&&(D.type==="block-map"||D.type==="block-seq");function OP({composeNode:D,composeEmptyNode:u},r,A,f,w){let F=A.start.source==="{",E=F?"flow map":"flow sequence",g=new(w?.nodeClass??(F?w_.YAMLMap:UP.YAMLSeq))(r.schema);g.flow=!0;let R=r.atRoot;if(R)r.atRoot=!1;if(r.atKey)r.atKey=!1;let S=A.offset+A.start.source.length;for(let U=0;U<A.items.length;++U){let O=A.items[U],{start:i,key:k,sep:z,value:q}=O,M=$_.resolveProps(i,{flow:E,indicator:"explicit-key-ind",next:k??z?.[0],offset:S,onError:f,parentIndent:A.indent,startOnNewline:!1});if(!M.found){if(!M.anchor&&!M.tag&&!z&&!q){if(U===0&&M.comma)f(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${E}`);else if(U<A.items.length-1)f(M.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${E}`);if(M.comment)if(g.comment)g.comment+=`
75
- `+M.comment;else g.comment=M.comment;S=M.end;continue}if(!F&&r.options.strict&&YP.containsNewline(k))f(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(U===0){if(M.comma)f(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${E}`)}else{if(!M.comma)f(M.start,"MISSING_CHAR",`Missing , between ${E} items`);if(M.comment){let s="";D:for(let h of i)switch(h.type){case"comma":case"space":break;case"comment":s=h.source.substring(1);break D;default:break D}if(s){let h=g.items[g.items.length-1];if(HP.isPair(h))h=h.value??h.key;if(h.comment)h.comment+=`
76
- `+s;else h.comment=s;M.comment=M.comment.substring(s.length+1)}}}if(!F&&!z&&!M.found){let s=q?D(r,q,M,f):u(r,M.end,z,null,M,f);if(g.items.push(s),S=s.range[2],Z6(q))f(s.range,"BLOCK_IN_FLOW",s6)}else{r.atKey=!0;let s=M.end,h=k?D(r,k,M,f):u(r,s,i,null,M,f);if(Z6(k))f(h.range,"BLOCK_IN_FLOW",s6);r.atKey=!1;let rD=$_.resolveProps(z??[],{flow:E,indicator:"map-value-ind",next:q,offset:h.range[2],onError:f,parentIndent:A.indent,startOnNewline:!1});if(rD.found){if(!F&&!M.found&&r.options.strict){if(z)for(let e of z){if(e===rD.found)break;if(e.type==="newline"){f(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(M.start<rD.found.offset-1024)f(rD.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(q)if("source"in q&&q.source?.[0]===":")f(q,"MISSING_CHAR",`Missing space after : in ${E}`);else f(rD.start,"MISSING_CHAR",`Missing , or : between ${E} items`);let _D=q?D(r,q,rD,f):rD.found?u(r,rD.end,z,null,rD,f):null;if(_D){if(Z6(q))f(_D.range,"BLOCK_IN_FLOW",s6)}else if(rD.comment)if(h.comment)h.comment+=`
77
- `+rD.comment;else h.comment=rD.comment;let WD=new nP.Pair(h,_D);if(r.options.keepSourceTokens)WD.srcToken=O;if(F){let e=g;if(MP.mapIncludes(r,e.items,h))f(s,"DUPLICATE_KEY","Map keys must be unique");e.items.push(WD)}else{let e=new w_.YAMLMap(r.schema);e.flow=!0,e.items.push(WD);let QD=(_D??h).range;e.range=[h.range[0],QD[1],QD[2]],g.items.push(e)}S=_D?_D.range[2]:rD.end}}let B=F?"}":"]",[J,...H]=A.end,G=S;if(J?.source===B)G=J.offset+J.source.length;else{let U=E[0].toUpperCase()+E.substring(1),O=R?`${U} must end with a ${B}`:`${U} in block collection must be sufficiently indented and end with a ${B}`;if(f(S,R?"MISSING_CHAR":"BAD_INDENT",O),J&&J.source.length!==1)H.unshift(J)}if(H.length>0){let U=XP.resolveEnd(H,G,r.options.strict,f);if(U.comment)if(g.comment)g.comment+=`
78
- `+U.comment;else g.comment=U.comment;g.range=[A.offset,G,U.offset]}else g.range=[A.offset,G,G];return g}PP.resolveFlowCollection=OP});var g_=Q((qP)=>{var kP=AD(),IP=ID(),VP=E0(),KP=g0(),hP=f_(),NP=F_(),QP=E_();function o6(D,u,r,A,f,w){let F=r.type==="block-map"?hP.resolveBlockMap(D,u,r,A,w):r.type==="block-seq"?NP.resolveBlockSeq(D,u,r,A,w):QP.resolveFlowCollection(D,u,r,A,w),E=F.constructor;if(f==="!"||f===E.tagName)return F.tag=E.tagName,F;if(f)F.tag=f;return F}function LP(D,u,r,A,f){let w=A.tag,F=!w?null:u.directives.tagName(w.source,(B)=>f(w,"TAG_RESOLVE_FAILED",B));if(r.type==="block-seq"){let{anchor:B,newlineAfterProp:J}=A,H=B&&w?B.offset>w.offset?B:w:B??w;if(H&&(!J||J.offset<H.offset))f(H,"MISSING_CHAR","Missing newline after block sequence props")}let E=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!w||!F||F==="!"||F===VP.YAMLMap.tagName&&E==="map"||F===KP.YAMLSeq.tagName&&E==="seq")return o6(D,u,r,f,F);let $=u.schema.tags.find((B)=>B.tag===F&&B.collection===E);if(!$){let B=u.schema.knownTags[F];if(B?.collection===E)u.schema.tags.push(Object.assign({},B,{default:!1})),$=B;else{if(B)f(w,"BAD_COLLECTION_TYPE",`${B.tag} used for ${E} collection, but expects ${B.collection??"scalar"}`,!0);else f(w,"TAG_RESOLVE_FAILED",`Unresolved tag: ${F}`,!0);return o6(D,u,r,f,F)}}let g=o6(D,u,r,f,F,$),R=$.resolve?.(g,(B)=>f(w,"TAG_RESOLVE_FAILED",B),u.options)??g,S=kP.isNode(R)?R:new IP.Scalar(R);if(S.range=g.range,S.tag=F,$?.format)S.format=$.format;return S}qP.composeCollection=LP});var y6=Q((vP)=>{var d6=ID();function zP(D,u,r){let A=u.offset,f=jP(u,D.options.strict,r);if(!f)return{value:"",type:null,comment:"",range:[A,A,A]};let w=f.mode===">"?d6.Scalar.BLOCK_FOLDED:d6.Scalar.BLOCK_LITERAL,F=u.source?TP(u.source):[],E=F.length;for(let G=F.length-1;G>=0;--G){let U=F[G][1];if(U===""||U==="\r")E=G;else break}if(E===0){let G=f.chomp==="+"&&F.length>0?`
79
- `.repeat(Math.max(1,F.length-1)):"",U=A+f.length;if(u.source)U+=u.source.length;return{value:G,type:w,comment:f.comment,range:[A,U,U]}}let $=u.indent+f.indent,g=u.offset+f.length,R=0;for(let G=0;G<E;++G){let[U,O]=F[G];if(O===""||O==="\r"){if(f.indent===0&&U.length>$)$=U.length}else{if(U.length<$)r(g+U.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(f.indent===0)$=U.length;if(R=G,$===0&&!D.atRoot)r(g,"BAD_INDENT","Block scalar values in collections must be indented");break}g+=U.length+O.length+1}for(let G=F.length-1;G>=E;--G)if(F[G][0].length>$)E=G+1;let S="",B="",J=!1;for(let G=0;G<R;++G)S+=F[G][0].slice($)+`
80
- `;for(let G=R;G<E;++G){let[U,O]=F[G];g+=U.length+O.length+1;let i=O[O.length-1]==="\r";if(i)O=O.slice(0,-1);if(O&&U.length<$){let z=`Block scalar lines must not be less indented than their ${f.indent?"explicit indentation indicator":"first line"}`;r(g-O.length-(i?2:1),"BAD_INDENT",z),U=""}if(w===d6.Scalar.BLOCK_LITERAL)S+=B+U.slice($)+O,B=`
81
- `;else if(U.length>$||O[0]==="\t"){if(B===" ")B=`
82
- `;else if(!J&&B===`
83
- `)B=`
84
-
85
- `;S+=B+U.slice($)+O,B=`
86
- `,J=!0}else if(O==="")if(B===`
87
- `)S+=`
88
- `;else B=`
89
- `;else S+=B+O,B=" ",J=!1}switch(f.chomp){case"-":break;case"+":for(let G=E;G<F.length;++G)S+=`
90
- `+F[G][0].slice($);if(S[S.length-1]!==`
91
- `)S+=`
92
- `;break;default:S+=`
93
- `}let H=A+f.length+u.source.length;return{value:S,type:w,comment:f.comment,range:[A,H,H]}}function jP({offset:D,props:u},r,A){if(u[0].type!=="block-scalar-header")return A(u[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:f}=u[0],w=f[0],F=0,E="",$=-1;for(let B=1;B<f.length;++B){let J=f[B];if(!E&&(J==="-"||J==="+"))E=J;else{let H=Number(J);if(!F&&H)F=H;else if($===-1)$=D+B}}if($!==-1)A($,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${f}`);let g=!1,R="",S=f.length;for(let B=1;B<u.length;++B){let J=u[B];switch(J.type){case"space":g=!0;case"newline":S+=J.source.length;break;case"comment":if(r&&!g)A(J,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");S+=J.source.length,R=J.source.substring(1);break;case"error":A(J,"UNEXPECTED_TOKEN",J.message),S+=J.source.length;break;default:{let H=`Unexpected token in block scalar header: ${J.type}`;A(J,"UNEXPECTED_TOKEN",H);let G=J.source;if(G&&typeof G==="string")S+=G.length}}}return{mode:w,indent:F,chomp:E,comment:R,length:S}}function TP(D){let u=D.split(/\n( *)/),r=u[0],A=r.match(/^( *)/),w=[A?.[1]?[A[1],r.slice(A[1].length)]:["",r]];for(let F=1;F<u.length;F+=2)w.push([u[F],u[F+1]]);return w}vP.resolveBlockScalar=zP});var c6=Q((mP)=>{var l6=ID(),ZP=N2();function oP(D,u,r){let{offset:A,type:f,source:w,end:F}=D,E,$,g=(B,J,H)=>r(A+B,J,H);switch(f){case"scalar":E=l6.Scalar.PLAIN,$=dP(w,g);break;case"single-quoted-scalar":E=l6.Scalar.QUOTE_SINGLE,$=yP(w,g);break;case"double-quoted-scalar":E=l6.Scalar.QUOTE_DOUBLE,$=lP(w,g);break;default:return r(D,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${f}`),{value:"",type:null,comment:"",range:[A,A+w.length,A+w.length]}}let R=A+w.length,S=ZP.resolveEnd(F,R,u,r);return{value:$,type:E,comment:S.comment,range:[A,R,S.offset]}}function dP(D,u){let r="";switch(D[0]){case"\t":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${D[0]}`;break}case"@":case"`":{r=`reserved character ${D[0]}`;break}}if(r)u(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`);return __(D)}function yP(D,u){if(D[D.length-1]!=="'"||D.length===1)u(D.length,"MISSING_CHAR","Missing closing 'quote");return __(D.slice(1,-1)).replace(/''/g,"'")}function __(D){let u,r;try{u=new RegExp(`(.*?)(?<![ ])[ ]*\r?
71
+ `}};EO.YAMLError=nf;EO.YAMLParseError=BS;EO.YAMLWarning=WS;EO.prettifyError=$O});var tA=L((BO)=>{function nO(D,{flow:u,indicator:r,next:A,offset:f,onError:w,parentIndent:F,startOnNewline:E}){let $=!1,g=E,_=E,R="",n="",B=!1,C=!1,J=null,X=null,M=null,P=null,k=null,s=null,q=null;for(let N of D){if(C){if(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma")w(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");C=!1}if(J){if(g&&N.type!=="comment"&&N.type!=="newline")w(J,"TAB_AS_INDENT","Tabs are not allowed as indentation");J=null}switch(N.type){case"space":if(!u&&(r!=="doc-start"||A?.type!=="flow-collection")&&N.source.includes("\t"))J=N;_=!0;break;case"comment":{if(!_)w(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let rD=N.source.substring(1)||" ";if(!R)R=rD;else R+=n+rD;n="",g=!1;break}case"newline":if(g){if(R)R+=N.source;else if(!s||r!=="seq-item-ind")$=!0}else n+=N.source;if(g=!0,B=!0,X||M)P=N;_=!0;break;case"anchor":if(X)w(N,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(N.source.endsWith(":"))w(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);X=N,q??(q=N.offset),g=!1,_=!1,C=!0;break;case"tag":{if(M)w(N,"MULTIPLE_TAGS","A node can have at most one tag");M=N,q??(q=N.offset),g=!1,_=!1,C=!0;break}case r:if(X||M)w(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`);if(s)w(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${u??"collection"}`);s=N,g=r==="seq-item-ind"||r==="explicit-key-ind",_=!1;break;case"comma":if(u){if(k)w(N,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`);k=N,g=!1,_=!1;break}default:w(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),g=!1,_=!1}}let Y=D[D.length-1],v=Y?Y.offset+Y.source.length:f;if(C&&A&&A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&(A.type!=="scalar"||A.source!==""))w(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(J&&(g&&J.indent<=F||A?.type==="block-map"||A?.type==="block-seq"))w(J,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:k,found:s,spaceBefore:$,comment:R,hasNewline:B,anchor:X,tag:M,newlineAfterProp:P,end:v,start:q??v}}BO.resolveProps=nO});var Bf=L((JO)=>{function d6(D){if(!D)return null;switch(D.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(D.source.includes(`
72
+ `))return!0;if(D.end){for(let u of D.end)if(u.type==="newline")return!0}return!1;case"flow-collection":for(let u of D.items){for(let r of u.start)if(r.type==="newline")return!0;if(u.sep){for(let r of u.sep)if(r.type==="newline")return!0}if(d6(u.key)||d6(u.value))return!0}return!1;default:return!0}}JO.containsNewline=d6});var l6=L((XO)=>{var CO=Bf();function HO(D,u,r){if(u?.type==="flow-collection"){let A=u.end[0];if(A.indent===D&&(A.source==="]"||A.source==="}")&&CO.containsNewline(u))r(A,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}XO.flowIndentCheck=HO});var y6=L((YO)=>{var JS=AD();function UO(D,u,r){let{uniqueKeys:A}=D.options;if(A===!1)return!1;let f=typeof A==="function"?A:(w,F)=>w===F||JS.isScalar(w)&&JS.isScalar(F)&&w.value===F.value;return u.some((w)=>f(w.key,r))}YO.mapIncludes=UO});var iS=L((VO)=>{var GS=w0(),OO=E0(),CS=tA(),PO=Bf(),HS=l6(),kO=y6(),XS="All mapping items must start at the same column";function IO({composeNode:D,composeEmptyNode:u},r,A,f,w){let E=new(w?.nodeClass??OO.YAMLMap)(r.schema);if(r.atRoot)r.atRoot=!1;let $=A.offset,g=null;for(let _ of A.items){let{start:R,key:n,sep:B,value:C}=_,J=CS.resolveProps(R,{indicator:"explicit-key-ind",next:n??B?.[0],offset:$,onError:f,parentIndent:A.indent,startOnNewline:!0}),X=!J.found;if(X){if(n){if(n.type==="block-seq")f($,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in n&&n.indent!==A.indent)f($,"BAD_INDENT",XS)}if(!J.anchor&&!J.tag&&!B){if(g=J.end,J.comment)if(E.comment)E.comment+=`
73
+ `+J.comment;else E.comment=J.comment;continue}if(J.newlineAfterProp||PO.containsNewline(n))f(n??R[R.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(J.found?.indent!==A.indent)f($,"BAD_INDENT",XS);r.atKey=!0;let M=J.end,P=n?D(r,n,J,f):u(r,M,R,null,J,f);if(r.schema.compat)HS.flowIndentCheck(A.indent,n,f);if(r.atKey=!1,kO.mapIncludes(r,E.items,P))f(M,"DUPLICATE_KEY","Map keys must be unique");let k=CS.resolveProps(B??[],{indicator:"map-value-ind",next:C,offset:P.range[2],onError:f,parentIndent:A.indent,startOnNewline:!n||n.type==="block-scalar"});if($=k.end,k.found){if(X){if(C?.type==="block-map"&&!k.hasNewline)f($,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(r.options.strict&&J.start<k.found.offset-1024)f(P.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let s=C?D(r,C,k,f):u(r,$,B,null,k,f);if(r.schema.compat)HS.flowIndentCheck(A.indent,C,f);$=s.range[2];let q=new GS.Pair(P,s);if(r.options.keepSourceTokens)q.srcToken=_;E.items.push(q)}else{if(X)f(P.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(k.comment)if(P.comment)P.comment+=`
74
+ `+k.comment;else P.comment=k.comment;let s=new GS.Pair(P);if(r.options.keepSourceTokens)s.srcToken=_;E.items.push(s)}}if(g&&g<$)f(g,"IMPOSSIBLE","Map comment with trailing content");return E.range=[A.offset,$,g??$],E}VO.resolveBlockMap=IO});var US=L((qO)=>{var hO=g0(),NO=tA(),QO=l6();function LO({composeNode:D,composeEmptyNode:u},r,A,f,w){let E=new(w?.nodeClass??hO.YAMLSeq)(r.schema);if(r.atRoot)r.atRoot=!1;if(r.atKey)r.atKey=!1;let $=A.offset,g=null;for(let{start:_,value:R}of A.items){let n=NO.resolveProps(_,{indicator:"seq-item-ind",next:R,offset:$,onError:f,parentIndent:A.indent,startOnNewline:!0});if(!n.found)if(n.anchor||n.tag||R)if(R?.type==="block-seq")f(n.end,"BAD_INDENT","All sequence items must start at the same column");else f($,"MISSING_CHAR","Sequence item without - indicator");else{if(g=n.end,n.comment)E.comment=n.comment;continue}let B=R?D(r,R,n,f):u(r,n.end,_,null,n,f);if(r.schema.compat)QO.flowIndentCheck(A.indent,R,f);$=B.range[2],E.items.push(B)}return E.range=[A.offset,$,g??$],E}qO.resolveBlockSeq=LO});var Q2=L((zO)=>{function sO(D,u,r,A){let f="";if(D){let w=!1,F="";for(let E of D){let{source:$,type:g}=E;switch(g){case"space":w=!0;break;case"comment":{if(r&&!w)A(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=$.substring(1)||" ";if(!f)f=_;else f+=F+_;F="";break}case"newline":if(f)F+=$;w=!0;break;default:A(E,"UNEXPECTED_TOKEN",`Unexpected ${g} at node end`)}u+=$.length}}return{comment:f,offset:u}}zO.resolveEnd=sO});var OS=L((cO)=>{var TO=AD(),vO=w0(),YS=E0(),ZO=g0(),oO=Q2(),MS=tA(),dO=Bf(),lO=y6(),c6="Block collections are not allowed within flow collections",t6=(D)=>D&&(D.type==="block-map"||D.type==="block-seq");function yO({composeNode:D,composeEmptyNode:u},r,A,f,w){let F=A.start.source==="{",E=F?"flow map":"flow sequence",g=new(w?.nodeClass??(F?YS.YAMLMap:ZO.YAMLSeq))(r.schema);g.flow=!0;let _=r.atRoot;if(_)r.atRoot=!1;if(r.atKey)r.atKey=!1;let R=A.offset+A.start.source.length;for(let X=0;X<A.items.length;++X){let M=A.items[X],{start:P,key:k,sep:s,value:q}=M,Y=MS.resolveProps(P,{flow:E,indicator:"explicit-key-ind",next:k??s?.[0],offset:R,onError:f,parentIndent:A.indent,startOnNewline:!1});if(!Y.found){if(!Y.anchor&&!Y.tag&&!s&&!q){if(X===0&&Y.comma)f(Y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${E}`);else if(X<A.items.length-1)f(Y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${E}`);if(Y.comment)if(g.comment)g.comment+=`
75
+ `+Y.comment;else g.comment=Y.comment;R=Y.end;continue}if(!F&&r.options.strict&&dO.containsNewline(k))f(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(X===0){if(Y.comma)f(Y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${E}`)}else{if(!Y.comma)f(Y.start,"MISSING_CHAR",`Missing , between ${E} items`);if(Y.comment){let v="";D:for(let N of P)switch(N.type){case"comma":case"space":break;case"comment":v=N.source.substring(1);break D;default:break D}if(v){let N=g.items[g.items.length-1];if(TO.isPair(N))N=N.value??N.key;if(N.comment)N.comment+=`
76
+ `+v;else N.comment=v;Y.comment=Y.comment.substring(v.length+1)}}}if(!F&&!s&&!Y.found){let v=q?D(r,q,Y,f):u(r,Y.end,s,null,Y,f);if(g.items.push(v),R=v.range[2],t6(q))f(v.range,"BLOCK_IN_FLOW",c6)}else{r.atKey=!0;let v=Y.end,N=k?D(r,k,Y,f):u(r,v,P,null,Y,f);if(t6(k))f(N.range,"BLOCK_IN_FLOW",c6);r.atKey=!1;let rD=MS.resolveProps(s??[],{flow:E,indicator:"map-value-ind",next:q,offset:N.range[2],onError:f,parentIndent:A.indent,startOnNewline:!1});if(rD.found){if(!F&&!Y.found&&r.options.strict){if(s)for(let e of s){if(e===rD.found)break;if(e.type==="newline"){f(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(Y.start<rD.found.offset-1024)f(rD.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(q)if("source"in q&&q.source?.[0]===":")f(q,"MISSING_CHAR",`Missing space after : in ${E}`);else f(rD.start,"MISSING_CHAR",`Missing , or : between ${E} items`);let _D=q?D(r,q,rD,f):rD.found?u(r,rD.end,s,null,rD,f):null;if(_D){if(t6(q))f(_D.range,"BLOCK_IN_FLOW",c6)}else if(rD.comment)if(N.comment)N.comment+=`
77
+ `+rD.comment;else N.comment=rD.comment;let WD=new vO.Pair(N,_D);if(r.options.keepSourceTokens)WD.srcToken=M;if(F){let e=g;if(lO.mapIncludes(r,e.items,N))f(v,"DUPLICATE_KEY","Map keys must be unique");e.items.push(WD)}else{let e=new YS.YAMLMap(r.schema);e.flow=!0,e.items.push(WD);let qD=(_D??N).range;e.range=[N.range[0],qD[1],qD[2]],g.items.push(e)}R=_D?_D.range[2]:rD.end}}let n=F?"}":"]",[B,...C]=A.end,J=R;if(B?.source===n)J=B.offset+B.source.length;else{let X=E[0].toUpperCase()+E.substring(1),M=_?`${X} must end with a ${n}`:`${X} in block collection must be sufficiently indented and end with a ${n}`;if(f(R,_?"MISSING_CHAR":"BAD_INDENT",M),B&&B.source.length!==1)C.unshift(B)}if(C.length>0){let X=oO.resolveEnd(C,J,r.options.strict,f);if(X.comment)if(g.comment)g.comment+=`
78
+ `+X.comment;else g.comment=X.comment;g.range=[A.offset,J,X.offset]}else g.range=[A.offset,J,J];return g}cO.resolveFlowCollection=yO});var PS=L((AP)=>{var pO=AD(),xO=VD(),mO=E0(),aO=g0(),eO=iS(),DP=US(),uP=OS();function p6(D,u,r,A,f,w){let F=r.type==="block-map"?eO.resolveBlockMap(D,u,r,A,w):r.type==="block-seq"?DP.resolveBlockSeq(D,u,r,A,w):uP.resolveFlowCollection(D,u,r,A,w),E=F.constructor;if(f==="!"||f===E.tagName)return F.tag=E.tagName,F;if(f)F.tag=f;return F}function rP(D,u,r,A,f){let w=A.tag,F=!w?null:u.directives.tagName(w.source,(n)=>f(w,"TAG_RESOLVE_FAILED",n));if(r.type==="block-seq"){let{anchor:n,newlineAfterProp:B}=A,C=n&&w?n.offset>w.offset?n:w:n??w;if(C&&(!B||B.offset<C.offset))f(C,"MISSING_CHAR","Missing newline after block sequence props")}let E=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!w||!F||F==="!"||F===mO.YAMLMap.tagName&&E==="map"||F===aO.YAMLSeq.tagName&&E==="seq")return p6(D,u,r,f,F);let $=u.schema.tags.find((n)=>n.tag===F&&n.collection===E);if(!$){let n=u.schema.knownTags[F];if(n?.collection===E)u.schema.tags.push(Object.assign({},n,{default:!1})),$=n;else{if(n)f(w,"BAD_COLLECTION_TYPE",`${n.tag} used for ${E} collection, but expects ${n.collection??"scalar"}`,!0);else f(w,"TAG_RESOLVE_FAILED",`Unresolved tag: ${F}`,!0);return p6(D,u,r,f,F)}}let g=p6(D,u,r,f,F,$),_=$.resolve?.(g,(n)=>f(w,"TAG_RESOLVE_FAILED",n),u.options)??g,R=pO.isNode(_)?_:new xO.Scalar(_);if(R.range=g.range,R.tag=F,$?.format)R.format=$.format;return R}AP.composeCollection=rP});var m6=L((EP)=>{var x6=VD();function FP(D,u,r){let A=u.offset,f=wP(u,D.options.strict,r);if(!f)return{value:"",type:null,comment:"",range:[A,A,A]};let w=f.mode===">"?x6.Scalar.BLOCK_FOLDED:x6.Scalar.BLOCK_LITERAL,F=u.source?$P(u.source):[],E=F.length;for(let J=F.length-1;J>=0;--J){let X=F[J][1];if(X===""||X==="\r")E=J;else break}if(E===0){let J=f.chomp==="+"&&F.length>0?`
79
+ `.repeat(Math.max(1,F.length-1)):"",X=A+f.length;if(u.source)X+=u.source.length;return{value:J,type:w,comment:f.comment,range:[A,X,X]}}let $=u.indent+f.indent,g=u.offset+f.length,_=0;for(let J=0;J<E;++J){let[X,M]=F[J];if(M===""||M==="\r"){if(f.indent===0&&X.length>$)$=X.length}else{if(X.length<$)r(g+X.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(f.indent===0)$=X.length;if(_=J,$===0&&!D.atRoot)r(g,"BAD_INDENT","Block scalar values in collections must be indented");break}g+=X.length+M.length+1}for(let J=F.length-1;J>=E;--J)if(F[J][0].length>$)E=J+1;let R="",n="",B=!1;for(let J=0;J<_;++J)R+=F[J][0].slice($)+`
80
+ `;for(let J=_;J<E;++J){let[X,M]=F[J];g+=X.length+M.length+1;let P=M[M.length-1]==="\r";if(P)M=M.slice(0,-1);if(M&&X.length<$){let s=`Block scalar lines must not be less indented than their ${f.indent?"explicit indentation indicator":"first line"}`;r(g-M.length-(P?2:1),"BAD_INDENT",s),X=""}if(w===x6.Scalar.BLOCK_LITERAL)R+=n+X.slice($)+M,n=`
81
+ `;else if(X.length>$||M[0]==="\t"){if(n===" ")n=`
82
+ `;else if(!B&&n===`
83
+ `)n=`
84
+
85
+ `;R+=n+X.slice($)+M,n=`
86
+ `,B=!0}else if(M==="")if(n===`
87
+ `)R+=`
88
+ `;else n=`
89
+ `;else R+=n+M,n=" ",B=!1}switch(f.chomp){case"-":break;case"+":for(let J=E;J<F.length;++J)R+=`
90
+ `+F[J][0].slice($);if(R[R.length-1]!==`
91
+ `)R+=`
92
+ `;break;default:R+=`
93
+ `}let C=A+f.length+u.source.length;return{value:R,type:w,comment:f.comment,range:[A,C,C]}}function wP({offset:D,props:u},r,A){if(u[0].type!=="block-scalar-header")return A(u[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:f}=u[0],w=f[0],F=0,E="",$=-1;for(let n=1;n<f.length;++n){let B=f[n];if(!E&&(B==="-"||B==="+"))E=B;else{let C=Number(B);if(!F&&C)F=C;else if($===-1)$=D+n}}if($!==-1)A($,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${f}`);let g=!1,_="",R=f.length;for(let n=1;n<u.length;++n){let B=u[n];switch(B.type){case"space":g=!0;case"newline":R+=B.source.length;break;case"comment":if(r&&!g)A(B,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");R+=B.source.length,_=B.source.substring(1);break;case"error":A(B,"UNEXPECTED_TOKEN",B.message),R+=B.source.length;break;default:{let C=`Unexpected token in block scalar header: ${B.type}`;A(B,"UNEXPECTED_TOKEN",C);let J=B.source;if(J&&typeof J==="string")R+=J.length}}}return{mode:w,indent:F,chomp:E,comment:_,length:R}}function $P(D){let u=D.split(/\n( *)/),r=u[0],A=r.match(/^( *)/),w=[A?.[1]?[A[1],r.slice(A[1].length)]:["",r]];for(let F=1;F<u.length;F+=2)w.push([u[F],u[F+1]]);return w}EP.resolveBlockScalar=FP});var e6=L((CP)=>{var a6=VD(),SP=Q2();function _P(D,u,r){let{offset:A,type:f,source:w,end:F}=D,E,$,g=(n,B,C)=>r(A+n,B,C);switch(f){case"scalar":E=a6.Scalar.PLAIN,$=RP(w,g);break;case"single-quoted-scalar":E=a6.Scalar.QUOTE_SINGLE,$=nP(w,g);break;case"double-quoted-scalar":E=a6.Scalar.QUOTE_DOUBLE,$=BP(w,g);break;default:return r(D,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${f}`),{value:"",type:null,comment:"",range:[A,A+w.length,A+w.length]}}let _=A+w.length,R=SP.resolveEnd(F,_,u,r);return{value:$,type:E,comment:R.comment,range:[A,_,R.offset]}}function RP(D,u){let r="";switch(D[0]){case"\t":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${D[0]}`;break}case"@":case"`":{r=`reserved character ${D[0]}`;break}}if(r)u(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`);return kS(D)}function nP(D,u){if(D[D.length-1]!=="'"||D.length===1)u(D.length,"MISSING_CHAR","Missing closing 'quote");return kS(D.slice(1,-1)).replace(/''/g,"'")}function kS(D){let u,r;try{u=new RegExp(`(.*?)(?<![ ])[ ]*\r?
94
94
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
95
95
  `,"sy")}catch{u=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let A=u.exec(D);if(!A)return D;let f=A[1],w=" ",F=u.lastIndex;r.lastIndex=F;while(A=r.exec(D)){if(A[1]==="")if(w===`
96
96
  `)f+=w;else w=`
97
- `;else f+=w+A[1],w=" ";F=r.lastIndex}let E=/[ \t]*(.*)/sy;return E.lastIndex=F,A=E.exec(D),f+w+(A?.[1]??"")}function lP(D,u){let r="";for(let A=1;A<D.length-1;++A){let f=D[A];if(f==="\r"&&D[A+1]===`
97
+ `;else f+=w+A[1],w=" ";F=r.lastIndex}let E=/[ \t]*(.*)/sy;return E.lastIndex=F,A=E.exec(D),f+w+(A?.[1]??"")}function BP(D,u){let r="";for(let A=1;A<D.length-1;++A){let f=D[A];if(f==="\r"&&D[A+1]===`
98
98
  `)continue;if(f===`
99
- `){let{fold:w,offset:F}=cP(D,A);r+=w,A=F}else if(f==="\\"){let w=D[++A],F=tP[w];if(F)r+=F;else if(w===`
99
+ `){let{fold:w,offset:F}=WP(D,A);r+=w,A=F}else if(f==="\\"){let w=D[++A],F=JP[w];if(F)r+=F;else if(w===`
100
100
  `){w=D[A+1];while(w===" "||w==="\t")w=D[++A+1]}else if(w==="\r"&&D[A+1]===`
101
- `){w=D[++A+1];while(w===" "||w==="\t")w=D[++A+1]}else if(w==="x"||w==="u"||w==="U"){let E={x:2,u:4,U:8}[w];r+=xP(D,A+1,E,u),A+=E}else{let E=D.substr(A-1,2);u(A-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${E}`),r+=E}}else if(f===" "||f==="\t"){let w=A,F=D[A+1];while(F===" "||F==="\t")F=D[++A+1];if(F!==`
101
+ `){w=D[++A+1];while(w===" "||w==="\t")w=D[++A+1]}else if(w==="x"||w==="u"||w==="U"){let E={x:2,u:4,U:8}[w];r+=GP(D,A+1,E,u),A+=E}else{let E=D.substr(A-1,2);u(A-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${E}`),r+=E}}else if(f===" "||f==="\t"){let w=A,F=D[A+1];while(F===" "||F==="\t")F=D[++A+1];if(F!==`
102
102
  `&&!(F==="\r"&&D[A+2]===`
103
- `))r+=A>w?D.slice(w,A+1):f}else r+=f}if(D[D.length-1]!=='"'||D.length===1)u(D.length,"MISSING_CHAR",'Missing closing "quote');return r}function cP(D,u){let r="",A=D[u+1];while(A===" "||A==="\t"||A===`
103
+ `))r+=A>w?D.slice(w,A+1):f}else r+=f}if(D[D.length-1]!=='"'||D.length===1)u(D.length,"MISSING_CHAR",'Missing closing "quote');return r}function WP(D,u){let r="",A=D[u+1];while(A===" "||A==="\t"||A===`
104
104
  `||A==="\r"){if(A==="\r"&&D[u+2]!==`
105
105
  `)break;if(A===`
106
106
  `)r+=`
107
- `;u+=1,A=D[u+1]}if(!r)r=" ";return{fold:r,offset:u}}var tP={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
108
- `,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function xP(D,u,r,A){let f=D.substr(u,r),F=f.length===r&&/^[0-9a-fA-F]+$/.test(f)?parseInt(f,16):NaN;if(isNaN(F)){let E=D.substr(u-2,r+2);return A(u-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${E}`),E}return String.fromCodePoint(F)}mP.resolveFlowScalar=oP});var S_=Q((Ai)=>{var j0=AD(),R_=ID(),aP=y6(),eP=c6();function Di(D,u,r,A){let{value:f,type:w,comment:F,range:E}=u.type==="block-scalar"?aP.resolveBlockScalar(D,u,A):eP.resolveFlowScalar(u,D.options.strict,A),$=r?D.directives.tagName(r.source,(S)=>A(r,"TAG_RESOLVE_FAILED",S)):null,g;if(D.options.stringKeys&&D.atKey)g=D.schema[j0.SCALAR];else if($)g=ui(D.schema,f,$,r,A);else if(u.type==="scalar")g=ri(D,f,u,A);else g=D.schema[j0.SCALAR];let R;try{let S=g.resolve(f,(B)=>A(r??u,"TAG_RESOLVE_FAILED",B),D.options);R=j0.isScalar(S)?S:new R_.Scalar(S)}catch(S){let B=S instanceof Error?S.message:String(S);A(r??u,"TAG_RESOLVE_FAILED",B),R=new R_.Scalar(f)}if(R.range=E,R.source=f,w)R.type=w;if($)R.tag=$;if(g.format)R.format=g.format;if(F)R.comment=F;return R}function ui(D,u,r,A,f){if(r==="!")return D[j0.SCALAR];let w=[];for(let E of D.tags)if(!E.collection&&E.tag===r)if(E.default&&E.test)w.push(E);else return E;for(let E of w)if(E.test?.test(u))return E;let F=D.knownTags[r];if(F&&!F.collection)return D.tags.push(Object.assign({},F,{default:!1,test:void 0})),F;return f(A,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),D[j0.SCALAR]}function ri({atKey:D,directives:u,schema:r},A,f,w){let F=r.tags.find((E)=>(E.default===!0||D&&E.default==="key")&&E.test?.test(A))||r[j0.SCALAR];if(r.compat){let E=r.compat.find(($)=>$.default&&$.test?.test(A))??r[j0.SCALAR];if(F.tag!==E.tag){let $=u.tagString(F.tag),g=u.tagString(E.tag),R=`Value may be parsed as either ${$} or ${g}`;w(f,"TAG_RESOLVE_FAILED",R,!0)}}return F}Ai.composeScalar=Di});var B_=Q((wi)=>{function Fi(D,u,r){if(u){r??(r=u.length);for(let A=r-1;A>=0;--A){let f=u[A];switch(f.type){case"space":case"comment":case"newline":D-=f.source.length;continue}f=u[++A];while(f?.type==="space")D+=f.source.length,f=u[++A];break}}return D}wi.emptyScalarPosition=Fi});var G_=Q((Wi)=>{var Ei=h1(),gi=AD(),_i=g_(),J_=S_(),Ri=N2(),Si=B_(),Bi={composeNode:W_,composeEmptyNode:t6};function W_(D,u,r,A){let f=D.atKey,{spaceBefore:w,comment:F,anchor:E,tag:$}=r,g,R=!0;switch(u.type){case"alias":if(g=Ji(D,u,A),E||$)A(u,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(g=J_.composeScalar(D,u,$,A),E)g.anchor=E.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(g=_i.composeCollection(Bi,D,u,r,A),E)g.anchor=E.source.substring(1)}catch(S){let B=S instanceof Error?S.message:String(S);A(u,"RESOURCE_EXHAUSTION",B)}break;default:{let S=u.type==="error"?u.message:`Unsupported token (type: ${u.type})`;A(u,"UNEXPECTED_TOKEN",S),R=!1}}if(g??(g=t6(D,u.offset,void 0,null,r,A)),E&&g.anchor==="")A(E,"BAD_ALIAS","Anchor cannot be an empty string");if(f&&D.options.stringKeys&&(!gi.isScalar(g)||typeof g.value!=="string"||g.tag&&g.tag!=="tag:yaml.org,2002:str"))A($??u,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(w)g.spaceBefore=!0;if(F)if(u.type==="scalar"&&u.source==="")g.comment=F;else g.commentBefore=F;if(D.options.keepSourceTokens&&R)g.srcToken=u;return g}function t6(D,u,r,A,{spaceBefore:f,comment:w,anchor:F,tag:E,end:$},g){let R={type:"scalar",offset:Si.emptyScalarPosition(u,r,A),indent:-1,source:""},S=J_.composeScalar(D,R,E,g);if(F){if(S.anchor=F.source.substring(1),S.anchor==="")g(F,"BAD_ALIAS","Anchor cannot be an empty string")}if(f)S.spaceBefore=!0;if(w)S.comment=w,S.range[2]=$;return S}function Ji({options:D},{offset:u,source:r,end:A},f){let w=new Ei.Alias(r.substring(1));if(w.source==="")f(u,"BAD_ALIAS","Alias cannot be an empty string");if(w.source.endsWith(":"))f(u+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let F=u+r.length,E=Ri.resolveEnd(A,F,D.strict,f);if(w.range=[u,F,E.offset],E.comment)w.comment=E.comment;return w}Wi.composeEmptyNode=t6;Wi.composeNode=W_});var H_=Q((Yi)=>{var Hi=l1(),C_=G_(),ni=N2(),Ui=t1();function Xi(D,u,{offset:r,start:A,value:f,end:w},F){let E=Object.assign({_directives:u},D),$=new Hi.Document(void 0,E),g={atKey:!1,atRoot:!0,directives:$.directives,options:$.options,schema:$.schema},R=Ui.resolveProps(A,{indicator:"doc-start",next:f??w?.[0],offset:r,onError:F,parentIndent:0,startOnNewline:!0});if(R.found){if($.directives.docStart=!0,f&&(f.type==="block-map"||f.type==="block-seq")&&!R.hasNewline)F(R.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}$.contents=f?C_.composeNode(g,f,R,F):C_.composeEmptyNode(g,R.end,A,null,R,F);let S=$.contents.range[2],B=ni.resolveEnd(w,S,!1,F);if(B.comment)$.comment=B.comment;return $.range=[r,S,B.offset],$}Yi.composeDoc=Xi});var x6=Q((Vi)=>{var Oi=yA("process"),Pi=eF(),ii=l1(),x1=c1(),n_=AD(),ki=H_(),Ii=N2();function m1(D){if(typeof D==="number")return[D,D+1];if(Array.isArray(D))return D.length===2?D:[D[0],D[1]];let{offset:u,source:r}=D;return[u,u+(typeof r==="string"?r.length:1)]}function U_(D){let u="",r=!1,A=!1;for(let f=0;f<D.length;++f){let w=D[f];switch(w[0]){case"#":u+=(u===""?"":A?`
107
+ `;u+=1,A=D[u+1]}if(!r)r=" ";return{fold:r,offset:u}}var JP={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
108
+ `,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function GP(D,u,r,A){let f=D.substr(u,r),F=f.length===r&&/^[0-9a-fA-F]+$/.test(f)?parseInt(f,16):NaN;if(isNaN(F)){let E=D.substr(u-2,r+2);return A(u-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${E}`),E}return String.fromCodePoint(F)}CP.resolveFlowScalar=_P});var VS=L((OP)=>{var z0=AD(),IS=VD(),XP=m6(),iP=e6();function UP(D,u,r,A){let{value:f,type:w,comment:F,range:E}=u.type==="block-scalar"?XP.resolveBlockScalar(D,u,A):iP.resolveFlowScalar(u,D.options.strict,A),$=r?D.directives.tagName(r.source,(R)=>A(r,"TAG_RESOLVE_FAILED",R)):null,g;if(D.options.stringKeys&&D.atKey)g=D.schema[z0.SCALAR];else if($)g=YP(D.schema,f,$,r,A);else if(u.type==="scalar")g=MP(D,f,u,A);else g=D.schema[z0.SCALAR];let _;try{let R=g.resolve(f,(n)=>A(r??u,"TAG_RESOLVE_FAILED",n),D.options);_=z0.isScalar(R)?R:new IS.Scalar(R)}catch(R){let n=R instanceof Error?R.message:String(R);A(r??u,"TAG_RESOLVE_FAILED",n),_=new IS.Scalar(f)}if(_.range=E,_.source=f,w)_.type=w;if($)_.tag=$;if(g.format)_.format=g.format;if(F)_.comment=F;return _}function YP(D,u,r,A,f){if(r==="!")return D[z0.SCALAR];let w=[];for(let E of D.tags)if(!E.collection&&E.tag===r)if(E.default&&E.test)w.push(E);else return E;for(let E of w)if(E.test?.test(u))return E;let F=D.knownTags[r];if(F&&!F.collection)return D.tags.push(Object.assign({},F,{default:!1,test:void 0})),F;return f(A,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),D[z0.SCALAR]}function MP({atKey:D,directives:u,schema:r},A,f,w){let F=r.tags.find((E)=>(E.default===!0||D&&E.default==="key")&&E.test?.test(A))||r[z0.SCALAR];if(r.compat){let E=r.compat.find(($)=>$.default&&$.test?.test(A))??r[z0.SCALAR];if(F.tag!==E.tag){let $=u.tagString(F.tag),g=u.tagString(E.tag),_=`Value may be parsed as either ${$} or ${g}`;w(f,"TAG_RESOLVE_FAILED",_,!0)}}return F}OP.composeScalar=UP});var KS=L((IP)=>{function kP(D,u,r){if(u){r??(r=u.length);for(let A=r-1;A>=0;--A){let f=u[A];switch(f.type){case"space":case"comment":case"newline":D-=f.source.length;continue}f=u[++A];while(f?.type==="space")D+=f.source.length,f=u[++A];break}}return D}IP.emptyScalarPosition=kP});var QS=L((sP)=>{var KP=hA(),hP=AD(),NP=PS(),hS=VS(),QP=Q2(),LP=KS(),qP={composeNode:NS,composeEmptyNode:Dw};function NS(D,u,r,A){let f=D.atKey,{spaceBefore:w,comment:F,anchor:E,tag:$}=r,g,_=!0;switch(u.type){case"alias":if(g=bP(D,u,A),E||$)A(u,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(g=hS.composeScalar(D,u,$,A),E)g.anchor=E.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(g=NP.composeCollection(qP,D,u,r,A),E)g.anchor=E.source.substring(1)}catch(R){let n=R instanceof Error?R.message:String(R);A(u,"RESOURCE_EXHAUSTION",n)}break;default:{let R=u.type==="error"?u.message:`Unsupported token (type: ${u.type})`;A(u,"UNEXPECTED_TOKEN",R),_=!1}}if(g??(g=Dw(D,u.offset,void 0,null,r,A)),E&&g.anchor==="")A(E,"BAD_ALIAS","Anchor cannot be an empty string");if(f&&D.options.stringKeys&&(!hP.isScalar(g)||typeof g.value!=="string"||g.tag&&g.tag!=="tag:yaml.org,2002:str"))A($??u,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(w)g.spaceBefore=!0;if(F)if(u.type==="scalar"&&u.source==="")g.comment=F;else g.commentBefore=F;if(D.options.keepSourceTokens&&_)g.srcToken=u;return g}function Dw(D,u,r,A,{spaceBefore:f,comment:w,anchor:F,tag:E,end:$},g){let _={type:"scalar",offset:LP.emptyScalarPosition(u,r,A),indent:-1,source:""},R=hS.composeScalar(D,_,E,g);if(F){if(R.anchor=F.source.substring(1),R.anchor==="")g(F,"BAD_ALIAS","Anchor cannot be an empty string")}if(f)R.spaceBefore=!0;if(w)R.comment=w,R.range[2]=$;return R}function bP({options:D},{offset:u,source:r,end:A},f){let w=new KP.Alias(r.substring(1));if(w.source==="")f(u,"BAD_ALIAS","Alias cannot be an empty string");if(w.source.endsWith(":"))f(u+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let F=u+r.length,E=QP.resolveEnd(A,F,D.strict,f);if(w.range=[u,F,E.offset],E.comment)w.comment=E.comment;return w}sP.composeEmptyNode=Dw;sP.composeNode=NS});var qS=L((dP)=>{var TP=yA(),LS=QS(),vP=Q2(),ZP=tA();function oP(D,u,{offset:r,start:A,value:f,end:w},F){let E=Object.assign({_directives:u},D),$=new TP.Document(void 0,E),g={atKey:!1,atRoot:!0,directives:$.directives,options:$.options,schema:$.schema},_=ZP.resolveProps(A,{indicator:"doc-start",next:f??w?.[0],offset:r,onError:F,parentIndent:0,startOnNewline:!0});if(_.found){if($.directives.docStart=!0,f&&(f.type==="block-map"||f.type==="block-seq")&&!_.hasNewline)F(_.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}$.contents=f?LS.composeNode(g,f,_,F):LS.composeEmptyNode(g,_.end,A,null,_,F);let R=$.contents.range[2],n=vP.resolveEnd(w,R,!1,F);if(n.comment)$.comment=n.comment;return $.range=[r,R,n.offset],$}dP.composeDoc=oP});var uw=L((mP)=>{var yP=p1("process"),cP=F6(),tP=yA(),pA=cA(),bS=AD(),pP=qS(),xP=Q2();function xA(D){if(typeof D==="number")return[D,D+1];if(Array.isArray(D))return D.length===2?D:[D[0],D[1]];let{offset:u,source:r}=D;return[u,u+(typeof r==="string"?r.length:1)]}function sS(D){let u="",r=!1,A=!1;for(let f=0;f<D.length;++f){let w=D[f];switch(w[0]){case"#":u+=(u===""?"":A?`
109
109
 
110
110
  `:`
111
- `)+(w.substring(1)||" "),r=!0,A=!1;break;case"%":if(D[f+1]?.[0]!=="#")f+=1;r=!1;break;default:if(!r)A=!0;r=!1}}return{comment:u,afterEmptyLine:A}}class X_{constructor(D={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(u,r,A,f)=>{let w=m1(u);if(f)this.warnings.push(new x1.YAMLWarning(w,r,A));else this.errors.push(new x1.YAMLParseError(w,r,A))},this.directives=new Pi.Directives({version:D.version||"1.2"}),this.options=D}decorate(D,u){let{comment:r,afterEmptyLine:A}=U_(this.prelude);if(r){let f=D.contents;if(u)D.comment=D.comment?`${D.comment}
112
- ${r}`:r;else if(A||D.directives.docStart||!f)D.commentBefore=r;else if(n_.isCollection(f)&&!f.flow&&f.items.length>0){let w=f.items[0];if(n_.isPair(w))w=w.key;let F=w.commentBefore;w.commentBefore=F?`${r}
111
+ `)+(w.substring(1)||" "),r=!0,A=!1;break;case"%":if(D[f+1]?.[0]!=="#")f+=1;r=!1;break;default:if(!r)A=!0;r=!1}}return{comment:u,afterEmptyLine:A}}class zS{constructor(D={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(u,r,A,f)=>{let w=xA(u);if(f)this.warnings.push(new pA.YAMLWarning(w,r,A));else this.errors.push(new pA.YAMLParseError(w,r,A))},this.directives=new cP.Directives({version:D.version||"1.2"}),this.options=D}decorate(D,u){let{comment:r,afterEmptyLine:A}=sS(this.prelude);if(r){let f=D.contents;if(u)D.comment=D.comment?`${D.comment}
112
+ ${r}`:r;else if(A||D.directives.docStart||!f)D.commentBefore=r;else if(bS.isCollection(f)&&!f.flow&&f.items.length>0){let w=f.items[0];if(bS.isPair(w))w=w.key;let F=w.commentBefore;w.commentBefore=F?`${r}
113
113
  ${F}`:r}else{let w=f.commentBefore;f.commentBefore=w?`${r}
114
- ${w}`:r}}if(u)Array.prototype.push.apply(D.errors,this.errors),Array.prototype.push.apply(D.warnings,this.warnings);else D.errors=this.errors,D.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:U_(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(D,u=!1,r=-1){for(let A of D)yield*this.next(A);yield*this.end(u,r)}*next(D){if(Oi.env.LOG_STREAM)console.dir(D,{depth:null});switch(D.type){case"directive":this.directives.add(D.source,(u,r,A)=>{let f=m1(D);f[0]+=u,this.onError(f,"BAD_DIRECTIVE",r,A)}),this.prelude.push(D.source),this.atDirectives=!0;break;case"document":{let u=ki.composeDoc(this.options,this.directives,D,this.onError);if(this.atDirectives&&!u.directives.docStart)this.onError(D,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(u,!1),this.doc)yield this.doc;this.doc=u,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(D.source);break;case"error":{let u=D.source?`${D.message}: ${JSON.stringify(D.source)}`:D.message,r=new x1.YAMLParseError(m1(D),"UNEXPECTED_TOKEN",u);if(this.atDirectives||!this.doc)this.errors.push(r);else this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){this.errors.push(new x1.YAMLParseError(m1(D),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let u=Ii.resolveEnd(D.end,D.offset+D.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),u.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
115
- ${u.comment}`:u.comment}this.doc.range[2]=u.offset;break}default:this.errors.push(new x1.YAMLParseError(m1(D),"UNEXPECTED_TOKEN",`Unsupported token ${D.type}`))}}*end(D=!1,u=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(D){let r=Object.assign({_directives:this.directives},this.options),A=new ii.Document(void 0,r);if(this.atDirectives)this.onError(u,"MISSING_CHAR","Missing directives-end indicator line");A.range=[0,u,u],this.decorate(A,!1),yield A}}}Vi.Composer=X_});var O_=Q((ji)=>{var hi=y6(),Ni=c6(),Qi=c1(),Y_=q1();function Li(D,u=!0,r){if(D){let A=(f,w,F)=>{let E=typeof f==="number"?f:Array.isArray(f)?f[0]:f.offset;if(r)r(E,w,F);else throw new Qi.YAMLParseError([E,E+1],w,F)};switch(D.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ni.resolveFlowScalar(D,u,A);case"block-scalar":return hi.resolveBlockScalar({options:{strict:u}},D,A)}}return null}function qi(D,u){let{implicitKey:r=!1,indent:A,inFlow:f=!1,offset:w=-1,type:F="PLAIN"}=u,E=Y_.stringifyString({type:F,value:D},{implicitKey:r,indent:A>0?" ".repeat(A):"",inFlow:f,options:{blockQuote:!0,lineWidth:-1}}),$=u.end??[{type:"newline",offset:-1,indent:A,source:`
114
+ ${w}`:r}}if(u)Array.prototype.push.apply(D.errors,this.errors),Array.prototype.push.apply(D.warnings,this.warnings);else D.errors=this.errors,D.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:sS(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(D,u=!1,r=-1){for(let A of D)yield*this.next(A);yield*this.end(u,r)}*next(D){if(yP.env.LOG_STREAM)console.dir(D,{depth:null});switch(D.type){case"directive":this.directives.add(D.source,(u,r,A)=>{let f=xA(D);f[0]+=u,this.onError(f,"BAD_DIRECTIVE",r,A)}),this.prelude.push(D.source),this.atDirectives=!0;break;case"document":{let u=pP.composeDoc(this.options,this.directives,D,this.onError);if(this.atDirectives&&!u.directives.docStart)this.onError(D,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(u,!1),this.doc)yield this.doc;this.doc=u,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(D.source);break;case"error":{let u=D.source?`${D.message}: ${JSON.stringify(D.source)}`:D.message,r=new pA.YAMLParseError(xA(D),"UNEXPECTED_TOKEN",u);if(this.atDirectives||!this.doc)this.errors.push(r);else this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){this.errors.push(new pA.YAMLParseError(xA(D),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let u=xP.resolveEnd(D.end,D.offset+D.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),u.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
115
+ ${u.comment}`:u.comment}this.doc.range[2]=u.offset;break}default:this.errors.push(new pA.YAMLParseError(xA(D),"UNEXPECTED_TOKEN",`Unsupported token ${D.type}`))}}*end(D=!1,u=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(D){let r=Object.assign({_directives:this.directives},this.options),A=new tP.Document(void 0,r);if(this.atDirectives)this.onError(u,"MISSING_CHAR","Missing directives-end indicator line");A.range=[0,u,u],this.decorate(A,!1),yield A}}}mP.Composer=zS});var vS=L((wk)=>{var eP=m6(),Dk=e6(),uk=cA(),jS=qA();function rk(D,u=!0,r){if(D){let A=(f,w,F)=>{let E=typeof f==="number"?f:Array.isArray(f)?f[0]:f.offset;if(r)r(E,w,F);else throw new uk.YAMLParseError([E,E+1],w,F)};switch(D.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Dk.resolveFlowScalar(D,u,A);case"block-scalar":return eP.resolveBlockScalar({options:{strict:u}},D,A)}}return null}function Ak(D,u){let{implicitKey:r=!1,indent:A,inFlow:f=!1,offset:w=-1,type:F="PLAIN"}=u,E=jS.stringifyString({type:F,value:D},{implicitKey:r,indent:A>0?" ".repeat(A):"",inFlow:f,options:{blockQuote:!0,lineWidth:-1}}),$=u.end??[{type:"newline",offset:-1,indent:A,source:`
116
116
  `}];switch(E[0]){case"|":case">":{let g=E.indexOf(`
117
- `),R=E.substring(0,g),S=E.substring(g+1)+`
118
- `,B=[{type:"block-scalar-header",offset:w,indent:A,source:R}];if(!M_(B,$))B.push({type:"newline",offset:-1,indent:A,source:`
119
- `});return{type:"block-scalar",offset:w,indent:A,props:B,source:S}}case'"':return{type:"double-quoted-scalar",offset:w,indent:A,source:E,end:$};case"'":return{type:"single-quoted-scalar",offset:w,indent:A,source:E,end:$};default:return{type:"scalar",offset:w,indent:A,source:E,end:$}}}function bi(D,u,r={}){let{afterKey:A=!1,implicitKey:f=!1,inFlow:w=!1,type:F}=r,E="indent"in D?D.indent:null;if(A&&typeof E==="number")E+=2;if(!F)switch(D.type){case"single-quoted-scalar":F="QUOTE_SINGLE";break;case"double-quoted-scalar":F="QUOTE_DOUBLE";break;case"block-scalar":{let g=D.props[0];if(g.type!=="block-scalar-header")throw Error("Invalid block scalar header");F=g.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:F="PLAIN"}let $=Y_.stringifyString({type:F,value:u},{implicitKey:f||E===null,indent:E!==null&&E>0?" ".repeat(E):"",inFlow:w,options:{blockQuote:!0,lineWidth:-1}});switch($[0]){case"|":case">":zi(D,$);break;case'"':m6(D,$,"double-quoted-scalar");break;case"'":m6(D,$,"single-quoted-scalar");break;default:m6(D,$,"scalar")}}function zi(D,u){let r=u.indexOf(`
117
+ `),_=E.substring(0,g),R=E.substring(g+1)+`
118
+ `,n=[{type:"block-scalar-header",offset:w,indent:A,source:_}];if(!TS(n,$))n.push({type:"newline",offset:-1,indent:A,source:`
119
+ `});return{type:"block-scalar",offset:w,indent:A,props:n,source:R}}case'"':return{type:"double-quoted-scalar",offset:w,indent:A,source:E,end:$};case"'":return{type:"single-quoted-scalar",offset:w,indent:A,source:E,end:$};default:return{type:"scalar",offset:w,indent:A,source:E,end:$}}}function fk(D,u,r={}){let{afterKey:A=!1,implicitKey:f=!1,inFlow:w=!1,type:F}=r,E="indent"in D?D.indent:null;if(A&&typeof E==="number")E+=2;if(!F)switch(D.type){case"single-quoted-scalar":F="QUOTE_SINGLE";break;case"double-quoted-scalar":F="QUOTE_DOUBLE";break;case"block-scalar":{let g=D.props[0];if(g.type!=="block-scalar-header")throw Error("Invalid block scalar header");F=g.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:F="PLAIN"}let $=jS.stringifyString({type:F,value:u},{implicitKey:f||E===null,indent:E!==null&&E>0?" ".repeat(E):"",inFlow:w,options:{blockQuote:!0,lineWidth:-1}});switch($[0]){case"|":case">":Fk(D,$);break;case'"':rw(D,$,"double-quoted-scalar");break;case"'":rw(D,$,"single-quoted-scalar");break;default:rw(D,$,"scalar")}}function Fk(D,u){let r=u.indexOf(`
120
120
  `),A=u.substring(0,r),f=u.substring(r+1)+`
121
- `;if(D.type==="block-scalar"){let w=D.props[0];if(w.type!=="block-scalar-header")throw Error("Invalid block scalar header");w.source=A,D.source=f}else{let{offset:w}=D,F="indent"in D?D.indent:-1,E=[{type:"block-scalar-header",offset:w,indent:F,source:A}];if(!M_(E,"end"in D?D.end:void 0))E.push({type:"newline",offset:-1,indent:F,source:`
122
- `});for(let $ of Object.keys(D))if($!=="type"&&$!=="offset")delete D[$];Object.assign(D,{type:"block-scalar",indent:F,props:E,source:f})}}function M_(D,u){if(u)for(let r of u)switch(r.type){case"space":case"comment":D.push(r);break;case"newline":return D.push(r),!0}return!1}function m6(D,u,r){switch(D.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":D.type=r,D.source=u;break;case"block-scalar":{let A=D.props.slice(1),f=u.length;if(D.props[0].type==="block-scalar-header")f-=D.props[0].source.length;for(let w of A)w.offset+=f;delete D.props,Object.assign(D,{type:r,source:u,end:A});break}case"block-map":case"block-seq":{let f={type:"newline",offset:D.offset+u.length,indent:D.indent,source:`
123
- `};delete D.items,Object.assign(D,{type:r,source:u,end:[f]});break}default:{let A="indent"in D?D.indent:-1,f="end"in D&&Array.isArray(D.end)?D.end.filter((w)=>w.type==="space"||w.type==="comment"||w.type==="newline"):[];for(let w of Object.keys(D))if(w!=="type"&&w!=="offset")delete D[w];Object.assign(D,{type:r,indent:A,source:u,end:f})}}}ji.createScalarToken=qi;ji.resolveAsScalar=Li;ji.setScalarValue=bi});var P_=Q((oi)=>{var Zi=(D)=>("type"in D)?Sf(D):Rf(D);function Sf(D){switch(D.type){case"block-scalar":{let u="";for(let r of D.props)u+=Sf(r);return u+D.source}case"block-map":case"block-seq":{let u="";for(let r of D.items)u+=Rf(r);return u}case"flow-collection":{let u=D.start.source;for(let r of D.items)u+=Rf(r);for(let r of D.end)u+=r.source;return u}case"document":{let u=Rf(D);if(D.end)for(let r of D.end)u+=r.source;return u}default:{let u=D.source;if("end"in D&&D.end)for(let r of D.end)u+=r.source;return u}}}function Rf({start:D,key:u,sep:r,value:A}){let f="";for(let w of D)f+=w.source;if(u)f+=Sf(u);if(r)for(let w of r)f+=w.source;if(A)f+=Sf(A);return f}oi.stringify=Zi});var I_=Q((li)=>{var p6=Symbol("break visit"),yi=Symbol("skip children"),i_=Symbol("remove item");function T0(D,u){if("type"in D&&D.type==="document")D={start:D.start,value:D.value};k_(Object.freeze([]),D,u)}T0.BREAK=p6;T0.SKIP=yi;T0.REMOVE=i_;T0.itemAtPath=(D,u)=>{let r=D;for(let[A,f]of u){let w=r?.[A];if(w&&"items"in w)r=w.items[f];else return}return r};T0.parentCollection=(D,u)=>{let r=T0.itemAtPath(D,u.slice(0,-1)),A=u[u.length-1][0],f=r?.[A];if(f&&"items"in f)return f;throw Error("Parent collection not found")};function k_(D,u,r){let A=r(u,D);if(typeof A==="symbol")return A;for(let f of["key","value"]){let w=u[f];if(w&&"items"in w){for(let F=0;F<w.items.length;++F){let E=k_(Object.freeze(D.concat([[f,F]])),w.items[F],r);if(typeof E==="number")F=E-1;else if(E===p6)return p6;else if(E===i_)w.items.splice(F,1),F-=1}if(typeof A==="function"&&f==="key")A=A(u,D)}}return typeof A==="function"?A(u,D):A}li.visit=T0});var Bf=Q((Dk)=>{var a6=O_(),ti=P_(),xi=I_(),e6="\uFEFF",D9="\x02",u9="\x18",r9="\x1F",mi=(D)=>!!D&&("items"in D),pi=(D)=>!!D&&(D.type==="scalar"||D.type==="single-quoted-scalar"||D.type==="double-quoted-scalar"||D.type==="block-scalar");function ai(D){switch(D){case e6:return"<BOM>";case D9:return"<DOC>";case u9:return"<FLOW_END>";case r9:return"<SCALAR>";default:return JSON.stringify(D)}}function ei(D){switch(D){case e6:return"byte-order-mark";case D9:return"doc-mode";case u9:return"flow-error-end";case r9:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
121
+ `;if(D.type==="block-scalar"){let w=D.props[0];if(w.type!=="block-scalar-header")throw Error("Invalid block scalar header");w.source=A,D.source=f}else{let{offset:w}=D,F="indent"in D?D.indent:-1,E=[{type:"block-scalar-header",offset:w,indent:F,source:A}];if(!TS(E,"end"in D?D.end:void 0))E.push({type:"newline",offset:-1,indent:F,source:`
122
+ `});for(let $ of Object.keys(D))if($!=="type"&&$!=="offset")delete D[$];Object.assign(D,{type:"block-scalar",indent:F,props:E,source:f})}}function TS(D,u){if(u)for(let r of u)switch(r.type){case"space":case"comment":D.push(r);break;case"newline":return D.push(r),!0}return!1}function rw(D,u,r){switch(D.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":D.type=r,D.source=u;break;case"block-scalar":{let A=D.props.slice(1),f=u.length;if(D.props[0].type==="block-scalar-header")f-=D.props[0].source.length;for(let w of A)w.offset+=f;delete D.props,Object.assign(D,{type:r,source:u,end:A});break}case"block-map":case"block-seq":{let f={type:"newline",offset:D.offset+u.length,indent:D.indent,source:`
123
+ `};delete D.items,Object.assign(D,{type:r,source:u,end:[f]});break}default:{let A="indent"in D?D.indent:-1,f="end"in D&&Array.isArray(D.end)?D.end.filter((w)=>w.type==="space"||w.type==="comment"||w.type==="newline"):[];for(let w of Object.keys(D))if(w!=="type"&&w!=="offset")delete D[w];Object.assign(D,{type:r,indent:A,source:u,end:f})}}}wk.createScalarToken=Ak;wk.resolveAsScalar=rk;wk.setScalarValue=fk});var ZS=L((_k)=>{var Sk=(D)=>("type"in D)?Jf(D):Wf(D);function Jf(D){switch(D.type){case"block-scalar":{let u="";for(let r of D.props)u+=Jf(r);return u+D.source}case"block-map":case"block-seq":{let u="";for(let r of D.items)u+=Wf(r);return u}case"flow-collection":{let u=D.start.source;for(let r of D.items)u+=Wf(r);for(let r of D.end)u+=r.source;return u}case"document":{let u=Wf(D);if(D.end)for(let r of D.end)u+=r.source;return u}default:{let u=D.source;if("end"in D&&D.end)for(let r of D.end)u+=r.source;return u}}}function Wf({start:D,key:u,sep:r,value:A}){let f="";for(let w of D)f+=w.source;if(u)f+=Jf(u);if(r)for(let w of r)f+=w.source;if(A)f+=Jf(A);return f}_k.stringify=Sk});var lS=L((Bk)=>{var Aw=Symbol("break visit"),nk=Symbol("skip children"),oS=Symbol("remove item");function j0(D,u){if("type"in D&&D.type==="document")D={start:D.start,value:D.value};dS(Object.freeze([]),D,u)}j0.BREAK=Aw;j0.SKIP=nk;j0.REMOVE=oS;j0.itemAtPath=(D,u)=>{let r=D;for(let[A,f]of u){let w=r?.[A];if(w&&"items"in w)r=w.items[f];else return}return r};j0.parentCollection=(D,u)=>{let r=j0.itemAtPath(D,u.slice(0,-1)),A=u[u.length-1][0],f=r?.[A];if(f&&"items"in f)return f;throw Error("Parent collection not found")};function dS(D,u,r){let A=r(u,D);if(typeof A==="symbol")return A;for(let f of["key","value"]){let w=u[f];if(w&&"items"in w){for(let F=0;F<w.items.length;++F){let E=dS(Object.freeze(D.concat([[f,F]])),w.items[F],r);if(typeof E==="number")F=E-1;else if(E===Aw)return Aw;else if(E===oS)w.items.splice(F,1),F-=1}if(typeof A==="function"&&f==="key")A=A(u,D)}}return typeof A==="function"?A(u,D):A}Bk.visit=j0});var Gf=L((Uk)=>{var fw=vS(),Jk=ZS(),Gk=lS(),Fw="\uFEFF",ww="\x02",$w="\x18",Ew="\x1F",Ck=(D)=>!!D&&("items"in D),Hk=(D)=>!!D&&(D.type==="scalar"||D.type==="single-quoted-scalar"||D.type==="double-quoted-scalar"||D.type==="block-scalar");function Xk(D){switch(D){case Fw:return"<BOM>";case ww:return"<DOC>";case $w:return"<FLOW_END>";case Ew:return"<SCALAR>";default:return JSON.stringify(D)}}function ik(D){switch(D){case Fw:return"byte-order-mark";case ww:return"doc-mode";case $w:return"flow-error-end";case Ew:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
124
124
  `:case`\r
125
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(D[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Dk.createScalarToken=a6.createScalarToken;Dk.resolveAsScalar=a6.resolveAsScalar;Dk.setScalarValue=a6.setScalarValue;Dk.stringify=ti.stringify;Dk.visit=xi.visit;Dk.BOM=e6;Dk.DOCUMENT=D9;Dk.FLOW_END=u9;Dk.SCALAR=r9;Dk.isCollection=mi;Dk.isScalar=pi;Dk.prettyToken=ai;Dk.tokenType=ei});var f9=Q((Gk)=>{var p1=Bf();function du(D){switch(D){case void 0:case" ":case`
126
- `:case"\r":case"\t":return!0;default:return!1}}var V_=new Set("0123456789ABCDEFabcdef"),Jk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Jf=new Set(",[]{}"),Wk=new Set(` ,[]{}
127
- \r `),A9=(D)=>!D||Wk.has(D);class K_{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(D,u=!1){if(D){if(typeof D!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+D:D,this.lineEndPos=null}this.atEnd=!u;let r=this.next??"stream";while(r&&(u||this.hasChars(1)))r=yield*this.parseNext(r)}atLineEnd(){let D=this.pos,u=this.buffer[D];while(u===" "||u==="\t")u=this.buffer[++D];if(!u||u==="#"||u===`
125
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(D[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Uk.createScalarToken=fw.createScalarToken;Uk.resolveAsScalar=fw.resolveAsScalar;Uk.setScalarValue=fw.setScalarValue;Uk.stringify=Jk.stringify;Uk.visit=Gk.visit;Uk.BOM=Fw;Uk.DOCUMENT=ww;Uk.FLOW_END=$w;Uk.SCALAR=Ew;Uk.isCollection=Ck;Uk.isScalar=Hk;Uk.prettyToken=Xk;Uk.tokenType=ik});var Sw=L((zk)=>{var mA=Gf();function yu(D){switch(D){case void 0:case" ":case`
126
+ `:case"\r":case"\t":return!0;default:return!1}}var yS=new Set("0123456789ABCDEFabcdef"),bk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Cf=new Set(",[]{}"),sk=new Set(` ,[]{}
127
+ \r `),gw=(D)=>!D||sk.has(D);class cS{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(D,u=!1){if(D){if(typeof D!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+D:D,this.lineEndPos=null}this.atEnd=!u;let r=this.next??"stream";while(r&&(u||this.hasChars(1)))r=yield*this.parseNext(r)}atLineEnd(){let D=this.pos,u=this.buffer[D];while(u===" "||u==="\t")u=this.buffer[++D];if(!u||u==="#"||u===`
128
128
  `)return!0;if(u==="\r")return this.buffer[D+1]===`
129
129
  `;return!1}charAt(D){return this.buffer[this.pos+D]}continueScalar(D){let u=this.buffer[D];if(this.indentNext>0){let r=0;while(u===" ")u=this.buffer[++r+D];if(u==="\r"){let A=this.buffer[r+D+1];if(A===`
130
130
  `||!A&&!this.atEnd)return D+r+1}return u===`
131
- `||r>=this.indentNext||!u&&!this.atEnd?D+r:-1}if(u==="-"||u==="."){let r=this.buffer.substr(D,3);if((r==="---"||r==="...")&&du(this.buffer[D+3]))return-1}return D}getLine(){let D=this.lineEndPos;if(typeof D!=="number"||D!==-1&&D<this.pos)D=this.buffer.indexOf(`
132
- `,this.pos),this.lineEndPos=D;if(D===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[D-1]==="\r")D-=1;return this.buffer.substring(this.pos,D)}hasChars(D){return this.pos+D<=this.buffer.length}setNext(D){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=D,null}peek(D){return this.buffer.substr(this.pos,D)}*parseNext(D){switch(D){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let D=this.getLine();if(D===null)return this.setNext("stream");if(D[0]===p1.BOM)yield*this.pushCount(1),D=D.substring(1);if(D[0]==="%"){let u=D.length,r=D.indexOf("#");while(r!==-1){let f=D[r-1];if(f===" "||f==="\t"){u=r-1;break}else r=D.indexOf("#",r+1)}while(!0){let f=D[u-1];if(f===" "||f==="\t")u-=1;else break}let A=(yield*this.pushCount(u))+(yield*this.pushSpaces(!0));return yield*this.pushCount(D.length-A),this.pushNewline(),"stream"}if(this.atLineEnd()){let u=yield*this.pushSpaces(!0);return yield*this.pushCount(D.length-u),yield*this.pushNewline(),"stream"}return yield p1.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let D=this.charAt(0);if(!D&&!this.atEnd)return this.setNext("line-start");if(D==="-"||D==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let u=this.peek(3);if((u==="---"||u==="...")&&du(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,u==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!du(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[D,u]=this.peek(2);if(!u&&!this.atEnd)return this.setNext("block-start");if((D==="-"||D==="?"||D===":")&&du(u)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let D=this.getLine();if(D===null)return this.setNext("doc");let u=yield*this.pushIndicators();switch(D[u]){case"#":yield*this.pushCount(D.length-u);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(A9),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return u+=yield*this.parseBlockScalarHeader(),u+=yield*this.pushSpaces(!0),yield*this.pushCount(D.length-u),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let D,u,r=-1;do{if(D=yield*this.pushNewline(),D>0)u=yield*this.pushSpaces(!1),this.indentValue=r=u;else u=0;u+=yield*this.pushSpaces(!0)}while(D+u>0);let A=this.getLine();if(A===null)return this.setNext("flow");if(r!==-1&&r<this.indentNext&&A[0]!=="#"||r===0&&(A.startsWith("---")||A.startsWith("..."))&&du(A[3])){if(!(r===this.indentNext-1&&this.flowLevel===1&&(A[0]==="]"||A[0]==="}")))return this.flowLevel=0,yield p1.FLOW_END,yield*this.parseLineStart()}let f=0;while(A[f]===",")f+=yield*this.pushCount(1),f+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(f+=yield*this.pushIndicators(),A[f]){case void 0:return"flow";case"#":return yield*this.pushCount(A.length-f),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(A9),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let w=this.charAt(1);if(this.flowKey||du(w)||w===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let D=this.charAt(0),u=this.buffer.indexOf(D,this.pos+1);if(D==="'")while(u!==-1&&this.buffer[u+1]==="'")u=this.buffer.indexOf("'",u+2);else while(u!==-1){let f=0;while(this.buffer[u-1-f]==="\\")f+=1;if(f%2===0)break;u=this.buffer.indexOf('"',u+1)}let r=this.buffer.substring(0,u),A=r.indexOf(`
131
+ `||r>=this.indentNext||!u&&!this.atEnd?D+r:-1}if(u==="-"||u==="."){let r=this.buffer.substr(D,3);if((r==="---"||r==="...")&&yu(this.buffer[D+3]))return-1}return D}getLine(){let D=this.lineEndPos;if(typeof D!=="number"||D!==-1&&D<this.pos)D=this.buffer.indexOf(`
132
+ `,this.pos),this.lineEndPos=D;if(D===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[D-1]==="\r")D-=1;return this.buffer.substring(this.pos,D)}hasChars(D){return this.pos+D<=this.buffer.length}setNext(D){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=D,null}peek(D){return this.buffer.substr(this.pos,D)}*parseNext(D){switch(D){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let D=this.getLine();if(D===null)return this.setNext("stream");if(D[0]===mA.BOM)yield*this.pushCount(1),D=D.substring(1);if(D[0]==="%"){let u=D.length,r=D.indexOf("#");while(r!==-1){let f=D[r-1];if(f===" "||f==="\t"){u=r-1;break}else r=D.indexOf("#",r+1)}while(!0){let f=D[u-1];if(f===" "||f==="\t")u-=1;else break}let A=(yield*this.pushCount(u))+(yield*this.pushSpaces(!0));return yield*this.pushCount(D.length-A),this.pushNewline(),"stream"}if(this.atLineEnd()){let u=yield*this.pushSpaces(!0);return yield*this.pushCount(D.length-u),yield*this.pushNewline(),"stream"}return yield mA.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let D=this.charAt(0);if(!D&&!this.atEnd)return this.setNext("line-start");if(D==="-"||D==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let u=this.peek(3);if((u==="---"||u==="...")&&yu(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,u==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!yu(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[D,u]=this.peek(2);if(!u&&!this.atEnd)return this.setNext("block-start");if((D==="-"||D==="?"||D===":")&&yu(u)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let D=this.getLine();if(D===null)return this.setNext("doc");let u=yield*this.pushIndicators();switch(D[u]){case"#":yield*this.pushCount(D.length-u);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(gw),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return u+=yield*this.parseBlockScalarHeader(),u+=yield*this.pushSpaces(!0),yield*this.pushCount(D.length-u),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let D,u,r=-1;do{if(D=yield*this.pushNewline(),D>0)u=yield*this.pushSpaces(!1),this.indentValue=r=u;else u=0;u+=yield*this.pushSpaces(!0)}while(D+u>0);let A=this.getLine();if(A===null)return this.setNext("flow");if(r!==-1&&r<this.indentNext&&A[0]!=="#"||r===0&&(A.startsWith("---")||A.startsWith("..."))&&yu(A[3])){if(!(r===this.indentNext-1&&this.flowLevel===1&&(A[0]==="]"||A[0]==="}")))return this.flowLevel=0,yield mA.FLOW_END,yield*this.parseLineStart()}let f=0;while(A[f]===",")f+=yield*this.pushCount(1),f+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(f+=yield*this.pushIndicators(),A[f]){case void 0:return"flow";case"#":return yield*this.pushCount(A.length-f),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(gw),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let w=this.charAt(1);if(this.flowKey||yu(w)||w===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let D=this.charAt(0),u=this.buffer.indexOf(D,this.pos+1);if(D==="'")while(u!==-1&&this.buffer[u+1]==="'")u=this.buffer.indexOf("'",u+2);else while(u!==-1){let f=0;while(this.buffer[u-1-f]==="\\")f+=1;if(f%2===0)break;u=this.buffer.indexOf('"',u+1)}let r=this.buffer.substring(0,u),A=r.indexOf(`
133
133
  `,this.pos);if(A!==-1){while(A!==-1){let f=this.continueScalar(A+1);if(f===-1)break;A=r.indexOf(`
134
- `,f)}if(A!==-1)u=A-(r[A-1]==="\r"?2:1)}if(u===-1){if(!this.atEnd)return this.setNext("quoted-scalar");u=this.buffer.length}return yield*this.pushToIndex(u+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let D=this.pos;while(!0){let u=this.buffer[++D];if(u==="+")this.blockScalarKeep=!0;else if(u>"0"&&u<="9")this.blockScalarIndent=Number(u)-1;else if(u!=="-")break}return yield*this.pushUntil((u)=>du(u)||u==="#")}*parseBlockScalar(){let D=this.pos-1,u=0,r;D:for(let f=this.pos;r=this.buffer[f];++f)switch(r){case" ":u+=1;break;case`
134
+ `,f)}if(A!==-1)u=A-(r[A-1]==="\r"?2:1)}if(u===-1){if(!this.atEnd)return this.setNext("quoted-scalar");u=this.buffer.length}return yield*this.pushToIndex(u+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let D=this.pos;while(!0){let u=this.buffer[++D];if(u==="+")this.blockScalarKeep=!0;else if(u>"0"&&u<="9")this.blockScalarIndent=Number(u)-1;else if(u!=="-")break}return yield*this.pushUntil((u)=>yu(u)||u==="#")}*parseBlockScalar(){let D=this.pos-1,u=0,r;D:for(let f=this.pos;r=this.buffer[f];++f)switch(r){case" ":u+=1;break;case`
135
135
  `:D=f,u=0;break;case"\r":{let w=this.buffer[f+1];if(!w&&!this.atEnd)return this.setNext("block-scalar");if(w===`
136
136
  `)break}default:break D}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(u>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=u;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let f=this.continueScalar(D+1);if(f===-1)break;D=this.buffer.indexOf(`
137
137
  `,f)}while(D!==-1);if(D===-1){if(!this.atEnd)return this.setNext("block-scalar");D=this.buffer.length}}let A=D+1;r=this.buffer[A];while(r===" ")r=this.buffer[++A];if(r==="\t"){while(r==="\t"||r===" "||r==="\r"||r===`
138
138
  `)r=this.buffer[++A];D=A-1}else if(!this.blockScalarKeep)do{let f=D-1,w=this.buffer[f];if(w==="\r")w=this.buffer[--f];let F=f;while(w===" ")w=this.buffer[--f];if(w===`
139
- `&&f>=this.pos&&f+1+u>F)D=f;else break}while(!0);return yield p1.SCALAR,yield*this.pushToIndex(D+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let D=this.flowLevel>0,u=this.pos-1,r=this.pos-1,A;while(A=this.buffer[++r])if(A===":"){let f=this.buffer[r+1];if(du(f)||D&&Jf.has(f))break;u=r}else if(du(A)){let f=this.buffer[r+1];if(A==="\r")if(f===`
139
+ `&&f>=this.pos&&f+1+u>F)D=f;else break}while(!0);return yield mA.SCALAR,yield*this.pushToIndex(D+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let D=this.flowLevel>0,u=this.pos-1,r=this.pos-1,A;while(A=this.buffer[++r])if(A===":"){let f=this.buffer[r+1];if(yu(f)||D&&Cf.has(f))break;u=r}else if(yu(A)){let f=this.buffer[r+1];if(A==="\r")if(f===`
140
140
  `)r+=1,A=`
141
- `,f=this.buffer[r+1];else u=r;if(f==="#"||D&&Jf.has(f))break;if(A===`
142
- `){let w=this.continueScalar(r+1);if(w===-1)break;r=Math.max(r,w-2)}}else{if(D&&Jf.has(A))break;u=r}if(!A&&!this.atEnd)return this.setNext("plain-scalar");return yield p1.SCALAR,yield*this.pushToIndex(u+1,!0),D?"flow":"doc"}*pushCount(D){if(D>0)return yield this.buffer.substr(this.pos,D),this.pos+=D,D;return 0}*pushToIndex(D,u){let r=this.buffer.slice(this.pos,D);if(r)return yield r,this.pos+=r.length,r.length;else if(u)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(A9))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let D=this.flowLevel>0,u=this.charAt(1);if(du(u)||D&&Jf.has(u)){if(!D)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;return(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let D=this.pos+2,u=this.buffer[D];while(!du(u)&&u!==">")u=this.buffer[++D];return yield*this.pushToIndex(u===">"?D+1:D,!1)}else{let D=this.pos+1,u=this.buffer[D];while(u)if(Jk.has(u))u=this.buffer[++D];else if(u==="%"&&V_.has(this.buffer[D+1])&&V_.has(this.buffer[D+2]))u=this.buffer[D+=3];else break;return yield*this.pushToIndex(D,!1)}}*pushNewline(){let D=this.buffer[this.pos];if(D===`
141
+ `,f=this.buffer[r+1];else u=r;if(f==="#"||D&&Cf.has(f))break;if(A===`
142
+ `){let w=this.continueScalar(r+1);if(w===-1)break;r=Math.max(r,w-2)}}else{if(D&&Cf.has(A))break;u=r}if(!A&&!this.atEnd)return this.setNext("plain-scalar");return yield mA.SCALAR,yield*this.pushToIndex(u+1,!0),D?"flow":"doc"}*pushCount(D){if(D>0)return yield this.buffer.substr(this.pos,D),this.pos+=D,D;return 0}*pushToIndex(D,u){let r=this.buffer.slice(this.pos,D);if(r)return yield r,this.pos+=r.length,r.length;else if(u)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(gw))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let D=this.flowLevel>0,u=this.charAt(1);if(yu(u)||D&&Cf.has(u)){if(!D)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;return(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let D=this.pos+2,u=this.buffer[D];while(!yu(u)&&u!==">")u=this.buffer[++D];return yield*this.pushToIndex(u===">"?D+1:D,!1)}else{let D=this.pos+1,u=this.buffer[D];while(u)if(bk.has(u))u=this.buffer[++D];else if(u==="%"&&yS.has(this.buffer[D+1])&&yS.has(this.buffer[D+2]))u=this.buffer[D+=3];else break;return yield*this.pushToIndex(D,!1)}}*pushNewline(){let D=this.buffer[this.pos];if(D===`
143
143
  `)return yield*this.pushCount(1);else if(D==="\r"&&this.charAt(1)===`
144
- `)return yield*this.pushCount(2);else return 0}*pushSpaces(D){let u=this.pos-1,r;do r=this.buffer[++u];while(r===" "||D&&r==="\t");let A=u-this.pos;if(A>0)yield this.buffer.substr(this.pos,A),this.pos=u;return A}*pushUntil(D){let u=this.pos,r=this.buffer[u];while(!D(r))r=this.buffer[++u];return yield*this.pushToIndex(u,!1)}}Gk.Lexer=K_});var F9=Q((Hk)=>{class h_{constructor(){this.lineStarts=[],this.addNewLine=(D)=>this.lineStarts.push(D),this.linePos=(D)=>{let u=0,r=this.lineStarts.length;while(u<r){let f=u+r>>1;if(this.lineStarts[f]<D)u=f+1;else r=f}if(this.lineStarts[u]===D)return{line:u+1,col:1};if(u===0)return{line:0,col:D};let A=this.lineStarts[u-1];return{line:u,col:D-A+1}}}}Hk.LineCounter=h_});var w9=Q((Yk)=>{var Uk=yA("process"),N_=Bf(),Xk=f9();function _0(D,u){for(let r=0;r<D.length;++r)if(D[r].type===u)return!0;return!1}function Q_(D){for(let u=0;u<D.length;++u)switch(D[u].type){case"space":case"comment":case"newline":break;default:return u}return-1}function q_(D){switch(D?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Wf(D){switch(D.type){case"document":return D.start;case"block-map":{let u=D.items[D.items.length-1];return u.sep??u.start}case"block-seq":return D.items[D.items.length-1].start;default:return[]}}function Q2(D){if(D.length===0)return[];let u=D.length;D:while(--u>=0)switch(D[u].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break D}while(D[++u]?.type==="space");return D.splice(u,D.length)}function L_(D){if(D.start.type==="flow-seq-start"){for(let u of D.items)if(u.sep&&!u.value&&!_0(u.start,"explicit-key-ind")&&!_0(u.sep,"map-value-ind")){if(u.key)u.value=u.key;if(delete u.key,q_(u.value))if(u.value.end)Array.prototype.push.apply(u.value.end,u.sep);else u.value.end=u.sep;else Array.prototype.push.apply(u.start,u.sep);delete u.sep}}}class b_{constructor(D){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Xk.Lexer,this.onNewLine=D}*parse(D,u=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let r of this.lexer.lex(D,u))yield*this.next(r);if(!u)yield*this.end()}*next(D){if(this.source=D,Uk.env.LOG_TOKENS)console.log("|",N_.prettyToken(D));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=D.length;return}let u=N_.tokenType(D);if(!u){let r=`Not a YAML token: ${D}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:D}),this.offset+=D.length}else if(u==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=u,yield*this.step(),u){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+D.length);break;case"space":if(this.atNewLine&&D[0]===" ")this.indent+=D.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=D.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=D.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let D=this.peek(1);if(this.type==="doc-end"&&D?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!D)return yield*this.stream();switch(D.type){case"document":return yield*this.document(D);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(D);case"block-scalar":return yield*this.blockScalar(D);case"block-map":return yield*this.blockMap(D);case"block-seq":return yield*this.blockSequence(D);case"flow-collection":return yield*this.flowCollection(D);case"doc-end":return yield*this.documentEnd(D)}yield*this.pop()}peek(D){return this.stack[this.stack.length-D]}*pop(D){let u=D??this.stack.pop();if(!u)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield u;else{let r=this.peek(1);if(u.type==="block-scalar")u.indent="indent"in r?r.indent:0;else if(u.type==="flow-collection"&&r.type==="document")u.indent=0;if(u.type==="flow-collection")L_(u);switch(r.type){case"document":r.value=u;break;case"block-scalar":r.props.push(u);break;case"block-map":{let A=r.items[r.items.length-1];if(A.value){r.items.push({start:[],key:u,sep:[]}),this.onKeyLine=!0;return}else if(A.sep)A.value=u;else{Object.assign(A,{key:u,sep:[]}),this.onKeyLine=!A.explicitKey;return}break}case"block-seq":{let A=r.items[r.items.length-1];if(A.value)r.items.push({start:[],value:u});else A.value=u;break}case"flow-collection":{let A=r.items[r.items.length-1];if(!A||A.value)r.items.push({start:[],key:u,sep:[]});else if(A.sep)A.value=u;else Object.assign(A,{key:u,sep:[]});return}default:yield*this.pop(),yield*this.pop(u)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(u.type==="block-map"||u.type==="block-seq")){let A=u.items[u.items.length-1];if(A&&!A.sep&&!A.value&&A.start.length>0&&Q_(A.start)===-1&&(u.indent===0||A.start.every((f)=>f.type!=="comment"||f.indent<u.indent))){if(r.type==="document")r.end=A.start;else r.items.push({start:A.start});u.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let D={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")D.start.push(this.sourceToken);this.stack.push(D);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(D){if(D.value)return yield*this.lineEnd(D);switch(this.type){case"doc-start":{if(Q_(D.start)!==-1)yield*this.pop(),yield*this.step();else D.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":D.start.push(this.sourceToken);return}let u=this.startBlockValue(D);if(u)this.stack.push(u);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(D){if(this.type==="map-value-ind"){let u=Wf(this.peek(2)),r=Q2(u),A;if(D.end)A=D.end,A.push(this.sourceToken),delete D.end;else A=[this.sourceToken];let f={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:r,key:D,sep:A}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=f}else yield*this.lineEnd(D)}*blockScalar(D){switch(this.type){case"space":case"comment":case"newline":D.props.push(this.sourceToken);return;case"scalar":if(D.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let u=this.source.indexOf(`
144
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces(D){let u=this.pos-1,r;do r=this.buffer[++u];while(r===" "||D&&r==="\t");let A=u-this.pos;if(A>0)yield this.buffer.substr(this.pos,A),this.pos=u;return A}*pushUntil(D){let u=this.pos,r=this.buffer[u];while(!D(r))r=this.buffer[++u];return yield*this.pushToIndex(u,!1)}}zk.Lexer=cS});var _w=L((Tk)=>{class tS{constructor(){this.lineStarts=[],this.addNewLine=(D)=>this.lineStarts.push(D),this.linePos=(D)=>{let u=0,r=this.lineStarts.length;while(u<r){let f=u+r>>1;if(this.lineStarts[f]<D)u=f+1;else r=f}if(this.lineStarts[u]===D)return{line:u+1,col:1};if(u===0)return{line:0,col:D};let A=this.lineStarts[u-1];return{line:u,col:D-A+1}}}}Tk.LineCounter=tS});var Rw=L((dk)=>{var Zk=p1("process"),pS=Gf(),ok=Sw();function S0(D,u){for(let r=0;r<D.length;++r)if(D[r].type===u)return!0;return!1}function xS(D){for(let u=0;u<D.length;++u)switch(D[u].type){case"space":case"comment":case"newline":break;default:return u}return-1}function aS(D){switch(D?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Hf(D){switch(D.type){case"document":return D.start;case"block-map":{let u=D.items[D.items.length-1];return u.sep??u.start}case"block-seq":return D.items[D.items.length-1].start;default:return[]}}function L2(D){if(D.length===0)return[];let u=D.length;D:while(--u>=0)switch(D[u].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break D}while(D[++u]?.type==="space");return D.splice(u,D.length)}function mS(D){if(D.start.type==="flow-seq-start"){for(let u of D.items)if(u.sep&&!u.value&&!S0(u.start,"explicit-key-ind")&&!S0(u.sep,"map-value-ind")){if(u.key)u.value=u.key;if(delete u.key,aS(u.value))if(u.value.end)Array.prototype.push.apply(u.value.end,u.sep);else u.value.end=u.sep;else Array.prototype.push.apply(u.start,u.sep);delete u.sep}}}class eS{constructor(D){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new ok.Lexer,this.onNewLine=D}*parse(D,u=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let r of this.lexer.lex(D,u))yield*this.next(r);if(!u)yield*this.end()}*next(D){if(this.source=D,Zk.env.LOG_TOKENS)console.log("|",pS.prettyToken(D));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=D.length;return}let u=pS.tokenType(D);if(!u){let r=`Not a YAML token: ${D}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:D}),this.offset+=D.length}else if(u==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=u,yield*this.step(),u){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+D.length);break;case"space":if(this.atNewLine&&D[0]===" ")this.indent+=D.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=D.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=D.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let D=this.peek(1);if(this.type==="doc-end"&&D?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!D)return yield*this.stream();switch(D.type){case"document":return yield*this.document(D);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(D);case"block-scalar":return yield*this.blockScalar(D);case"block-map":return yield*this.blockMap(D);case"block-seq":return yield*this.blockSequence(D);case"flow-collection":return yield*this.flowCollection(D);case"doc-end":return yield*this.documentEnd(D)}yield*this.pop()}peek(D){return this.stack[this.stack.length-D]}*pop(D){let u=D??this.stack.pop();if(!u)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield u;else{let r=this.peek(1);if(u.type==="block-scalar")u.indent="indent"in r?r.indent:0;else if(u.type==="flow-collection"&&r.type==="document")u.indent=0;if(u.type==="flow-collection")mS(u);switch(r.type){case"document":r.value=u;break;case"block-scalar":r.props.push(u);break;case"block-map":{let A=r.items[r.items.length-1];if(A.value){r.items.push({start:[],key:u,sep:[]}),this.onKeyLine=!0;return}else if(A.sep)A.value=u;else{Object.assign(A,{key:u,sep:[]}),this.onKeyLine=!A.explicitKey;return}break}case"block-seq":{let A=r.items[r.items.length-1];if(A.value)r.items.push({start:[],value:u});else A.value=u;break}case"flow-collection":{let A=r.items[r.items.length-1];if(!A||A.value)r.items.push({start:[],key:u,sep:[]});else if(A.sep)A.value=u;else Object.assign(A,{key:u,sep:[]});return}default:yield*this.pop(),yield*this.pop(u)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(u.type==="block-map"||u.type==="block-seq")){let A=u.items[u.items.length-1];if(A&&!A.sep&&!A.value&&A.start.length>0&&xS(A.start)===-1&&(u.indent===0||A.start.every((f)=>f.type!=="comment"||f.indent<u.indent))){if(r.type==="document")r.end=A.start;else r.items.push({start:A.start});u.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let D={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")D.start.push(this.sourceToken);this.stack.push(D);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(D){if(D.value)return yield*this.lineEnd(D);switch(this.type){case"doc-start":{if(xS(D.start)!==-1)yield*this.pop(),yield*this.step();else D.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":D.start.push(this.sourceToken);return}let u=this.startBlockValue(D);if(u)this.stack.push(u);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(D){if(this.type==="map-value-ind"){let u=Hf(this.peek(2)),r=L2(u),A;if(D.end)A=D.end,A.push(this.sourceToken),delete D.end;else A=[this.sourceToken];let f={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:r,key:D,sep:A}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=f}else yield*this.lineEnd(D)}*blockScalar(D){switch(this.type){case"space":case"comment":case"newline":D.props.push(this.sourceToken);return;case"scalar":if(D.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let u=this.source.indexOf(`
145
145
  `)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
146
- `,u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(D){let u=D.items[D.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,u.value){let r="end"in u.value?u.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)D.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else{if(this.atIndentedComment(u.start,D.indent)){let A=D.items[D.items.length-2]?.value?.end;if(Array.isArray(A)){Array.prototype.push.apply(A,u.start),A.push(this.sourceToken),D.items.pop();return}}u.start.push(this.sourceToken)}return}if(this.indent>=D.indent){let r=!this.onKeyLine&&this.indent===D.indent,A=r&&(u.sep||u.explicitKey)&&this.type!=="seq-item-ind",f=[];if(A&&u.sep&&!u.value){let w=[];for(let F=0;F<u.sep.length;++F){let E=u.sep[F];switch(E.type){case"newline":w.push(F);break;case"space":break;case"comment":if(E.indent>D.indent)w.length=0;break;default:w.length=0}}if(w.length>=2)f=u.sep.splice(w[1])}switch(this.type){case"anchor":case"tag":if(A||u.value)f.push(this.sourceToken),D.items.push({start:f}),this.onKeyLine=!0;else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"explicit-key-ind":if(!u.sep&&!u.explicitKey)u.start.push(this.sourceToken),u.explicitKey=!0;else if(A||u.value)f.push(this.sourceToken),D.items.push({start:f,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(u.explicitKey)if(!u.sep)if(_0(u.start,"newline"))Object.assign(u,{key:null,sep:[this.sourceToken]});else{let w=Q2(u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:null,sep:[this.sourceToken]}]})}else if(u.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(_0(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:f,key:null,sep:[this.sourceToken]}]});else if(q_(u.key)&&!_0(u.sep,"newline")){let w=Q2(u.start),F=u.key,E=u.sep;E.push(this.sourceToken),delete u.key,delete u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:F,sep:E}]})}else if(f.length>0)u.sep=u.sep.concat(f,this.sourceToken);else u.sep.push(this.sourceToken);else if(!u.sep)Object.assign(u,{key:null,sep:[this.sourceToken]});else if(u.value||A)D.items.push({start:f,key:null,sep:[this.sourceToken]});else if(_0(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else u.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let w=this.flowScalar(this.type);if(A||u.value)D.items.push({start:f,key:w,sep:[]}),this.onKeyLine=!0;else if(u.sep)this.stack.push(w);else Object.assign(u,{key:w,sep:[]}),this.onKeyLine=!0;return}default:{let w=this.startBlockValue(D);if(w){if(w.type==="block-seq"){if(!u.explicitKey&&u.sep&&!_0(u.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)D.items.push({start:f});this.stack.push(w);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(D){let u=D.items[D.items.length-1];switch(this.type){case"newline":if(u.value){let r="end"in u.value?u.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)D.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(u.start,D.indent)){let A=D.items[D.items.length-2]?.value?.end;if(Array.isArray(A)){Array.prototype.push.apply(A,u.start),A.push(this.sourceToken),D.items.pop();return}}u.start.push(this.sourceToken)}return;case"anchor":case"tag":if(u.value||this.indent<=D.indent)break;u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==D.indent)break;if(u.value||_0(u.start,"seq-item-ind"))D.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return}if(this.indent>D.indent){let r=this.startBlockValue(D);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(D){let u=D.items[D.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(D.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!u||u.sep)D.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return;case"map-value-ind":if(!u||u.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else Object.assign(u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!u||u.value)D.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let A=this.flowScalar(this.type);if(!u||u.value)D.items.push({start:[],key:A,sep:[]});else if(u.sep)this.stack.push(A);else Object.assign(u,{key:A,sep:[]});return}case"flow-map-end":case"flow-seq-end":D.end.push(this.sourceToken);return}let r=this.startBlockValue(D);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===D.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let A=Wf(r),f=Q2(A);L_(D);let w=D.end.splice(1,D.end.length);w.push(this.sourceToken);let F={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:f,key:D,sep:w}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=F}else yield*this.lineEnd(D)}}flowScalar(D){if(this.onNewLine){let u=this.source.indexOf(`
146
+ `,u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(D){let u=D.items[D.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,u.value){let r="end"in u.value?u.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)D.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else{if(this.atIndentedComment(u.start,D.indent)){let A=D.items[D.items.length-2]?.value?.end;if(Array.isArray(A)){Array.prototype.push.apply(A,u.start),A.push(this.sourceToken),D.items.pop();return}}u.start.push(this.sourceToken)}return}if(this.indent>=D.indent){let r=!this.onKeyLine&&this.indent===D.indent,A=r&&(u.sep||u.explicitKey)&&this.type!=="seq-item-ind",f=[];if(A&&u.sep&&!u.value){let w=[];for(let F=0;F<u.sep.length;++F){let E=u.sep[F];switch(E.type){case"newline":w.push(F);break;case"space":break;case"comment":if(E.indent>D.indent)w.length=0;break;default:w.length=0}}if(w.length>=2)f=u.sep.splice(w[1])}switch(this.type){case"anchor":case"tag":if(A||u.value)f.push(this.sourceToken),D.items.push({start:f}),this.onKeyLine=!0;else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"explicit-key-ind":if(!u.sep&&!u.explicitKey)u.start.push(this.sourceToken),u.explicitKey=!0;else if(A||u.value)f.push(this.sourceToken),D.items.push({start:f,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(u.explicitKey)if(!u.sep)if(S0(u.start,"newline"))Object.assign(u,{key:null,sep:[this.sourceToken]});else{let w=L2(u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:null,sep:[this.sourceToken]}]})}else if(u.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(S0(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:f,key:null,sep:[this.sourceToken]}]});else if(aS(u.key)&&!S0(u.sep,"newline")){let w=L2(u.start),F=u.key,E=u.sep;E.push(this.sourceToken),delete u.key,delete u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:F,sep:E}]})}else if(f.length>0)u.sep=u.sep.concat(f,this.sourceToken);else u.sep.push(this.sourceToken);else if(!u.sep)Object.assign(u,{key:null,sep:[this.sourceToken]});else if(u.value||A)D.items.push({start:f,key:null,sep:[this.sourceToken]});else if(S0(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else u.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let w=this.flowScalar(this.type);if(A||u.value)D.items.push({start:f,key:w,sep:[]}),this.onKeyLine=!0;else if(u.sep)this.stack.push(w);else Object.assign(u,{key:w,sep:[]}),this.onKeyLine=!0;return}default:{let w=this.startBlockValue(D);if(w){if(w.type==="block-seq"){if(!u.explicitKey&&u.sep&&!S0(u.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)D.items.push({start:f});this.stack.push(w);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(D){let u=D.items[D.items.length-1];switch(this.type){case"newline":if(u.value){let r="end"in u.value?u.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)D.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(u.start,D.indent)){let A=D.items[D.items.length-2]?.value?.end;if(Array.isArray(A)){Array.prototype.push.apply(A,u.start),A.push(this.sourceToken),D.items.pop();return}}u.start.push(this.sourceToken)}return;case"anchor":case"tag":if(u.value||this.indent<=D.indent)break;u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==D.indent)break;if(u.value||S0(u.start,"seq-item-ind"))D.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return}if(this.indent>D.indent){let r=this.startBlockValue(D);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(D){let u=D.items[D.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(D.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!u||u.sep)D.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return;case"map-value-ind":if(!u||u.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else Object.assign(u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!u||u.value)D.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let A=this.flowScalar(this.type);if(!u||u.value)D.items.push({start:[],key:A,sep:[]});else if(u.sep)this.stack.push(A);else Object.assign(u,{key:A,sep:[]});return}case"flow-map-end":case"flow-seq-end":D.end.push(this.sourceToken);return}let r=this.startBlockValue(D);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===D.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let A=Hf(r),f=L2(A);mS(D);let w=D.end.splice(1,D.end.length);w.push(this.sourceToken);let F={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:f,key:D,sep:w}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=F}else yield*this.lineEnd(D)}}flowScalar(D){if(this.onNewLine){let u=this.source.indexOf(`
147
147
  `)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
148
- `,u)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let u=Wf(D),r=Q2(u);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let u=Wf(D),r=Q2(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return D.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}Yk.Parser=b_});var s_=Q((hk)=>{var z_=x6(),Ok=l1(),a1=c1(),Pk=F6(),ik=AD(),kk=F9(),j_=w9();function T_(D){let u=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||u&&new kk.LineCounter||null,prettyErrors:u}}function Ik(D,u={}){let{lineCounter:r,prettyErrors:A}=T_(u),f=new j_.Parser(r?.addNewLine),w=new z_.Composer(u),F=Array.from(w.compose(f.parse(D)));if(A&&r)for(let E of F)E.errors.forEach(a1.prettifyError(D,r)),E.warnings.forEach(a1.prettifyError(D,r));if(F.length>0)return F;return Object.assign([],{empty:!0},w.streamInfo())}function v_(D,u={}){let{lineCounter:r,prettyErrors:A}=T_(u),f=new j_.Parser(r?.addNewLine),w=new z_.Composer(u),F=null;for(let E of w.compose(f.parse(D),!0,D.length))if(!F)F=E;else if(F.options.logLevel!=="silent"){F.errors.push(new a1.YAMLParseError(E.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(A&&r)F.errors.forEach(a1.prettifyError(D,r)),F.warnings.forEach(a1.prettifyError(D,r));return F}function Vk(D,u,r){let A=void 0;if(typeof u==="function")A=u;else if(r===void 0&&u&&typeof u==="object")r=u;let f=v_(D,r);if(!f)return null;if(f.warnings.forEach((w)=>Pk.warn(f.options.logLevel,w)),f.errors.length>0)if(f.options.logLevel!=="silent")throw f.errors[0];else f.errors=[];return f.toJS(Object.assign({reviver:A},r))}function Kk(D,u,r){let A=null;if(typeof u==="function"||Array.isArray(u))A=u;else if(r===void 0&&u)r=u;if(typeof r==="string")r=r.length;if(typeof r==="number"){let f=Math.round(r);r=f<1?void 0:f>8?{indent:8}:{indent:f}}if(D===void 0){let{keepUndefined:f}=r??u??{};if(!f)return}if(ik.isDocument(D)&&!A)return D.toString(r);return new Ok.Document(D,A,r).toString(r)}hk.parse=Vk;hk.parseAllDocuments=Ik;hk.parseDocument=v_;hk.stringify=Kk});var bk,zk,jk,$9,Tk,R0,vk,sk,Zk,ok,ed,dk,yk,lk,Gf,Z_,ck,tk,xk,mk,pk,ak,ek,DI,uI,rI,AI,fI,FI,wI,$I,EI,gI,_I,RI,SI,BI,JI,e1,WI,GI,CI,HI,nI;var E9=W(()=>{bk=x6(),zk=l1(),jk=Q6(),$9=c1(),Tk=h1(),R0=AD(),vk=w0(),sk=ID(),Zk=E0(),ok=g0(),ed=Bf(),dk=f9(),yk=F9(),lk=w9(),Gf=s_(),Z_=V1();ck=bk.Composer,tk=zk.Document,xk=jk.Schema,mk=$9.YAMLError,pk=$9.YAMLParseError,ak=$9.YAMLWarning,ek=Tk.Alias,DI=R0.isAlias,uI=R0.isCollection,rI=R0.isDocument,AI=R0.isMap,fI=R0.isNode,FI=R0.isPair,wI=R0.isScalar,$I=R0.isSeq,EI=vk.Pair,gI=sk.Scalar,_I=Zk.YAMLMap,RI=ok.YAMLSeq,SI=dk.Lexer,BI=yk.LineCounter,JI=lk.Parser,e1=Gf.parse,WI=Gf.parseAllDocuments,GI=Gf.parseDocument,CI=Gf.stringify,HI=Z_.visit,nI=Z_.visitAsync});var DA,o_,d_,Cf,y_,g9,l_,_9,c_,UI,t_,R9,x_,m_,p_,XI,a_,S9;var Hf=W(()=>{YD();DA=_.string().min(1).regex(/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/),o_=_.enum(["info","warning","error"]),d_=_.enum(["pending","pass","warn","fail"]),Cf=_.enum(["draft","enabled","disabled"]),y_=_.object({code:_.string().min(1),message:_.string().min(1),path:_.string().min(1).optional(),severity:o_}),g9=_.object({checkedAt:_.string().min(1).optional(),issues:_.array(y_),status:d_}),l_=_.object({id:DA,status:Cf,validation:g9}),_9=_.enum(["auto","ask","deny"]),c_=_.object({action:_9,pattern:_.string().min(1),reason:_.string().min(1).optional()}),UI=_.object({outOfScope:_.object({default:_.string().min(1).optional(),strategy:_.string().min(1).optional()}).passthrough().refine((D)=>typeof D.default==="string"||typeof D.strategy==="string","outOfScope requires either default or strategy"),risk:_.object({highRiskRequiresApproval:_.boolean(),policy:_.string().min(1).optional()}).passthrough(),schemaVersion:_.literal(1),soul:_.object({label:_.string().min(1).optional(),preset:DA,source:_.string().min(1).optional()}).passthrough().optional(),status:Cf,toolPolicy:_.object({default:_9,rules:_.array(c_)}).passthrough().optional()}),t_=_.object({description:_.string().min(1).optional(),risk:_.enum(["low","medium","high"]).optional(),tools:_.array(_.string().min(1)).optional()}).passthrough(),R9=_.object({secretRef:_.string().min(1)}),x_=_.object({description:_.string().min(1).optional(),inputSchema:_.record(_.unknown()).optional(),name:_.string().min(1)}).passthrough(),m_=_.object({args:_.array(_.string()).optional(),command:_.string().min(1).optional(),description:_.string().min(1).optional(),disabled:_.boolean().optional(),env:_.record(_.unknown()).optional(),headers:_.record(_.unknown()).optional(),tools:_.array(x_).optional(),transport:_.enum(["stdio","streamable-http","sse"]).optional(),url:_.string().min(1).optional()}).passthrough(),p_=_.object({schemaVersion:_.literal(1).optional(),servers:_.record(m_)}),XI=_.object({defaultToolsets:_.array(DA),mcp:p_,packs:_.array(l_),schemaVersion:_.literal(1),soul:DA.optional(),status:Cf,toolsets:_.record(t_).optional(),validation:g9.optional()}),a_=_.enum(["filesystem-read","filesystem-write","shell","network","browser","mcp"]),S9=_.object({capabilities:_.array(_.string().min(1)).optional(),description:_.string().min(1),name:_.string().min(1),permissions:_.array(a_).optional(),version:_.string().min(1).optional()}).passthrough()});function PI(D,u){let r=YI.exec(D);if(!r)throw Error(`Brain skill pack ${u} is missing YAML frontmatter`);let A;try{A=e1(r[1]??"")}catch(f){throw Error(`Brain skill pack ${u} has invalid YAML frontmatter: ${f instanceof Error?f.message:String(f)}`)}try{return MI.parse(A)}catch(f){if(f instanceof _.ZodError)throw Error(`Brain skill pack ${u} does not satisfy SkillMetadata: ${f.issues.map((w)=>w.message).join("; ")}`);throw f}}function $u(D){let u=OI.parse(D),r=PI(u.skillMd,u.sourcePath);if(r.id!==u.expectedId)throw Error(`Brain skill pack ${u.sourcePath} declares id "${r.id}" but expected "${u.expectedId}"`);return{id:r.id,installPath:`${r.id}/SKILL.md`,metadata:r,skillMd:u.skillMd.trimEnd(),sourcePath:u.sourcePath}}var YI,MI,OI;var B9=W(()=>{E9();YD();Hf();YI=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/,MI=S9.extend({id:_.string().min(1)}),OI=_.object({expectedId:_.string().min(1),skillMd:_.string().min(1),sourcePath:_.string().min(1)})});var DR=`---
148
+ `,u)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let u=Hf(D),r=L2(u);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let u=Hf(D),r=L2(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return D.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}dk.Parser=eS});var f_=L((ek)=>{var D_=uw(),yk=yA(),aA=cA(),ck=_6(),tk=AD(),pk=_w(),u_=Rw();function r_(D){let u=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||u&&new pk.LineCounter||null,prettyErrors:u}}function xk(D,u={}){let{lineCounter:r,prettyErrors:A}=r_(u),f=new u_.Parser(r?.addNewLine),w=new D_.Composer(u),F=Array.from(w.compose(f.parse(D)));if(A&&r)for(let E of F)E.errors.forEach(aA.prettifyError(D,r)),E.warnings.forEach(aA.prettifyError(D,r));if(F.length>0)return F;return Object.assign([],{empty:!0},w.streamInfo())}function A_(D,u={}){let{lineCounter:r,prettyErrors:A}=r_(u),f=new u_.Parser(r?.addNewLine),w=new D_.Composer(u),F=null;for(let E of w.compose(f.parse(D),!0,D.length))if(!F)F=E;else if(F.options.logLevel!=="silent"){F.errors.push(new aA.YAMLParseError(E.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(A&&r)F.errors.forEach(aA.prettifyError(D,r)),F.warnings.forEach(aA.prettifyError(D,r));return F}function mk(D,u,r){let A=void 0;if(typeof u==="function")A=u;else if(r===void 0&&u&&typeof u==="object")r=u;let f=A_(D,r);if(!f)return null;if(f.warnings.forEach((w)=>ck.warn(f.options.logLevel,w)),f.errors.length>0)if(f.options.logLevel!=="silent")throw f.errors[0];else f.errors=[];return f.toJS(Object.assign({reviver:A},r))}function ak(D,u,r){let A=null;if(typeof u==="function"||Array.isArray(u))A=u;else if(r===void 0&&u)r=u;if(typeof r==="string")r=r.length;if(typeof r==="number"){let f=Math.round(r);r=f<1?void 0:f>8?{indent:8}:{indent:f}}if(D===void 0){let{keepUndefined:f}=r??u??{};if(!f)return}if(tk.isDocument(D)&&!A)return D.toString(r);return new yk.Document(D,A,r).toString(r)}ek.parse=mk;ek.parseAllDocuments=xk;ek.parseDocument=A_;ek.stringify=ak});var fI,FI,wI,nw,$I,_0,EI,gI,SI,_I,Ll,RI,nI,BI,Xf,F_,WI,JI,GI,CI,HI,XI,iI,UI,YI,MI,OI,PI,kI,II,VI,KI,hI,NI,QI,LI,qI,bI,eA,sI,zI,jI,TI,vI;var Bw=W(()=>{fI=uw(),FI=yA(),wI=j6(),nw=cA(),$I=hA(),_0=AD(),EI=w0(),gI=VD(),SI=E0(),_I=g0(),Ll=Gf(),RI=Sw(),nI=_w(),BI=Rw(),Xf=f_(),F_=VA();WI=fI.Composer,JI=FI.Document,GI=wI.Schema,CI=nw.YAMLError,HI=nw.YAMLParseError,XI=nw.YAMLWarning,iI=$I.Alias,UI=_0.isAlias,YI=_0.isCollection,MI=_0.isDocument,OI=_0.isMap,PI=_0.isNode,kI=_0.isPair,II=_0.isScalar,VI=_0.isSeq,KI=EI.Pair,hI=gI.Scalar,NI=SI.YAMLMap,QI=_I.YAMLSeq,LI=RI.Lexer,qI=nI.LineCounter,bI=BI.Parser,eA=Xf.parse,sI=Xf.parseAllDocuments,zI=Xf.parseDocument,jI=Xf.stringify,TI=F_.visit,vI=F_.visitAsync});var D1,w_,$_,Uf,E_,Ww,g_,Jw,S_,ZI,__,Gw,R_,n_,B_,oI,W_,Cw;var Yf=W(()=>{YD();D1=S.string().min(1).regex(/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/),w_=S.enum(["info","warning","error"]),$_=S.enum(["pending","pass","warn","fail"]),Uf=S.enum(["draft","enabled","disabled"]),E_=S.object({code:S.string().min(1),message:S.string().min(1),path:S.string().min(1).optional(),severity:w_}),Ww=S.object({checkedAt:S.string().min(1).optional(),issues:S.array(E_),status:$_}),g_=S.object({id:D1,status:Uf,validation:Ww}),Jw=S.enum(["auto","ask","deny"]),S_=S.object({action:Jw,pattern:S.string().min(1),reason:S.string().min(1).optional()}),ZI=S.object({outOfScope:S.object({default:S.string().min(1).optional(),strategy:S.string().min(1).optional()}).passthrough().refine((D)=>typeof D.default==="string"||typeof D.strategy==="string","outOfScope requires either default or strategy"),risk:S.object({highRiskRequiresApproval:S.boolean(),policy:S.string().min(1).optional()}).passthrough(),schemaVersion:S.literal(1),soul:S.object({label:S.string().min(1).optional(),preset:D1,source:S.string().min(1).optional()}).passthrough().optional(),status:Uf,toolPolicy:S.object({default:Jw,rules:S.array(S_)}).passthrough().optional()}),__=S.object({description:S.string().min(1).optional(),risk:S.enum(["low","medium","high"]).optional(),tools:S.array(S.string().min(1)).optional()}).passthrough(),Gw=S.object({secretRef:S.string().min(1)}),R_=S.object({description:S.string().min(1).optional(),inputSchema:S.record(S.unknown()).optional(),name:S.string().min(1)}).passthrough(),n_=S.object({args:S.array(S.string()).optional(),command:S.string().min(1).optional(),description:S.string().min(1).optional(),disabled:S.boolean().optional(),env:S.record(S.unknown()).optional(),headers:S.record(S.unknown()).optional(),tools:S.array(R_).optional(),transport:S.enum(["stdio","streamable-http","sse"]).optional(),url:S.string().min(1).optional()}).passthrough(),B_=S.object({schemaVersion:S.literal(1).optional(),servers:S.record(n_)}),oI=S.object({defaultToolsets:S.array(D1),mcp:B_,packs:S.array(g_),schemaVersion:S.literal(1),soul:D1.optional(),status:Uf,toolsets:S.record(__).optional(),validation:Ww.optional()}),W_=S.enum(["filesystem-read","filesystem-write","shell","network","browser","mcp"]),Cw=S.object({capabilities:S.array(S.string().min(1)).optional(),description:S.string().min(1),name:S.string().min(1),permissions:S.array(W_).optional(),version:S.string().min(1).optional()}).passthrough()});function cI(D,u){let r=dI.exec(D);if(!r)throw Error(`Brain skill pack ${u} is missing YAML frontmatter`);let A;try{A=eA(r[1]??"")}catch(f){throw Error(`Brain skill pack ${u} has invalid YAML frontmatter: ${f instanceof Error?f.message:String(f)}`)}try{return lI.parse(A)}catch(f){if(f instanceof S.ZodError)throw Error(`Brain skill pack ${u} does not satisfy SkillMetadata: ${f.issues.map((w)=>w.message).join("; ")}`);throw f}}function gu(D){let u=yI.parse(D),r=cI(u.skillMd,u.sourcePath);if(r.id!==u.expectedId)throw Error(`Brain skill pack ${u.sourcePath} declares id "${r.id}" but expected "${u.expectedId}"`);return{id:r.id,installPath:`${r.id}/SKILL.md`,metadata:r,skillMd:u.skillMd.trimEnd(),sourcePath:u.sourcePath}}var dI,lI,yI;var Hw=W(()=>{Bw();YD();Yf();dI=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/,lI=Cw.extend({id:S.string().min(1)}),yI=S.object({expectedId:S.string().min(1),skillMd:S.string().min(1),sourcePath:S.string().min(1)})});var G_=`---
149
149
  id: developer.codebase-orientation
150
150
  name: Codebase Orientation
151
151
  description: Build codebase context before editing, with narrow search, impact tracing, and focused verification.
@@ -175,7 +175,7 @@ Use this before implementing code changes.
175
175
  - Do not rewrite unrelated code.
176
176
  - Do not use destructive git operations.
177
177
  - Keep secrets out of source, logs, and Brain memory.
178
- `;var e_=()=>{};var rR=`---
178
+ `;var J_=()=>{};var H_=`---
179
179
  id: devops-sre.incident-triage
180
180
  name: Incident Triage
181
181
  description: Triage operational incidents with timeline, blast radius, evidence, rollback, and escalation.
@@ -204,7 +204,7 @@ Use this for alerts, outages, degraded service, deployment failures, or reliabil
204
204
 
205
205
  - Do not restart, scale, deploy, or change production state without explicit approval.
206
206
  - Redact tokens, host secrets, and customer data in summaries.
207
- `;var uR=()=>{};var fR=`---
207
+ `;var C_=()=>{};var i_=`---
208
208
  id: finance-ops.financial-evidence-review
209
209
  name: Financial Evidence Review
210
210
  description: Review finance artifacts with source tracking, reconciliation questions, and escalation boundaries.
@@ -231,7 +231,7 @@ Use this for invoices, expenses, reconciliation notes, payment questions, and fi
231
231
 
232
232
  - Do not infer sensitive account details that are not in evidence.
233
233
  - Do not store personal or payment data in Brain memory without admission and redaction.
234
- `;var AR=()=>{};var wR=`---
234
+ `;var X_=()=>{};var Y_=`---
235
235
  id: general-assistant.general-task-framing
236
236
  name: General Task Framing
237
237
  description: Turn broad requests into scoped, evidence-backed next actions without overreaching.
@@ -258,7 +258,7 @@ Use this when the user asks for help but the domain, evidence, or desired output
258
258
 
259
259
  - Do not silently convert a general request into code, finance, HR, legal, or production operations.
260
260
  - Do not expand filesystem or network access without a clear reason.
261
- `;var FR=()=>{};var ER=`---
261
+ `;var U_=()=>{};var O_=`---
262
262
  id: hr-recruiting.candidate-screening
263
263
  name: Candidate Screening
264
264
  description: Screen recruiting evidence against role criteria with bias-aware, source-backed notes.
@@ -285,7 +285,7 @@ Use this for resumes, candidate notes, role requirements, interview packets, and
285
285
 
286
286
  - Avoid protected-class inference and unsupported personal judgments.
287
287
  - Treat candidate data as sensitive; durable memory requires admission and redaction.
288
- `;var $R=()=>{};var _R=`---
288
+ `;var M_=()=>{};var k_=`---
289
289
  id: product-designer.design-critique
290
290
  name: Design Critique
291
291
  description: Critique product design evidence against user goals, interaction clarity, and visual system fit.
@@ -312,7 +312,7 @@ Use this for product UI, flows, prototypes, screenshots, specs, or visual direct
312
312
 
313
313
  - Do not present subjective taste as a hard rule.
314
314
  - Do not overwrite design-system constraints unless the operator asks to change them.
315
- `;var gR=()=>{};var SR=`---
315
+ `;var P_=()=>{};var V_=`---
316
316
  id: project-manager.delivery-risk-review
317
317
  name: Delivery Risk Review
318
318
  description: Review project delivery state, dependencies, blockers, owner clarity, and next milestones.
@@ -339,7 +339,7 @@ Use this for roadmaps, plans, delivery status, blockers, handoffs, and execution
339
339
 
340
340
  - Do not treat plans as approvals.
341
341
  - Do not hide missing owner, scope, or deadline information behind optimistic summaries.
342
- `;var RR=()=>{};var JR=`---
342
+ `;var I_=()=>{};var h_=`---
343
343
  id: qa-reviewer.regression-review
344
344
  name: Regression Review
345
345
  description: Review behavior changes for regression risk, missing tests, and focused verification strategy.
@@ -367,7 +367,7 @@ Use this before closing a bug fix, refactor, release, or behavior change.
367
367
 
368
368
  - Do not claim coverage from unrelated tests.
369
369
  - Do not require broad test gates when a focused test is sufficient.
370
- `;var BR=()=>{};var GR=`---
370
+ `;var K_=()=>{};var Q_=`---
371
371
  id: support-operator.support-case-triage
372
372
  name: Support Case Triage
373
373
  description: Triage support cases into facts, customer impact, severity, next response, and escalation path.
@@ -394,7 +394,7 @@ Use this for customer tickets, support inbox items, troubleshooting notes, and e
394
394
 
395
395
  - Do not expose internal secrets, private notes, or unrelated customer data.
396
396
  - Do not promise fixes, refunds, or policy exceptions without authorization.
397
- `;var WR=()=>{};var HR=`---
397
+ `;var N_=()=>{};var q_=`---
398
398
  id: kernel.brain-admission
399
399
  name: Brain Admission
400
400
  description: Propose durable Project Brain mutations with evidence, rollback, and operator approval.
@@ -423,7 +423,7 @@ Use this when a reply would change durable Project Brain state: memory, brain sk
423
423
  - Do not write durable Brain files directly as a side effect of a normal task.
424
424
  - Do not claim admission succeeded unless AIWorker admission state confirms it.
425
425
  - Do not store plaintext secrets; use redacted values or secret refs.
426
- `;var CR=()=>{};var UR=`---
426
+ `;var L_=()=>{};var s_=`---
427
427
  id: kernel.executor-quality-review
428
428
  name: Executor Quality Review
429
429
  description: Review executor output for evidence, boundary fit, verification, and Brain governance bypass risk.
@@ -449,7 +449,7 @@ Use this when checking whether an executor result is ready to return, retry, or
449
449
  ## Output
450
450
 
451
451
  Return a concise verdict: \`pass\`, \`needs-repair\`, or \`escalate\`, followed by the smallest concrete repair.
452
- `;var nR=()=>{};function Yu(D){return M9[D]??[]}var XR,YR,J9,W9,G9,C9,H9,n9,U9,X9,Y9,M9;var MR=W(()=>{e_();uR();AR();FR();$R();gR();RR();BR();WR();B9();CR();nR();XR=$u({expectedId:"kernel.brain-admission",skillMd:HR,sourcePath:"packages/shared/src/brain/skills/kernel/brain-admission/SKILL.md"}),YR=$u({expectedId:"kernel.executor-quality-review",skillMd:UR,sourcePath:"packages/shared/src/brain/skills/kernel/executor-quality-review/SKILL.md"}),J9=$u({expectedId:"developer.codebase-orientation",skillMd:DR,sourcePath:"packages/shared/src/soul/packs/developer/skills/codebase-orientation/SKILL.md"}),W9=$u({expectedId:"devops-sre.incident-triage",skillMd:rR,sourcePath:"packages/shared/src/soul/packs/devops-sre/skills/incident-triage/SKILL.md"}),G9=$u({expectedId:"finance-ops.financial-evidence-review",skillMd:fR,sourcePath:"packages/shared/src/soul/packs/finance-ops/skills/financial-evidence-review/SKILL.md"}),C9=$u({expectedId:"general-assistant.general-task-framing",skillMd:wR,sourcePath:"packages/shared/src/soul/packs/general-assistant/skills/general-task-framing/SKILL.md"}),H9=$u({expectedId:"hr-recruiting.candidate-screening",skillMd:ER,sourcePath:"packages/shared/src/soul/packs/hr-recruiting/skills/candidate-screening/SKILL.md"}),n9=$u({expectedId:"product-designer.design-critique",skillMd:_R,sourcePath:"packages/shared/src/soul/packs/product-designer/skills/design-critique/SKILL.md"}),U9=$u({expectedId:"project-manager.delivery-risk-review",skillMd:SR,sourcePath:"packages/shared/src/soul/packs/project-manager/skills/delivery-risk-review/SKILL.md"}),X9=$u({expectedId:"qa-reviewer.regression-review",skillMd:JR,sourcePath:"packages/shared/src/soul/packs/qa-reviewer/skills/regression-review/SKILL.md"}),Y9=$u({expectedId:"support-operator.support-case-triage",skillMd:GR,sourcePath:"packages/shared/src/soul/packs/support-operator/skills/support-case-triage/SKILL.md"}),M9={developer:[J9],"devops-sre":[W9],"finance-ops":[G9],"general-assistant":[C9],"hr-recruiting":[H9],"product-designer":[n9],"project-manager":[U9],"qa-reviewer":[X9],"support-operator":[Y9]}});var nf=W(()=>{cF();hE();LE();oF();B9();MR()});var yu;var OR=W(()=>{yu=class yu extends Error{code;status;constructor(D,u,r){super(r);this.code=D;this.status=u;this.name="AppError"}static badRequest(D,u="BAD_REQUEST"){return new yu(u,400,D)}static notFound(D,u="NOT_FOUND"){return new yu(u,404,D)}static internal(D,u="INTERNAL_ERROR"){return new yu(u,500,D)}toJSON(){return{error:{code:this.code,message:this.message}}}}});var PR,i9,iR,P9,kR,tI,O9,IR,xI;var VR=W(()=>{YD();Hf();PR=_.enum(["codex","claude-code"]),i9=_.enum(["project"]),iR=_.enum(["stdio","streamable-http","sse"]),P9=_.union([_.string().min(1),R9]),kR=_.object({args:_.array(_.string()).optional(),bearerTokenEnvVar:_.string().min(1).optional(),command:_.string().min(1).optional(),description:_.string().min(1).optional(),disabled:_.boolean().optional(),env:_.record(P9).optional(),headers:_.record(P9).optional(),scope:i9,transport:iR,url:_.string().min(1).optional()}).passthrough(),tI=_.object({issues:_.array(_.object({code:_.string().min(1),message:_.string().min(1),severity:_.enum(["error","warning"])})).optional(),status:_.enum(["pending","pass","warn","fail"])}).passthrough(),O9=_.object({disabled:_.boolean().optional(),scope:i9.optional(),source:_.object({ref:_.string().min(1).optional(),type:_.enum(["engine-cli","path","registry","url","manual"])}).passthrough().optional(),status:_.enum(["draft","declared","validated","projected"]).optional(),validation:tI.optional()}).passthrough(),IR=_.object({mcp:_.record(kR).optional(),plugins:_.record(O9).optional(),policies:_.record(O9).optional(),skills:_.record(O9).optional()}).passthrough(),xI=_.object({engines:_.record(PR,IR),schemaVersion:_.literal(1)})});function mI(D,u){let r=0,A=0,f="";for(let w=0;w<D.length&&f.length<u;w+=1){A=A<<8|D[w],r+=8;while(r>=5&&f.length<u)f+="0123456789abcdefghjkmnpqrstvwxyz"[A>>>r-5&31],r-=5}return f.padEnd(u,"0")}function k9(){let D=new Uint8Array(10);return globalThis.crypto.getRandomValues(D),`w_${mI(D,12)}`}var KR=()=>{};var hR,NR,QR,LR,qR,bR,zR,jR,TR,vR,sR,Bu,CD,FD,pI,aI,eI,DV,uV,rV,AV,fV,FV,wV,$V,ZR,oR,dR,Uf;var yR=W(()=>{YD();hR=_.enum(["active","paused","disabled"]),NR=_.enum(["active","archived"]),QR=_.enum(["active","completed","failed","cancelled"]),LR=_.enum(["queued","running","succeeded","failed","cancelled"]),qR=_.enum(["queued","running","succeeded","failed","cancelled"]),bR=_.enum(["status","assistant_delta","tool","file_change","artifact","review","lesson","error","log"]),zR=_.enum(["file","directory","generated","uploaded"]),jR=_.enum(["user","session","system"]),TR=_.enum(["available","missing","archived"]),vR=_.enum(["pass","warn","fail","needs_review"]),sR=_.enum(["proposed","accepted","rejected"]),Bu=_.record(_.string(),_.unknown()),CD=_.string().min(1),FD=_.string().min(1),pI=_.object({id:FD,soulId:FD,name:_.string().min(1),status:hR,defaultEngineId:_.string().nullable(),metadataJson:Bu,createdAt:CD,updatedAt:CD}),aI=_.object({id:FD,workerId:FD,name:_.string().min(1),rootPath:_.string().min(1),type:_.string().min(1),status:NR,sourcePointersJson:_.array(Bu),metadataJson:Bu,createdAt:CD,updatedAt:CD}),eI=_.object({id:FD,workerId:FD,workspaceId:FD,capabilityTemplateId:FD,title:_.string().min(1),context:_.string(),status:QR,metadataJson:Bu,startedAt:CD.nullable(),endedAt:CD.nullable(),createdAt:CD,updatedAt:CD}),DV=_.object({id:FD,sessionId:FD,seq:_.number().int().positive(),input:_.string().min(1),response:_.string().nullable(),status:LR,error:_.string().nullable(),metadataJson:Bu,createdAt:CD,updatedAt:CD}),uV=_.object({id:FD,sessionId:FD,turnId:FD,seq:_.number().int().positive(),engineId:_.string().min(1),engineCommand:_.string().nullable(),status:qR,prompt:_.string().min(1),summary:_.string().nullable(),error:_.string().nullable(),metadataJson:Bu,startedAt:CD.nullable(),finishedAt:CD.nullable(),createdAt:CD,updatedAt:CD}),rV=_.object({id:_.number().int().positive(),sessionId:FD,turnId:FD.nullable(),invocationId:FD.nullable(),seq:_.number().int().nonnegative(),type:bR,payloadJson:Bu,createdAt:CD}),AV=_.object({id:FD,workspaceId:FD,path:_.string().min(1),kind:zR,size:_.number().int().nonnegative().nullable(),mtime:_.number().int().nonnegative().nullable(),hash:_.string().nullable(),source:jR,createdAt:CD,updatedAt:CD}),fV=_.object({id:FD,workspaceId:FD,sessionId:FD.nullable(),turnId:FD.nullable(),invocationId:FD.nullable(),path:_.string().min(1),kind:_.string().min(1),title:_.string().min(1),status:TR,metadataJson:Bu,createdAt:CD,updatedAt:CD}),FV=_.object({id:FD,workspaceId:FD,sessionId:FD.nullable(),turnId:FD.nullable(),artifactId:FD.nullable(),verdict:vR,findingsJson:_.array(Bu),risksJson:_.array(Bu),createdAt:CD}),wV=_.object({id:FD,workspaceId:FD,sourceReviewId:FD.nullable(),statement:_.string().min(1),evidenceJson:_.array(Bu),status:sR,createdAt:CD,updatedAt:CD}),$V=_.object({key:_.string().min(1),valueJson:Bu,updatedAt:CD}),ZR=_.enum(["local-cli","byok"]),oR=_.enum(["system","light","dark"]),dR=_.object({command:_.string().min(1),id:FD,installed:_.boolean(),name:_.string().min(1),path:_.string().nullable(),version:_.string().nullable()}),Uf=_.object({appearance:oR,byok:_.object({apiKeyRef:_.string(),baseUrl:_.string(),model:_.string(),provider:_.string()}),connectors:_.array(_.object({enabled:_.boolean(),id:_.string().min(1),name:_.string().min(1),status:_.enum(["configured","not_configured"])})),engineId:_.string().min(1),engines:_.array(dR),executionMode:ZR,externalMcpServers:_.array(_.object({command:_.string(),enabled:_.boolean(),id:_.string().min(1),name:_.string().min(1)})),language:_.string().min(1),localMcpServer:_.object({enabled:_.boolean(),url:_.string()}),updatedAt:CD})});var I9,V9,Xf,EV,K9,lR;var cR=W(()=>{YD();I9=_.discriminatedUnion("kind",[_.object({kind:_.literal("file_read"),path:_.string()}),_.object({kind:_.literal("file_edit"),path:_.string(),diff:_.string().optional()}),_.object({kind:_.literal("command_run"),command:_.string()}),_.object({kind:_.literal("search"),query:_.string()}),_.object({kind:_.literal("web_fetch"),url:_.string()}),_.object({kind:_.literal("task_plan"),summary:_.string()}),_.object({kind:_.literal("tool"),toolName:_.string(),arguments:_.record(_.unknown()).optional()}),_.object({kind:_.literal("other"),description:_.string().optional()})]),V9=_.enum(["pending","running","success","failed","pending_approval","denied"]),Xf=_.object({inputTokens:_.number().int().nonnegative(),outputTokens:_.number().int().nonnegative()}),EV=_.record(_.unknown()),K9=_.enum(["stop","tool","length","error","cancelled"]),lR=_.discriminatedUnion("type",[_.object({type:_.literal("assistant_message_delta"),delta:_.string()}),_.object({type:_.literal("thinking_delta"),delta:_.string()}),_.object({type:_.literal("tool_use"),id:_.string(),name:_.string(),arguments:_.record(_.unknown()),action:I9,status:V9.optional()}),_.object({type:_.literal("tool_result"),id:_.string(),name:_.string(),content:_.string(),isError:_.boolean().optional()}),_.object({type:_.literal("permission_request"),id:_.string(),reason:_.string(),toolUseId:_.string().optional()}),_.object({type:_.literal("token_usage"),usage:Xf}),_.object({type:_.literal("engine_binding"),engine:_.string().min(1),binding:EV.nullable()}),_.object({type:_.literal("finish"),reason:K9,usage:Xf.optional()}),_.object({type:_.literal("error"),error:_.string()})])});var tR=W(()=>{cR()});var gV,_V,RV,h9,N9,Q9,L9,q9,b9,xR;var mR=W(()=>{YD();gV=/^[a-z0-9][a-z0-9._-]*$/,_V=/^[a-z][a-z0-9-]*$/,RV=/^[a-z][a-z0-9-]*$/,h9=_.enum(["private","team","public"]),N9=_.enum(["manual-approval","auto-low-risk"]),Q9=_.string().min(1).regex(gV,"scope id must be lowercase alphanumeric with . _ -"),L9=_.string().min(1).regex(_V,"scope kind must be kebab-case"),q9=_.string().min(1).regex(RV,"primary soul id must be kebab-case"),b9=_.object({description:_.string().min(1).optional(),path:_.string().min(1)}),xR=_.object({approval:N9.optional(),artifactRoots:_.array(b9).readonly().optional(),id:Q9.optional(),kind:L9,labels:_.array(_.string().min(1)).readonly().optional(),primarySoul:q9,privacy:h9.optional(),retention:_.string().min(1).optional(),schemaVersion:_.literal(1),subject:_.string().min(1).optional()})});var pR=W(()=>{mR()});var WV,GV,CV,aR,z9,j9,Yf,T9,v9,s9,Z9,o9,d9,Mf;var Of=W(()=>{YD();WV=/^[a-z][a-z0-9-]*$/,GV=/^\d+\.\d+\.\d+$/,CV=/^[a-z][a-z0-9-]*$/,aR=/^[a-z][a-z0-9-]*$/,z9=_.string().min(1).regex(WV,"soul id must be kebab-case"),j9=_.string().regex(GV,"soul version must be major.minor.patch"),Yf=_.string().min(1).regex(CV,"scope kind must be kebab-case"),T9=_.object({description:_.string().min(1),id:z9,label:_.string().min(1),version:j9}),v9=_.object({communicationStyle:_.string().min(1),highRiskRequiresApproval:_.boolean(),outOfScopeStrategy:_.string().min(1),riskNotes:_.string().min(1),vagueContextStrategy:_.string().min(1).optional()}),s9=_.object({retention:_.string().min(1),target:_.string().min(1)}),Z9=_.object({artifactTypes:_.array(_.string().min(1)).readonly(),entityTypes:_.array(_.string().min(1)).readonly(),proposalTypes:_.array(_.string().min(1)).readonly(),workflowStates:_.array(_.string().min(1)).readonly()}),o9=_.object({defaultSections:_.array(_.string().min(1).regex(aR)).readonly(),protectedSections:_.array(_.string().min(1).regex(aR)).readonly()}).superRefine((D,u)=>{let r=new Set(D.defaultSections);for(let A of D.protectedSections)if(!r.has(A))u.addIssue({code:_.ZodIssueCode.custom,message:`protected section "${A}" must also appear in defaultSections`,path:["protectedSections"]})}),d9=_.object({boundaries:_.array(_.string().min(1)).min(1).readonly(),packs:_.array(_.string().min(1)).min(1).readonly(),responsibilities:_.array(_.string().min(1)).min(1).readonly(),toolsets:_.array(_.string().min(1)).min(1).readonly()}),Mf=_.object({briefHooks:o9,initProjection:d9,manifest:T9,primaryScopeKind:Yf,retentionDefaults:_.array(s9).readonly(),riskPolicy:v9,schemaPack:Z9,supportedScopeKinds:_.array(Yf).min(1).readonly()}).superRefine((D,u)=>{if(!D.supportedScopeKinds.includes(D.primaryScopeKind))u.addIssue({code:_.ZodIssueCode.custom,message:"primaryScopeKind must appear in supportedScopeKinds",path:["primaryScopeKind"]})})});function y9(D){let u=eR.exec(D);if(!u)return D.trim();return(u[2]??"").trim()}function nV(D,u){let r=eR.exec(D);if(!r)throw Error(`Soul pack ${u} is missing YAML frontmatter`);let A;try{A=e1(r[1]??"")}catch(f){throw Error(`Soul pack ${u} has invalid YAML frontmatter: ${f instanceof Error?f.message:String(f)}`)}try{return Mf.parse(A)}catch(f){if(f instanceof _.ZodError)throw Error(`Soul pack ${u} does not satisfy SoulModule: ${f.issues.map((w)=>w.message).join("; ")}`);throw f}}function Mu(D){let u=HV.parse(D),r=nV(u.soulMd,u.sourcePath);if(r.manifest.id!==u.expectedId)throw Error(`Soul pack ${u.sourcePath} declares id "${r.manifest.id}" but expected "${u.expectedId}"`);return{brainSkillPacks:u.brainSkillPacks??[],module:r,soulBody:y9(u.soulMd),soulMd:u.soulMd.trimEnd(),sourcePath:u.sourcePath}}var eR,HV;var l9=W(()=>{E9();YD();Of();eR=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,HV=_.object({brainSkillPacks:_.custom().optional(),expectedId:_.string().min(1),soulMd:_.string().min(1),sourcePath:_.string().min(1)})});var c9=W(()=>{Of()});var rS=`---
452
+ `;var b_=()=>{};function Yu(D){return Vw[D]??[]}var z_,j_,Xw,iw,Uw,Yw,Mw,Ow,Pw,kw,Iw,Vw;var T_=W(()=>{J_();C_();X_();U_();M_();P_();I_();K_();N_();Hw();L_();b_();z_=gu({expectedId:"kernel.brain-admission",skillMd:q_,sourcePath:"packages/shared/src/brain/skills/kernel/brain-admission/SKILL.md"}),j_=gu({expectedId:"kernel.executor-quality-review",skillMd:s_,sourcePath:"packages/shared/src/brain/skills/kernel/executor-quality-review/SKILL.md"}),Xw=gu({expectedId:"developer.codebase-orientation",skillMd:G_,sourcePath:"packages/shared/src/soul/packs/developer/skills/codebase-orientation/SKILL.md"}),iw=gu({expectedId:"devops-sre.incident-triage",skillMd:H_,sourcePath:"packages/shared/src/soul/packs/devops-sre/skills/incident-triage/SKILL.md"}),Uw=gu({expectedId:"finance-ops.financial-evidence-review",skillMd:i_,sourcePath:"packages/shared/src/soul/packs/finance-ops/skills/financial-evidence-review/SKILL.md"}),Yw=gu({expectedId:"general-assistant.general-task-framing",skillMd:Y_,sourcePath:"packages/shared/src/soul/packs/general-assistant/skills/general-task-framing/SKILL.md"}),Mw=gu({expectedId:"hr-recruiting.candidate-screening",skillMd:O_,sourcePath:"packages/shared/src/soul/packs/hr-recruiting/skills/candidate-screening/SKILL.md"}),Ow=gu({expectedId:"product-designer.design-critique",skillMd:k_,sourcePath:"packages/shared/src/soul/packs/product-designer/skills/design-critique/SKILL.md"}),Pw=gu({expectedId:"project-manager.delivery-risk-review",skillMd:V_,sourcePath:"packages/shared/src/soul/packs/project-manager/skills/delivery-risk-review/SKILL.md"}),kw=gu({expectedId:"qa-reviewer.regression-review",skillMd:h_,sourcePath:"packages/shared/src/soul/packs/qa-reviewer/skills/regression-review/SKILL.md"}),Iw=gu({expectedId:"support-operator.support-case-triage",skillMd:Q_,sourcePath:"packages/shared/src/soul/packs/support-operator/skills/support-case-triage/SKILL.md"}),Vw={developer:[Xw],"devops-sre":[iw],"finance-ops":[Uw],"general-assistant":[Yw],"hr-recruiting":[Mw],"product-designer":[Ow],"project-manager":[Pw],"qa-reviewer":[kw],"support-operator":[Iw]}});var Mf=W(()=>{eF();tE();mE();pF();Hw();T_()});var cu;var v_=W(()=>{cu=class cu extends Error{code;status;constructor(D,u,r){super(r);this.code=D;this.status=u;this.name="AppError"}static badRequest(D,u="BAD_REQUEST"){return new cu(u,400,D)}static notFound(D,u="NOT_FOUND"){return new cu(u,404,D)}static internal(D,u="INTERNAL_ERROR"){return new cu(u,500,D)}toJSON(){return{error:{code:this.code,message:this.message}}}}});var Z_,Nw,o_,hw,d_,JV,Kw,l_,GV;var y_=W(()=>{YD();Yf();Z_=S.enum(["codex","claude-code"]),Nw=S.enum(["project"]),o_=S.enum(["stdio","streamable-http","sse"]),hw=S.union([S.string().min(1),Gw]),d_=S.object({args:S.array(S.string()).optional(),bearerTokenEnvVar:S.string().min(1).optional(),command:S.string().min(1).optional(),description:S.string().min(1).optional(),disabled:S.boolean().optional(),env:S.record(hw).optional(),headers:S.record(hw).optional(),scope:Nw,transport:o_,url:S.string().min(1).optional()}).passthrough(),JV=S.object({issues:S.array(S.object({code:S.string().min(1),message:S.string().min(1),severity:S.enum(["error","warning"])})).optional(),status:S.enum(["pending","pass","warn","fail"])}).passthrough(),Kw=S.object({disabled:S.boolean().optional(),scope:Nw.optional(),source:S.object({ref:S.string().min(1).optional(),type:S.enum(["engine-cli","path","registry","url","manual"])}).passthrough().optional(),status:S.enum(["draft","declared","validated","projected"]).optional(),validation:JV.optional()}).passthrough(),l_=S.object({mcp:S.record(d_).optional(),plugins:S.record(Kw).optional(),policies:S.record(Kw).optional(),skills:S.record(Kw).optional()}).passthrough(),GV=S.object({engines:S.record(Z_,l_),schemaVersion:S.literal(1)})});function CV(D,u){let r=0,A=0,f="";for(let w=0;w<D.length&&f.length<u;w+=1){A=A<<8|D[w],r+=8;while(r>=5&&f.length<u)f+="0123456789abcdefghjkmnpqrstvwxyz"[A>>>r-5&31],r-=5}return f.padEnd(u,"0")}function Qw(){let D=new Uint8Array(10);return globalThis.crypto.getRandomValues(D),`w_${CV(D,12)}`}var c_=()=>{};var t_,p_,x_,m_,a_,e_,DR,uR,rR,AR,fR,Wu,GD,FD,HV,XV,iV,UV,YV,MV,OV,PV,kV,IV,VV,FR,wR,$R,Of;var ER=W(()=>{YD();t_=S.enum(["active","paused","disabled"]),p_=S.enum(["active","archived"]),x_=S.enum(["active","completed","failed","cancelled"]),m_=S.enum(["queued","running","succeeded","failed","cancelled"]),a_=S.enum(["queued","running","succeeded","failed","cancelled"]),e_=S.enum(["status","assistant_delta","tool","file_change","artifact","review","lesson","error","log"]),DR=S.enum(["file","directory","generated","uploaded"]),uR=S.enum(["user","session","system"]),rR=S.enum(["available","missing","archived"]),AR=S.enum(["pass","warn","fail","needs_review"]),fR=S.enum(["proposed","accepted","rejected"]),Wu=S.record(S.string(),S.unknown()),GD=S.string().min(1),FD=S.string().min(1),HV=S.object({id:FD,soulId:FD,name:S.string().min(1),status:t_,defaultEngineId:S.string().nullable(),metadataJson:Wu,createdAt:GD,updatedAt:GD}),XV=S.object({id:FD,workerId:FD,name:S.string().min(1),rootPath:S.string().min(1),type:S.string().min(1),status:p_,sourcePointersJson:S.array(Wu),metadataJson:Wu,createdAt:GD,updatedAt:GD}),iV=S.object({id:FD,workerId:FD,workspaceId:FD,capabilityTemplateId:FD,title:S.string().min(1),context:S.string(),status:x_,metadataJson:Wu,startedAt:GD.nullable(),endedAt:GD.nullable(),createdAt:GD,updatedAt:GD}),UV=S.object({id:FD,sessionId:FD,seq:S.number().int().positive(),input:S.string().min(1),response:S.string().nullable(),status:m_,error:S.string().nullable(),metadataJson:Wu,createdAt:GD,updatedAt:GD}),YV=S.object({id:FD,sessionId:FD,turnId:FD,seq:S.number().int().positive(),engineId:S.string().min(1),engineCommand:S.string().nullable(),status:a_,prompt:S.string().min(1),summary:S.string().nullable(),error:S.string().nullable(),metadataJson:Wu,startedAt:GD.nullable(),finishedAt:GD.nullable(),createdAt:GD,updatedAt:GD}),MV=S.object({id:S.number().int().positive(),sessionId:FD,turnId:FD.nullable(),invocationId:FD.nullable(),seq:S.number().int().nonnegative(),type:e_,payloadJson:Wu,createdAt:GD}),OV=S.object({id:FD,workspaceId:FD,path:S.string().min(1),kind:DR,size:S.number().int().nonnegative().nullable(),mtime:S.number().int().nonnegative().nullable(),hash:S.string().nullable(),source:uR,createdAt:GD,updatedAt:GD}),PV=S.object({id:FD,workspaceId:FD,sessionId:FD.nullable(),turnId:FD.nullable(),invocationId:FD.nullable(),path:S.string().min(1),kind:S.string().min(1),title:S.string().min(1),status:rR,metadataJson:Wu,createdAt:GD,updatedAt:GD}),kV=S.object({id:FD,workspaceId:FD,sessionId:FD.nullable(),turnId:FD.nullable(),artifactId:FD.nullable(),verdict:AR,findingsJson:S.array(Wu),risksJson:S.array(Wu),createdAt:GD}),IV=S.object({id:FD,workspaceId:FD,sourceReviewId:FD.nullable(),statement:S.string().min(1),evidenceJson:S.array(Wu),status:fR,createdAt:GD,updatedAt:GD}),VV=S.object({key:S.string().min(1),valueJson:Wu,updatedAt:GD}),FR=S.enum(["local-cli","byok"]),wR=S.enum(["system","light","dark"]),$R=S.object({command:S.string().min(1),id:FD,installed:S.boolean(),name:S.string().min(1),path:S.string().nullable(),version:S.string().nullable()}),Of=S.object({appearance:wR,byok:S.object({apiKeyRef:S.string(),baseUrl:S.string(),model:S.string(),provider:S.string()}),connectors:S.array(S.object({enabled:S.boolean(),id:S.string().min(1),name:S.string().min(1),status:S.enum(["configured","not_configured"])})),engineId:S.string().min(1),engines:S.array($R),executionMode:FR,externalMcpServers:S.array(S.object({command:S.string(),enabled:S.boolean(),id:S.string().min(1),name:S.string().min(1)})),language:S.string().min(1),localMcpServer:S.object({enabled:S.boolean(),url:S.string()}),updatedAt:GD})});var Lw,qw,Pf,KV,bw,gR;var SR=W(()=>{YD();Lw=S.discriminatedUnion("kind",[S.object({kind:S.literal("file_read"),path:S.string()}),S.object({kind:S.literal("file_edit"),path:S.string(),diff:S.string().optional()}),S.object({kind:S.literal("command_run"),command:S.string()}),S.object({kind:S.literal("search"),query:S.string()}),S.object({kind:S.literal("web_fetch"),url:S.string()}),S.object({kind:S.literal("task_plan"),summary:S.string()}),S.object({kind:S.literal("tool"),toolName:S.string(),arguments:S.record(S.unknown()).optional()}),S.object({kind:S.literal("other"),description:S.string().optional()})]),qw=S.enum(["pending","running","success","failed","pending_approval","denied"]),Pf=S.object({inputTokens:S.number().int().nonnegative(),outputTokens:S.number().int().nonnegative()}),KV=S.record(S.unknown()),bw=S.enum(["stop","tool","length","error","cancelled"]),gR=S.discriminatedUnion("type",[S.object({type:S.literal("assistant_message_delta"),delta:S.string()}),S.object({type:S.literal("thinking_delta"),delta:S.string()}),S.object({type:S.literal("tool_use"),id:S.string(),name:S.string(),arguments:S.record(S.unknown()),action:Lw,status:qw.optional()}),S.object({type:S.literal("tool_result"),id:S.string(),name:S.string(),content:S.string(),isError:S.boolean().optional()}),S.object({type:S.literal("permission_request"),id:S.string(),reason:S.string(),toolUseId:S.string().optional()}),S.object({type:S.literal("token_usage"),usage:Pf}),S.object({type:S.literal("engine_binding"),engine:S.string().min(1),binding:KV.nullable()}),S.object({type:S.literal("finish"),reason:bw,usage:Pf.optional()}),S.object({type:S.literal("error"),error:S.string()})])});var _R=W(()=>{SR()});var hV,NV,QV,sw,zw,jw,Tw,vw,Zw,RR;var nR=W(()=>{YD();hV=/^[a-z0-9][a-z0-9._-]*$/,NV=/^[a-z][a-z0-9-]*$/,QV=/^[a-z][a-z0-9-]*$/,sw=S.enum(["private","team","public"]),zw=S.enum(["manual-approval","auto-low-risk"]),jw=S.string().min(1).regex(hV,"scope id must be lowercase alphanumeric with . _ -"),Tw=S.string().min(1).regex(NV,"scope kind must be kebab-case"),vw=S.string().min(1).regex(QV,"primary soul id must be kebab-case"),Zw=S.object({description:S.string().min(1).optional(),path:S.string().min(1)}),RR=S.object({approval:zw.optional(),artifactRoots:S.array(Zw).readonly().optional(),id:jw.optional(),kind:Tw,labels:S.array(S.string().min(1)).readonly().optional(),primarySoul:vw,privacy:sw.optional(),retention:S.string().min(1).optional(),schemaVersion:S.literal(1),subject:S.string().min(1).optional()})});var BR=W(()=>{nR()});var sV,zV,jV,WR,ow,dw,kf,lw,yw,cw,tw,pw,xw,If;var Vf=W(()=>{YD();sV=/^[a-z][a-z0-9-]*$/,zV=/^\d+\.\d+\.\d+$/,jV=/^[a-z][a-z0-9-]*$/,WR=/^[a-z][a-z0-9-]*$/,ow=S.string().min(1).regex(sV,"soul id must be kebab-case"),dw=S.string().regex(zV,"soul version must be major.minor.patch"),kf=S.string().min(1).regex(jV,"scope kind must be kebab-case"),lw=S.object({description:S.string().min(1),id:ow,label:S.string().min(1),version:dw}),yw=S.object({communicationStyle:S.string().min(1),highRiskRequiresApproval:S.boolean(),outOfScopeStrategy:S.string().min(1),riskNotes:S.string().min(1),vagueContextStrategy:S.string().min(1).optional()}),cw=S.object({retention:S.string().min(1),target:S.string().min(1)}),tw=S.object({artifactTypes:S.array(S.string().min(1)).readonly(),entityTypes:S.array(S.string().min(1)).readonly(),proposalTypes:S.array(S.string().min(1)).readonly(),workflowStates:S.array(S.string().min(1)).readonly()}),pw=S.object({defaultSections:S.array(S.string().min(1).regex(WR)).readonly(),protectedSections:S.array(S.string().min(1).regex(WR)).readonly()}).superRefine((D,u)=>{let r=new Set(D.defaultSections);for(let A of D.protectedSections)if(!r.has(A))u.addIssue({code:S.ZodIssueCode.custom,message:`protected section "${A}" must also appear in defaultSections`,path:["protectedSections"]})}),xw=S.object({boundaries:S.array(S.string().min(1)).min(1).readonly(),packs:S.array(S.string().min(1)).min(1).readonly(),responsibilities:S.array(S.string().min(1)).min(1).readonly(),toolsets:S.array(S.string().min(1)).min(1).readonly()}),If=S.object({briefHooks:pw,initProjection:xw,manifest:lw,primaryScopeKind:kf,retentionDefaults:S.array(cw).readonly(),riskPolicy:yw,schemaPack:tw,supportedScopeKinds:S.array(kf).min(1).readonly()}).superRefine((D,u)=>{if(!D.supportedScopeKinds.includes(D.primaryScopeKind))u.addIssue({code:S.ZodIssueCode.custom,message:"primaryScopeKind must appear in supportedScopeKinds",path:["primaryScopeKind"]})})});function mw(D){let u=JR.exec(D);if(!u)return D.trim();return(u[2]??"").trim()}function vV(D,u){let r=JR.exec(D);if(!r)throw Error(`Soul pack ${u} is missing YAML frontmatter`);let A;try{A=eA(r[1]??"")}catch(f){throw Error(`Soul pack ${u} has invalid YAML frontmatter: ${f instanceof Error?f.message:String(f)}`)}try{return If.parse(A)}catch(f){if(f instanceof S.ZodError)throw Error(`Soul pack ${u} does not satisfy SoulModule: ${f.issues.map((w)=>w.message).join("; ")}`);throw f}}function Mu(D){let u=TV.parse(D),r=vV(u.soulMd,u.sourcePath);if(r.manifest.id!==u.expectedId)throw Error(`Soul pack ${u.sourcePath} declares id "${r.manifest.id}" but expected "${u.expectedId}"`);return{brainSkillPacks:u.brainSkillPacks??[],module:r,soulBody:mw(u.soulMd),soulMd:u.soulMd.trimEnd(),sourcePath:u.sourcePath}}var JR,TV;var aw=W(()=>{Bw();YD();Vf();JR=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,TV=S.object({brainSkillPacks:S.custom().optional(),expectedId:S.string().min(1),soulMd:S.string().min(1),sourcePath:S.string().min(1)})});var ew=W(()=>{Vf()});var HR=`---
453
453
  manifest:
454
454
  id: developer
455
455
  label: Developer
@@ -565,7 +565,7 @@ retentionDefaults: []
565
565
  \u6536\u5230\u4E0D\u5B8C\u6574 prompt \u65F6\uFF0C\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\u4FE1\u606F\uFF0C\u4E0D\u8981\u76F4\u63A5\u8C03 tool \u63A2\u7D22\uFF0C\u4E0D\u8981\u4E3A\u4E86\u907F\u514D\u53CD\u95EE\u800C\u6269\u5927\u641C\u7D22\u8303\u56F4\u8D8A\u8FC7\u5F53\u524D scope\u3002
566
566
 
567
567
  \u4E0D\u76F4\u63A5 ls / grep \u63A2\u7D22\u6574\u4E2A\u9879\u76EE\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u5177\u4F53\u62A5\u9519\u6587\u672C\u3001\u590D\u73B0\u6B65\u9AA4\u3001\u6700\u8FD1\u6539\u52A8\u7684\u6587\u4EF6\u6216\u63D0\u4EA4\u3001\u662F\u5426\u80FD\u5728\u5E72\u51C0 checkout \u4E0A\u590D\u73B0\u3002
568
- `;var uS=()=>{};var fS=`---
568
+ `;var CR=()=>{};var iR=`---
569
569
  manifest:
570
570
  id: devops-sre
571
571
  label: DevOps SRE
@@ -671,7 +671,7 @@ retentionDefaults: []
671
671
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
672
672
 
673
673
  \u4E0D\u76F4\u63A5\u6267\u884C ops \u52A8\u4F5C\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u53D7\u5F71\u54CD\u7CFB\u7EDF / \u65F6\u95F4\u7A97\u53E3 / \u5F53\u524D\u6307\u6807\u6216\u65E5\u5FD7\u5FEB\u7167 / \u5DF2\u7ECF\u5C1D\u8BD5\u8FC7\u54EA\u4E9B\u52A8\u4F5C / incident commander \u662F\u8C01\u3002
674
- `;var AS=()=>{};var wS=`---
674
+ `;var XR=()=>{};var YR=`---
675
675
  manifest:
676
676
  id: finance-ops
677
677
  label: Finance Ops
@@ -775,7 +775,7 @@ retentionDefaults: []
775
775
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
776
776
 
777
777
  \u4E0D\u76F4\u63A5\u7ED9\u51FA\u91D1\u989D\u7ED3\u8BBA\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u8D26\u671F / \u5E01\u79CD / \u6570\u636E\u6765\u6E90\uFF08\u8D26\u5355 ID\u3001ERP \u8868\uFF09/ \u662F\u4F30\u7B97\u8FD8\u662F\u7EC8\u503C / \u662F\u5426\u9700\u8981\u5BA1\u8BA1\u4F50\u8BC1\u3002
778
- `;var FS=()=>{};var ES=`---
778
+ `;var UR=()=>{};var OR=`---
779
779
  manifest:
780
780
  id: general-assistant
781
781
  label: General Assistant
@@ -865,7 +865,7 @@ retentionDefaults: []
865
865
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
866
866
 
867
867
  \u4E0D\u5F3A\u884C\u731C\u6D4B\u610F\u56FE\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u5E0C\u671B\u8FBE\u6210\u7684\u76EE\u6807 / \u662F\u5426\u6709\u65F6\u95F4\u6216\u8D44\u6E90\u9650\u5236 / \u662F\u5426\u9700\u8981\u5207\u6362\u5230\u4E13\u4E1A Soul\uFF08\u5F00\u53D1\u3001HR\u3001Ops\uFF09\u6765\u5904\u7406\u3002
868
- `;var $S=()=>{};var _S=`---
868
+ `;var MR=()=>{};var kR=`---
869
869
  manifest:
870
870
  id: hr-recruiting
871
871
  label: HR Recruiting
@@ -975,7 +975,7 @@ retentionDefaults: []
975
975
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
976
976
 
977
977
  \u4E0D\u76F4\u63A5\u505A\u5019\u9009\u4EBA\u5224\u65AD\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u5C97\u4F4D / \u5019\u9009\u4EBA\u8BC6\u522B\u7B26 / \u6D41\u7A0B\u9636\u6BB5\uFF08screening/interview/offer\uFF09/ \u8BC4\u4F30\u7EF4\u5EA6 / \u662F\u5426\u9700\u8981\u5408\u89C4\u5907\u6CE8\u3002
978
- `;var gS=()=>{};var SS=`---
978
+ `;var PR=()=>{};var VR=`---
979
979
  manifest:
980
980
  id: product-designer
981
981
  label: Product Designer
@@ -1079,7 +1079,7 @@ retentionDefaults: []
1079
1079
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
1080
1080
 
1081
1081
  \u4E0D\u76F4\u63A5\u7ED9\u89C6\u89C9\u5EFA\u8BAE\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u7528\u6237\u573A\u666F / \u5F53\u524D\u75DB\u70B9\u6216\u6570\u636E / \u4E1A\u52A1\u76EE\u6807 / \u662F\u5426\u6709\u73B0\u6210 design system token / \u671F\u671B\u4EA7\u51FA\uFF08\u8349\u56FE\u3001\u89C4\u8303\u3001\u6587\u6848\uFF09\u3002
1082
- `;var RS=()=>{};var JS=`---
1082
+ `;var IR=()=>{};var hR=`---
1083
1083
  manifest:
1084
1084
  id: project-manager
1085
1085
  label: Project Manager
@@ -1182,7 +1182,7 @@ retentionDefaults: []
1182
1182
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
1183
1183
 
1184
1184
  \u4E0D\u66FF\u8D1F\u8D23\u4EBA\u505A\u4E0D\u53EF\u9006\u51B3\u5B9A\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u76F8\u5173\u4EFB\u52A1 / \u963B\u585E\u9879 / \u65F6\u95F4\u7EA6\u675F / \u51B3\u7B56\u8303\u56F4\u4E0E\u6743\u9650 / \u53D7\u5F71\u54CD\u5E72\u7CFB\u4EBA\u3002
1185
- `;var BS=()=>{};var GS=`---
1185
+ `;var KR=()=>{};var QR=`---
1186
1186
  manifest:
1187
1187
  id: qa-reviewer
1188
1188
  label: QA Reviewer
@@ -1288,7 +1288,7 @@ retentionDefaults: []
1288
1288
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
1289
1289
 
1290
1290
  \u4E0D\u66FF\u9879\u76EE\u5BA3\u5E03\u901A\u8FC7 / \u4E0D\u901A\u8FC7\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u88AB\u6D4B\u4EA7\u7269 / \u9A8C\u8BC1\u77E9\u9635\u7684\u8986\u76D6\u9879 / \u5DF2\u8FD0\u884C vs \u672A\u8FD0\u884C / \u6B8B\u4F59\u98CE\u9669\u4E0E\u56DE\u6EDA\u8DEF\u5F84 / \u662F\u5426\u9700\u8981 release gate\u3002
1291
- `;var WS=()=>{};var HS=`---
1291
+ `;var NR=()=>{};var qR=`---
1292
1292
  manifest:
1293
1293
  id: support-operator
1294
1294
  label: Support Operator
@@ -1391,7 +1391,7 @@ retentionDefaults: []
1391
1391
  ## \u6A21\u7CCA\u6216\u7F3A\u5931\u4E0A\u4E0B\u6587
1392
1392
 
1393
1393
  \u4E0D\u76F4\u63A5\u627F\u8BFA\u8865\u507F\u6216\u56DE\u590D\u6A21\u677F\uFF1B\u5148\u4E00\u53E5\u8BDD\u53CD\u95EE\u5173\u952E\u7F3A\u5931\uFF1A\u7528\u6237\u6807\u8BC6 / \u4EA7\u54C1\u6216\u670D\u52A1 / \u671F\u671B\u7ED3\u679C / \u5386\u53F2\u5DE5\u5355 ID / \u662F\u5426\u9700\u8981\u5347\u7EA7\u3002
1394
- `;var CS=()=>{};var uA,rA,AA,fA,FA,wA,$A,EA,gA,t9,x9;var m9=W(()=>{nf();l9();c9();uS();AS();FS();$S();gS();RS();BS();WS();CS();uA=Mu({brainSkillPacks:Yu("developer"),expectedId:"developer",soulMd:rS,sourcePath:"packages/shared/src/soul/packs/developer/SOUL.md"}),rA=Mu({brainSkillPacks:Yu("project-manager"),expectedId:"project-manager",soulMd:JS,sourcePath:"packages/shared/src/soul/packs/project-manager/SOUL.md"}),AA=Mu({brainSkillPacks:Yu("devops-sre"),expectedId:"devops-sre",soulMd:fS,sourcePath:"packages/shared/src/soul/packs/devops-sre/SOUL.md"}),fA=Mu({brainSkillPacks:Yu("product-designer"),expectedId:"product-designer",soulMd:SS,sourcePath:"packages/shared/src/soul/packs/product-designer/SOUL.md"}),FA=Mu({brainSkillPacks:Yu("qa-reviewer"),expectedId:"qa-reviewer",soulMd:GS,sourcePath:"packages/shared/src/soul/packs/qa-reviewer/SOUL.md"}),wA=Mu({brainSkillPacks:Yu("support-operator"),expectedId:"support-operator",soulMd:HS,sourcePath:"packages/shared/src/soul/packs/support-operator/SOUL.md"}),$A=Mu({brainSkillPacks:Yu("finance-ops"),expectedId:"finance-ops",soulMd:wS,sourcePath:"packages/shared/src/soul/packs/finance-ops/SOUL.md"}),EA=Mu({brainSkillPacks:Yu("hr-recruiting"),expectedId:"hr-recruiting",soulMd:_S,sourcePath:"packages/shared/src/soul/packs/hr-recruiting/SOUL.md"}),gA=Mu({brainSkillPacks:Yu("general-assistant"),expectedId:"general-assistant",soulMd:ES,sourcePath:"packages/shared/src/soul/packs/general-assistant/SOUL.md"}),t9=[uA,rA,AA,fA,FA,wA,$A,EA,gA],x9=t9.map((D)=>D.module)});var XS,YS,MS,OS,PS,iS,kS,IS,VS;var KS=W(()=>{m9();XS=uA.module,YS=AA.module,MS=$A.module,OS=gA.module,PS=EA.module,iS=fA.module,kS=rA.module,IS=FA.module,VS=wA.module});var hS=W(()=>{Of();KS();l9();m9();c9()});function v0(D,u={}){let r=qV(D,u.supportedProtocols??[If]);if(r)return{issues:[r],status:"invalid"};let A=Hr.safeParse(D);if(!A.success)return{issues:A.error.issues.map((E)=>({code:bV(E),message:E.message,path:E.path.map(String).join(".")||"<root>",severity:"error"})),status:"invalid"};let f=A.data,w=[];if(u.hostVersion&&!zV(u.hostVersion,f.compatibility.host))w.push({code:"incompatible_host_version",message:`Host ${u.hostVersion} does not satisfy ${f.compatibility.host.minVersion}${f.compatibility.host.maxVersion?`..${f.compatibility.host.maxVersion}`:"+"}.`,path:"compatibility.host",severity:"error"});if(f.storage.namespace!==f.id)w.push({code:"invalid_storage_namespace",message:"storage.namespace must match the Soul App id for v1 discovery.",path:"storage.namespace",severity:"error"});if((u.existingStorageNamespaces??[]).includes(f.storage.namespace))w.push({code:"namespace_collision",message:`storage namespace already exists: ${f.storage.namespace}`,path:"storage.namespace",severity:"error"});let F=new Set(u.availableConnectorIds??[]);if(F.size>0){for(let E of f.connectors.required)if(!F.has(E.id))w.push({code:"missing_required_connector",message:`required connector is not available: ${E.id}`,path:`connectors.required.${E.id}`,severity:"error"})}if(f.modes.hostMounted.supported&&!TV(f))w.push({code:"missing_ui_api_entry",message:"host-mounted Soul Apps must declare at least one UI contribution or API entry.",path:"ui",severity:"error"});if(f.api.entry&&f.api.routePrefix!==`/api/local/apps/${f.id}`)w.push({code:"missing_ui_api_entry",message:`api.routePrefix must equal /api/local/apps/${f.id}.`,path:"api.routePrefix",severity:"error"});if(f.api.localService?.baseUrl&&!b2(f.api.localService.baseUrl))w.push({code:"unsafe_local_service_url",message:"api.localService.baseUrl must use loopback HTTP for mounted local services.",path:"api.localService.baseUrl",severity:"error"});for(let E of f.permissions){let $=vV(E,f);if($)w.push({code:"unsafe_permission_request",message:$,path:`permissions.${E.kind}.${E.target}`,severity:"error"})}for(let E of ZV(f)){if(!E.surface)continue;let $=sV(E.surface);if($)w.push({code:"unsafe_ui_surface",message:$,path:`${E.path}.surface`,severity:"error"})}return{issues:w,manifest:f,status:w.some((E)=>E.severity==="error")?"invalid":"valid"}}function RA(D,u={}){let r;try{r=JSON.parse(D)}catch(f){return{error:`Soul App manifest is not valid JSON: ${f instanceof Error?f.message:String(f)}`,issues:[{code:"invalid_manifest",message:"Soul App manifest is not valid JSON.",severity:"error"}],status:"malformed"}}let A=v0(r,u);if(A.status==="valid"&&A.manifest)return{manifest:A.manifest,status:"ok"};return{error:A.issues.map((f)=>`${f.path??"<root>"}: ${f.message}`).join("; "),issues:A.issues,status:"malformed"}}function b2(D){let u;try{u=new URL(D)}catch{return!1}if(u.protocol!=="http:")return!1;let r=u.hostname.toLowerCase();if(r==="localhost"||r==="::1"||r==="[::1]")return!0;let A=r.split(".");if(A.length!==4||A[0]!=="127")return!1;return A.slice(1).every((f)=>/^\d+$/.test(f)&&Number(f)>=0&&Number(f)<=255)}function _A(D,u,r){let A=new Set;for(let f of u){if(A.has(f.id))D.addIssue({code:_.ZodIssueCode.custom,message:`duplicate id "${f.id}"`,path:r});A.add(f.id)}}function qV(D,u){if(typeof D!=="object"||D===null)return null;let r=D.protocol;if(typeof r!=="string"||u.includes(r))return null;return{code:"unsupported_protocol",message:`unsupported Soul App protocol: ${r}`,path:"protocol",severity:"error"}}function bV(D){let[u]=D.path;if(u==="artifactTypes")return"invalid_artifact_schema";if(u==="storage")return"invalid_storage_namespace";if(u==="permissions")return"unsafe_permission_request";if(u==="api"||u==="ui")return"missing_ui_api_entry";return"invalid_manifest"}function zV(D,u){if(!jV(D))return!1;if(NS(D,u.minVersion)<0)return!1;return u.maxVersion?NS(D,u.maxVersion)<=0:!0}function jV(D){return LS.test(D)}function NS(D,u){let r=QS(D),A=QS(u);for(let f=0;f<3;f++){let w=r[f]-A[f];if(w!==0)return w}return 0}function QS(D){let[u="0",r="0",A="0"]=D.split(".");return[Number(u),Number(r),Number(A)]}function TV(D){return Boolean(D.api.entry||D.ui.routes.length>0||D.ui.panels.length>0||D.ui.artifactPreviews.length>0||D.ui.reviewPanels.length>0||(D.ui.workspaceWidgets?.length??0)>0)}function vV(D,u){let r=D.target.toLowerCase();if(r==="*"||r==="global"||r.includes("secret")||r.includes("vault")||r.includes("host-db"))return`unsafe permission target: ${D.target}`;if(D.kind==="storage"&&D.target!==u.storage.namespace)return`storage permission target must match namespace ${u.storage.namespace}`;if(D.kind==="api"&&u.api.routePrefix&&D.target!==u.api.routePrefix)return`api permission target must match route prefix ${u.api.routePrefix}`;return null}function sV(D){if(D.renderer==="trusted-module")return"trusted-module surfaces are reserved for a future signed first-party module loader.";if(D.renderer==="host-descriptor"&&!D.entry.startsWith("/surfaces/"))return"host-descriptor surfaces must use a /surfaces/* mounted service entry.";if(D.renderer==="sandboxed-frame"&&!D.entry.startsWith("/frames/"))return"sandboxed-frame surfaces must use a /frames/* mounted service entry.";return null}function ZV(D){return[...D.ui.routes.map((u,r)=>({path:`ui.routes.${r}`,surface:u.surface})),...D.ui.panels.map((u,r)=>({path:`ui.panels.${r}`,surface:u.surface})),...D.ui.artifactPreviews.map((u,r)=>({path:`ui.artifactPreviews.${r}`,surface:u.surface})),...D.ui.reviewPanels.map((u,r)=>({path:`ui.reviewPanels.${r}`,surface:u.surface})),...(D.ui.workspaceWidgets??[]).map((u,r)=>({path:`ui.workspaceWidgets.${r}`,surface:u.surface}))]}var If="soul-app/v1",NV,LS,a9,QV,LV,RD,lu,e9,Pf,Dw,uw,rw,Aw,fw,Fw,ww,$w,Ew,gw,q2,Vf,_w,L2,qS,p9,bS,zS,Kf,Rw,Sw,Bw,Jw,Ww,kf,Gw,Cw,Hw,nw,Uw,Xw,Yw,Mw,Ow,Hr,Pw,iw,hf,jS;var Nf=W(()=>{YD();NV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,LS=/^\d+\.\d+\.\d+$/,a9=/^\/[a-z0-9][a-z0-9/_:.-]*$/,QV=/^\/api\/local\/apps\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z0-9/_:.-]*)?$/,LV=/^(storage|connector|artifact|review|memory|ui|api|search):(read|write|create|propose|mount|serve):[^:\s].*$/,RD=_.string().min(1).regex(NV,"Soul App id must be kebab-case"),lu=_.string().regex(LS,"version must be major.minor.patch"),e9=_.literal(If),Pf=_.object({entry:_.string().min(1).optional(),supported:_.boolean()}),Dw=_.object({host:_.object({maxVersion:lu.optional(),minVersion:lu}),sdk:_.object({maxVersion:lu.optional(),minVersion:lu}).optional()}),uw=_.object({description:_.string().min(1),domain:_.string().min(1),id:RD,name:_.string().min(1),version:lu}),rw=_.enum(["embedded","path","package"]),Aw=_.object({id:RD,ref:_.string().min(1),source:rw,version:lu.optional()}),fw=_.object({artifactTypes:_.array(RD).min(1).readonly(),description:_.string().min(1),id:RD,name:_.string().min(1),outputKind:RD,packRefs:_.array(RD).readonly().optional(),promptRef:_.string().min(1),reviewRubricRef:_.string().min(1).optional(),version:lu,workspaceTypes:_.array(RD).min(1).readonly()}),Fw=_.object({artifactTypes:_.array(RD).min(1).readonly(),defaultCapabilityIds:_.array(RD).readonly().optional(),description:_.string().min(1),id:RD,name:_.string().min(1)}),ww=_.object({description:_.string().min(1),id:RD,name:_.string().min(1),previewRef:_.string().min(1).optional(),reviewPolicyRef:_.string().min(1).optional(),schemaRef:_.string().min(1),schemaSha256:_.string().regex(/^[a-f0-9]{64}$/).optional(),version:lu}),$w=_.enum(["route","panel","workspace-widget","artifact-preview","review-panel"]),Ew=_.enum(["host-descriptor","sandboxed-frame","trusted-module"]),gw=_.enum(["app","workspace","session","artifact","review"]),q2=_.string().regex(LV,"requiredPermissions must use kind:action:target"),Vf=_.object({entry:_.string().regex(a9,"surface entry must be an absolute mounted service route"),renderer:Ew,requiredPermissions:_.array(q2).readonly().optional(),scope:gw}),_w=_.object({entry:_.string().min(1),id:RD,label:_.string().min(1),path:_.string().regex(a9,"route path must be an absolute local route"),surface:Vf.optional()}),L2=_.object({entry:_.string().min(1),id:RD,label:_.string().min(1),slot:$w.exclude(["route"]),surface:Vf.optional(),target:RD.optional()}),qS=_.enum(["primary","action","drawer-toggle","refresh","settings"]),p9=_.object({id:RD,label:_.string().min(1),protocolAction:_.string({required_error:"protocolAction is required"}).min(1),requiredPermissions:_.array(q2).readonly().optional(),slot:qS}),bS=_.object({id:RD,label:_.string().min(1),placeholder:_.string().min(1),protocolProvider:_.string({required_error:"protocolProvider is required"}).min(1),requiredPermissions:_.array(q2).readonly().optional()}),zS=_.object({id:RD,label:_.string().min(1),protocolAction:_.string({required_error:"protocolAction is required"}).min(1),requiredPermissions:_.array(q2).readonly().optional()}),Kf=_.object({actions:_.array(p9).readonly().optional(),primaryAction:p9.optional(),search:bS.optional(),settings:zS.optional()}).superRefine((D,u)=>{if(D.primaryAction&&D.primaryAction.slot!=="primary")u.addIssue({code:_.ZodIssueCode.custom,message:"primaryAction slot must be primary",path:["primaryAction","slot"]})}),Rw=_.object({artifactPreviews:_.array(L2).readonly(),panels:_.array(L2).readonly(),reviewPanels:_.array(L2).readonly(),routes:_.array(_w).readonly(),shell:Kf.optional(),workspaceWidgets:_.array(L2).readonly().optional()}),Sw=_.object({entry:_.string().min(1).optional(),localService:_.object({baseUrl:_.string().url().optional(),command:_.array(_.string().min(1)).min(1).readonly().optional(),cwd:_.string().min(1).optional(),healthPath:_.string().regex(a9,"health path must be an absolute local route")}).refine((D)=>D.baseUrl||D.command,{message:"localService must declare baseUrl or command"}).optional(),routePrefix:_.string().regex(QV,"API route prefix must live under /api/local/apps/<appId>").optional()}),Bw=_.object({id:RD,path:_.string().min(1),sha256:_.string().regex(/^[a-f0-9]{64}$/).optional()}),Jw=_.object({migrations:_.array(Bw).readonly(),namespace:RD}),Ww=_.enum(["read","write"]),kf=_.object({access:_.array(Ww).min(1).readonly(),id:RD,reason:_.string().min(1),scopes:_.array(_.string().min(1)).readonly()}),Gw=_.object({optional:_.array(kf).readonly(),required:_.array(kf).readonly()}),Cw=_.enum(["manual-review","host-policy","disabled"]),Hw=_.object({admissionPolicy:Cw,namespace:RD}),nw=_.enum(["storage","connector","artifact","review","memory","ui","api","search"]),Uw=_.enum(["read","write","create","propose","mount","serve"]),Xw=_.object({action:Uw,kind:nw,reason:_.string().min(1),target:_.string().min(1)}),Yw=_.enum(["protocol-handler","http"]),Mw=_.object({kind:Yw,ref:_.string().min(1),timeoutMs:_.number().int().positive().max(60000)}),Ow=_.object({artifact:_.string().min(1).optional(),connector:_.string().min(1).optional(),event:_.string().min(1).optional(),lifecycle:_.string().min(1).optional(),review:_.string().min(1).optional(),runtime:_.string().min(1).optional(),ui:_.string().min(1).optional()}),Hr=_.object({api:Sw,artifactTypes:_.array(ww).min(1).readonly(),capabilities:_.array(fw).min(1).readonly(),compatibility:Dw,connectors:Gw,description:_.string().min(1),exports:Ow,healthcheck:Mw,id:RD,memory:Hw,modes:_.object({hostMounted:Pf,standalone:Pf}),name:_.string().min(1),pack:_.object({refs:_.array(Aw).min(1).readonly()}),permissions:_.array(Xw).min(1).readonly(),protocol:e9,soul:uw,storage:Jw,ui:Rw,version:lu,workspaceTypes:_.array(Fw).min(1).readonly()}).superRefine((D,u)=>{if(!D.modes.standalone.supported&&!D.modes.hostMounted.supported)u.addIssue({code:_.ZodIssueCode.custom,message:"at least one mode must be supported",path:["modes"]});_A(u,D.capabilities,["capabilities"]),_A(u,D.workspaceTypes,["workspaceTypes"]),_A(u,D.artifactTypes,["artifactTypes"]),_A(u,D.pack.refs,["pack","refs"]),_A(u,[...D.ui.routes,...D.ui.panels,...D.ui.artifactPreviews,...D.ui.reviewPanels,...D.ui.workspaceWidgets??[]],["ui"])}),Pw=_.enum(["invalid_manifest","unsupported_protocol","incompatible_host_version","missing_required_connector","invalid_storage_namespace","unsafe_local_service_url","unsafe_permission_request","unsafe_ui_surface","missing_ui_api_entry","invalid_artifact_schema","namespace_collision"]),iw=_.enum(["warning","error"]),hf=_.object({code:Pw,message:_.string().min(1),path:_.string().min(1).optional(),severity:iw}),jS=_.enum(["valid","invalid"])});var oV="35c14e3d4c0fe9fd95c87e9bc47a210e21f99bcb1b079aa99a95bb93e820c8ab",dV="e8bd207be63eab23073cd47e41092f1d753c38d609383206e94334dd984b309c",yV="6a4f3494764431e8785a82865215eabc4c4678dfb4e447eda4d4684f341892a0",lV="0c953a3453ff235c419600073c70c1f155976f448c4567711b511d83668a09e4",TS,vS;var sS=W(()=>{Nf();TS=Hr.parse({api:{entry:"./src/api.ts",routePrefix:"/api/local/apps/aiworker-hr"},artifactTypes:[{description:"Source-backed HR lifecycle profile.",id:"person-profile",name:"Person Profile",previewRef:"./src/ui/person-profile-preview.tsx",reviewPolicyRef:"./review/person-profile.md",schemaRef:"./schemas/person-profile.schema.json",schemaSha256:oV,version:"0.1.0"},{description:"Role-related candidate screen with missing evidence and risks.",id:"candidate-screen",name:"Candidate Screen",previewRef:"./src/ui/candidate-screen-preview.tsx",reviewPolicyRef:"./review/candidate-screen.md",schemaRef:"./schemas/candidate-screen.schema.json",schemaSha256:dV,version:"0.1.0"}],capabilities:[{artifactTypes:["person-profile"],description:"Create a source-backed people profile snapshot.",id:"person-profile",name:"Person Profile",outputKind:"person-profile",packRefs:[],promptRef:"./capabilities/person-profile/prompt.md",reviewRubricRef:"./capabilities/person-profile/review.md",version:"0.1.0",workspaceTypes:["people-profile"]},{artifactTypes:["candidate-screen"],description:"Screen candidate evidence against a role rubric.",id:"candidate-screen",name:"Candidate Screen",outputKind:"candidate-screen",packRefs:[],promptRef:"./capabilities/candidate-screen/prompt.md",reviewRubricRef:"./capabilities/candidate-screen/review.md",version:"0.1.0",workspaceTypes:["role-search","candidate"]}],compatibility:{host:{minVersion:"0.12.0"},sdk:{minVersion:"0.1.0"}},connectors:{optional:[{access:["read"],id:"calendar",reason:"Collect interview availability and touchpoint context.",scopes:["events.read"]}],required:[{access:["read"],id:"ats",reason:"Read candidate packets and role evidence through the Host connector broker.",scopes:["candidates.read","roles.read"]}]},description:"People operations Soul App for profiles, recruiting evidence, lifecycle touchpoints, and HR review policy.",exports:{artifact:"./src/protocol/artifact.ts",connector:"./src/protocol/connectors.ts",lifecycle:"./src/protocol/lifecycle.ts",review:"./src/protocol/review.ts",runtime:"./src/protocol/runtime.ts",ui:"./src/protocol/ui.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:"aiworker-hr",memory:{admissionPolicy:"manual-review",namespace:"aiworker-hr"},modes:{hostMounted:{entry:"./src/host-mounted.ts",supported:!0},standalone:{entry:"./src/standalone.ts",supported:!0}},name:"AIWorker HR",pack:{refs:[{id:"hr-recruiting",ref:"packs/hr-recruiting/SOUL.md",source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped HR domain metadata.",target:"aiworker-hr"},{action:"write",kind:"storage",reason:"Write app-scoped HR domain metadata.",target:"aiworker-hr"},{action:"read",kind:"search",reason:"Read app-owned HR search descriptors.",target:"aiworker-hr"},{action:"write",kind:"search",reason:"Publish app-owned HR search descriptors.",target:"aiworker-hr"},{action:"read",kind:"connector",reason:"Read HR evidence through Host connector broker.",target:"ats"},{action:"write",kind:"artifact",reason:"Create reviewable HR artifacts.",target:"person-profile"},{action:"create",kind:"review",reason:"Create HR review rubrics and findings.",target:"hr-review"},{action:"propose",kind:"memory",reason:"Propose reviewed HR lessons into the app namespace.",target:"aiworker-hr"},{action:"mount",kind:"ui",reason:"Mount HR workbench contributions.",target:"hr-workbench"},{action:"serve",kind:"api",reason:"Serve HR scoped API routes.",target:"/api/local/apps/aiworker-hr"}],protocol:"soul-app/v1",soul:{description:"HR Soul for people operations, recruiting, onboarding, offboarding, and sensitive evidence review.",domain:"hr-people-ops",id:"hr",name:"HR",version:"0.1.0"},storage:{migrations:[{id:"hr-initial",path:"./migrations/0001_hr.sql"}],namespace:"aiworker-hr"},ui:{artifactPreviews:[{entry:"./src/ui/person-profile-preview.tsx",id:"person-profile-preview",label:"Person profile preview",slot:"artifact-preview",target:"person-profile"}],panels:[{entry:"./src/ui/profile-panel.tsx",id:"hr-profile-panel",label:"Profile panel",slot:"panel",surface:{entry:"/surfaces/panels/hr-profile-panel",renderer:"host-descriptor",requiredPermissions:["storage:read:aiworker-hr"],scope:"workspace"}}],reviewPanels:[{entry:"./src/ui/review-panel.tsx",id:"hr-review-panel",label:"HR review panel",slot:"review-panel"}],routes:[{entry:"./src/ui/hr-route.tsx",id:"hr-home",label:"HR",path:"/hr",surface:{entry:"/surfaces/routes/hr-home",renderer:"host-descriptor",requiredPermissions:["ui:mount:hr-workbench"],scope:"app"}}],shell:{actions:[{id:"refresh-people",label:"Refresh",protocolAction:"people.refresh",requiredPermissions:["storage:read:aiworker-hr"],slot:"refresh"},{id:"toggle-evidence-drawer",label:"Evidence",protocolAction:"drawers.evidence.toggle",requiredPermissions:["connector:read:ats"],slot:"drawer-toggle"}],primaryAction:{id:"create-people-profile",label:"New people profile",protocolAction:"peopleProfiles.create",requiredPermissions:["storage:write:aiworker-hr","search:write:aiworker-hr"],slot:"primary"},search:{id:"people-profile-search",label:"Search people profiles",placeholder:"Search people profiles",protocolProvider:"peopleProfiles.search",requiredPermissions:["search:read:aiworker-hr"]},settings:{id:"hr-settings",label:"HR settings",protocolAction:"settings.open",requiredPermissions:["api:serve:/api/local/apps/aiworker-hr"]}},workspaceWidgets:[{entry:"./src/ui/people-widget.tsx",id:"hr-people-widget",label:"People widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/hr-people-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"people-profile"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["person-profile"],defaultCapabilityIds:["person-profile"],description:"Profile-centered workspace for one person lifecycle.",id:"people-profile",name:"People Profile"},{artifactTypes:["candidate-screen"],defaultCapabilityIds:["candidate-screen"],description:"Recruiting role workspace with candidate evidence and review.",id:"role-search",name:"Role Search"},{artifactTypes:["candidate-screen"],defaultCapabilityIds:["candidate-screen"],description:"Focused candidate packet workspace.",id:"candidate",name:"Candidate"}]}),vS=Hr.parse({api:{entry:"./src/api.ts",routePrefix:"/api/local/apps/aiworker-qa"},artifactTypes:[{description:"Coverage matrix mapped to release risk.",id:"regression-matrix",name:"Regression Matrix",previewRef:"./src/ui/regression-matrix-preview.tsx",reviewPolicyRef:"./review/regression-matrix.md",schemaRef:"./schemas/regression-matrix.schema.json",schemaSha256:yV,version:"0.1.0"},{description:"Go/no-go release readiness artifact.",id:"release-gate",name:"Release Gate",previewRef:"./src/ui/release-gate-preview.tsx",reviewPolicyRef:"./review/release-gate.md",schemaRef:"./schemas/release-gate.schema.json",schemaSha256:lV,version:"0.1.0"}],capabilities:[{artifactTypes:["regression-matrix"],description:"Build regression coverage from change and test evidence.",id:"regression-matrix",name:"Regression Matrix",outputKind:"regression-matrix",packRefs:[],promptRef:"./capabilities/regression-matrix/prompt.md",reviewRubricRef:"./capabilities/regression-matrix/review.md",version:"0.1.0",workspaceTypes:["release","test-suite"]},{artifactTypes:["release-gate"],description:"Summarize release blockers, residual risk, and go/no-go recommendation.",id:"release-gate",name:"Release Gate",outputKind:"release-gate",packRefs:[],promptRef:"./capabilities/release-gate/prompt.md",reviewRubricRef:"./capabilities/release-gate/review.md",version:"0.1.0",workspaceTypes:["release"]}],compatibility:{host:{minVersion:"0.12.0"},sdk:{minVersion:"0.1.0"}},connectors:{optional:[{access:["read"],id:"issue-tracker",reason:"Read defect evidence through Host connector broker.",scopes:["issues.read"]}],required:[{access:["read"],id:"ci",reason:"Read CI and test evidence through Host connector broker.",scopes:["runs.read","artifacts.read"]}]},description:"Quality Soul App for release workspaces, regression evidence, defect triage, and release gate review.",exports:{artifact:"./src/protocol/artifact.ts",connector:"./src/protocol/connectors.ts",lifecycle:"./src/protocol/lifecycle.ts",review:"./src/protocol/review.ts",runtime:"./src/protocol/runtime.ts",ui:"./src/protocol/ui.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:"aiworker-qa",memory:{admissionPolicy:"manual-review",namespace:"aiworker-qa"},modes:{hostMounted:{entry:"./src/host-mounted.ts",supported:!0},standalone:{entry:"./src/standalone.ts",supported:!0}},name:"AIWorker QA",pack:{refs:[{id:"qa-reviewer",ref:"packs/qa-reviewer/SOUL.md",source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped QA domain metadata.",target:"aiworker-qa"},{action:"write",kind:"storage",reason:"Write app-scoped QA domain metadata.",target:"aiworker-qa"},{action:"read",kind:"search",reason:"Read app-owned QA search descriptors.",target:"aiworker-qa"},{action:"write",kind:"search",reason:"Publish app-owned QA search descriptors.",target:"aiworker-qa"},{action:"read",kind:"connector",reason:"Read CI evidence through Host connector broker.",target:"ci"},{action:"write",kind:"artifact",reason:"Create reviewable QA release artifacts.",target:"release-gate"},{action:"create",kind:"review",reason:"Create QA review rubrics and findings.",target:"qa-review"},{action:"propose",kind:"memory",reason:"Propose reviewed QA lessons into the app namespace.",target:"aiworker-qa"},{action:"mount",kind:"ui",reason:"Mount QA workbench contributions.",target:"qa-workbench"},{action:"serve",kind:"api",reason:"Serve QA scoped API routes.",target:"/api/local/apps/aiworker-qa"}],protocol:"soul-app/v1",soul:{description:"QA Soul for release evidence, regression coverage, defect triage, and release readiness review.",domain:"quality-assurance",id:"qa",name:"QA",version:"0.1.0"},storage:{migrations:[{id:"qa-initial",path:"./migrations/0001_qa.sql"}],namespace:"aiworker-qa"},ui:{artifactPreviews:[{entry:"./src/ui/release-gate-preview.tsx",id:"release-gate-preview",label:"Release gate preview",slot:"artifact-preview",target:"release-gate"}],panels:[{entry:"./src/ui/release-panel.tsx",id:"qa-release-panel",label:"Release panel",slot:"panel",surface:{entry:"/surfaces/panels/qa-release-panel",renderer:"host-descriptor",requiredPermissions:["storage:read:aiworker-qa"],scope:"workspace"}}],reviewPanels:[{entry:"./src/ui/review-panel.tsx",id:"qa-review-panel",label:"QA review panel",slot:"review-panel"}],routes:[{entry:"./src/ui/qa-route.tsx",id:"qa-home",label:"QA",path:"/qa",surface:{entry:"/surfaces/routes/qa-home",renderer:"host-descriptor",requiredPermissions:["ui:mount:qa-workbench"],scope:"app"}}],shell:{actions:[{id:"refresh-release",label:"Refresh",protocolAction:"release.refresh",requiredPermissions:["storage:read:aiworker-qa"],slot:"refresh"}],primaryAction:{id:"create-release-gate",label:"New release gate",protocolAction:"releaseGates.create",requiredPermissions:["storage:write:aiworker-qa","search:write:aiworker-qa"],slot:"primary"},search:{id:"release-search",label:"Search releases",placeholder:"Search releases",protocolProvider:"releases.search",requiredPermissions:["search:read:aiworker-qa"]},settings:{id:"qa-settings",label:"QA settings",protocolAction:"settings.open",requiredPermissions:["api:serve:/api/local/apps/aiworker-qa"]}},workspaceWidgets:[{entry:"./src/ui/release-widget.tsx",id:"qa-release-widget",label:"Release widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/qa-release-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"release"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["regression-matrix","release-gate"],defaultCapabilityIds:["regression-matrix","release-gate"],description:"Release readiness workspace with test and defect evidence.",id:"release",name:"Release"},{artifactTypes:["regression-matrix"],defaultCapabilityIds:["regression-matrix"],description:"Focused test suite coverage workspace.",id:"test-suite",name:"Test Suite"}]})});var kw,Iw,Vw,Kw,ZS;var oS=W(()=>{YD();kw=_.enum(["audit","connector","secret","storage"]),Iw=_.enum(["active","disabled","not_configured","planned"]),Vw=_.object({appScoped:_.boolean(),capabilities:_.array(_.string().min(1)).readonly(),configured:_.boolean(),description:_.string().min(1),enabled:_.boolean(),id:_.string().min(1),kind:kw,label:_.string().min(1),local:_.boolean(),notes:_.array(_.string().min(1)).readonly().optional(),status:Iw}),Kw=_.object({activeCount:_.number().int().nonnegative(),configuredCount:_.number().int().nonnegative(),plannedCount:_.number().int().nonnegative(),providerCount:_.number().int().nonnegative()}),ZS=_.object({providers:_.array(Vw).readonly(),summary:Kw})});function MD(D,u,r,A,f,w,F){return{description:f,id:u,inputHints:w,name:r,outputKind:A,prompt:`Use the ${r} capability template. Produce a ${A} business artifact for the selected ${D.toUpperCase()} Soul project.`,reviewRubric:F,soulId:D}}var dS,hw,Nw,c,dl;var Qw=W(()=>{YD();dS=_.enum(["available","coming_soon"]),hw=_.object({description:_.string().min(1),id:_.string().min(1),inputHints:_.array(_.string().min(1)).readonly(),name:_.string().min(1),outputKind:_.string().min(1),prompt:_.string().min(1),reviewRubric:_.array(_.string().min(1)).readonly(),soulId:_.string().min(1)}),Nw=_.object({defaultTemplates:_.array(_.string().min(1)).readonly(),description:_.string().min(1),domain:_.string().min(1),id:_.string().min(1),name:_.string().min(1),status:dS}),c={evidence:"Output cites the supplied context and labels missing evidence.",action:"Next action is concrete, owned, and useful for a human reviewer.",risk:"Risks and assumptions are separated from confirmed facts."},dl=[MD("hr","person-profile","Person Profile","person-profile","Create a source-backed HR profile snapshot with lifecycle stage, evidence, risks, and next steps.",["Person context","Lifecycle stage","Relevant HR notes"],[c.evidence,c.risk,"No protected-class inference or unsupported personal judgment."]),MD("hr","lifecycle-next-step","Lifecycle Next Step","lifecycle-next-step","Prepare the next reviewable HR touchpoint for a person across recruiting, onboarding, employee care, or offboarding.",["Person profile","Current lifecycle moment","Open questions"],[c.evidence,c.action,"Decision and employment commitments remain human-owned."]),MD("hr","candidate-screen","Candidate Screen","candidate-screen","Screen a candidate against a role and identify strengths, gaps, and follow-ups.",["Role requirements","Resume or profile","Relevant notes"],[c.evidence,c.risk,"No protected-class inference."]),MD("hr","interview-brief","Interview Brief","interview-brief","Prepare a structured interviewer brief with evidence-backed questions.",["Role stage","Candidate packet","Interview goals"],[c.evidence,c.action,"Questions target missing signal."]),MD("hr","role-rubric","Role Rubric","role-rubric","Turn role expectations into a hiring rubric and scoring guide.",["Role description","Level expectations","Team constraints"],[c.action,"Criteria are observable and role-related.",c.risk]),MD("hr","onboarding-plan","Onboarding Plan","onboarding-plan","Draft a 30/60/90 onboarding or check-in plan with owners, evidence, risks, and follow-up prompts.",["Employee profile","Role expectations","Team context"],[c.evidence,c.action,"No private or unsupported employment claims."]),MD("hr","offboarding-summary","Offboarding Summary","offboarding-summary","Prepare an offboarding or alumni handoff summary with knowledge-transfer notes, open actions, and privacy guardrails.",["Departing employee context","Handoff notes","Open actions"],[c.evidence,c.action,"Sensitive details are minimized and reviewed."]),MD("hr","evidence-matrix","Evidence Matrix","evidence-matrix","Compare candidates against role signals with source-backed coverage, gaps, and conflicts.",["Role rubric","Candidate evidence packets","Interview notes or scorecards"],[c.evidence,"Coverage states strong, weak, missing, or conflict.","No candidate ranking without human review."]),MD("hr","roundup-packet","Roundup Packet","roundup-packet","Prepare a hiring roundup packet with rubric snapshot, comparison, missing signals, and decision guardrails.",["Role rubric","Evidence matrix","Scorecard summaries"],[c.evidence,c.risk,"Decision placeholders remain human-owned."]),MD("hr","hiring-risk","Hiring Risk","hiring-risk","Summarize hiring risks, uncertainty, and decision guardrails.",["Candidate evidence","Scorecard notes","Decision constraints"],[c.evidence,c.risk,"Decision remains human-owned."]),MD("pm","prd-draft","PRD Draft","prd-draft","Draft a PRD from goals, user evidence, constraints, and success metrics.",["Problem statement","User evidence","Constraints"],[c.action,"Scope and non-goals are explicit.",c.risk]),MD("pm","decision-record","Decision Record","decision-record","Capture options, tradeoffs, decision, and follow-up owners.",["Decision context","Options considered","Stakeholder notes"],[c.evidence,c.action,"Tradeoffs are balanced."]),MD("pm","roadmap-slice","Roadmap Slice","roadmap-slice","Break a goal into a sequenced roadmap slice with dependencies.",["Goal","Time horizon","Dependencies"],[c.action,c.risk,"Milestones are inspectable."]),MD("pm","status-report","Status Report","status-report","Produce a concise stakeholder status report with risks and next decisions.",["Current status","Risks","Decisions needed"],[c.evidence,c.action,"No vague summary filler."]),MD("qa","test-plan","Test Plan","test-plan","Create a test plan matched to release scope and user-facing risk.",["Release scope","Acceptance criteria","Known risks"],[c.action,"Coverage maps to risk.",c.risk]),MD("qa","regression-matrix","Regression Matrix","regression-matrix","Build a regression matrix with coverage, evidence, gaps, and recommendation.",["Changed behavior","Existing tests","Release criteria"],[c.evidence,"Gaps are visible.",c.risk]),MD("qa","defect-triage","Defect Triage","defect-triage","Prioritize defects with reproduction evidence and release impact.",["Bug reports","Logs/screenshots","Release target"],[c.evidence,c.action,"Observed failure and suspected cause are separate."]),MD("qa","release-gate","Release Gate","release-gate","Summarize release readiness, blockers, residual risk, and go/no-go recommendation.",["Test evidence","Known defects","Release policy"],[c.evidence,c.risk,"Recommendation is explicit."]),MD("devops","deploy-checklist","Deploy Checklist","deploy-checklist","Prepare a deploy checklist with rollback, monitoring, and owner steps.",["Change summary","Environment","Rollback plan"],[c.action,c.risk,"Steps are operationally concrete."]),MD("devops","incident-review","Incident Review","incident-review","Produce an incident review with timeline, impact, contributing factors, and actions.",["Timeline","Signals","Impact notes"],[c.evidence,c.action,"Blameless language and source boundaries."]),MD("devops","runbook-update","Runbook Update","runbook-update","Convert new operational learning into a runbook update.",["Current runbook","Observed gap","Operational context"],[c.action,"Procedure is repeatable.",c.risk]),MD("devops","capacity-summary","Capacity Summary","capacity-summary","Summarize capacity signals, thresholds, and scaling recommendations.",["Metrics","Service context","Forecast horizon"],[c.evidence,c.risk,"Recommendation states confidence."])]});function Qf(D,u){return`${D}.${u}`}function SA(D,u="available"){return{defaultTemplates:D.workspaceTypes.flatMap((r)=>(r.defaultCapabilityIds??[]).map((A)=>Qf(D.id,A))),description:D.description,domain:D.soul.domain,id:D.id,name:D.name,status:u}}function Tw(D,u){return{description:u.description,id:Qf(D.id,u.id),inputHints:[`Workspace types: ${u.workspaceTypes.join(", ")}`,`Artifact types: ${u.artifactTypes.join(", ")}`,`Prompt ref: ${u.promptRef}`],name:u.name,outputKind:u.outputKind,prompt:[`Use the ${D.name} Soul App capability ${u.name}.`,`Use prompt asset ${u.promptRef}.`,`Produce a ${u.outputKind} business artifact for the selected ${D.soul.name} workspace.`,"Keep Host runtime, connector, artifact, review, and memory ownership intact."].join(" "),reviewRubric:u.reviewRubricRef?[`Review rubric ref: ${u.reviewRubricRef}`,"Evidence, missing facts, risks, and human review notes remain explicit."]:["Evidence, missing facts, risks, and human review notes remain explicit."],soulId:D.id}}function BA(D){return D.capabilities.map((u)=>Tw(D,u))}function vw(D){let u=[...D.ui.routes,...D.ui.panels,...D.ui.artifactPreviews,...D.ui.reviewPanels,...D.ui.workspaceWidgets??[]].filter((r)=>r.surface);return{apiRoutePrefix:D.api.routePrefix??null,artifactPreviewIds:D.ui.artifactPreviews.map((r)=>r.id),descriptorSurfaceIds:u.filter((r)=>r.surface?.renderer==="host-descriptor").map((r)=>r.id),frameSurfaceIds:u.filter((r)=>r.surface?.renderer==="sandboxed-frame").map((r)=>r.id),panelIds:D.ui.panels.map((r)=>r.id),reviewPanelIds:D.ui.reviewPanels.map((r)=>r.id),routePaths:D.ui.routes.map((r)=>r.path),shell:D.ui.shell??null,surfaceIds:u.map((r)=>r.id),workspaceWidgetIds:(D.ui.workspaceWidgets??[]).map((r)=>r.id)}}function Lf(D){return jw.parse({appId:D.manifest.id,healthMessage:D.healthMessage??null,healthStatus:D.healthStatus??"unknown",manifest:D.manifest,manifestDigest:D.manifestDigest,mountedContribution:vw(D.manifest),projectedCapabilities:BA(D.manifest),projectedSoul:SA(D.manifest,D.status==="enabled"?"available":"coming_soon"),sourceKind:D.sourceKind,sourceRef:D.sourceRef,status:D.status,validationIssues:D.validationIssues??[],version:D.manifest.version})}var Lw,qw,bw,zw,jw;var yS=W(()=>{YD();Qw();Nf();Lw=_.enum(["installed","enabled","disabled","error"]),qw=_.enum(["manifest-path","inline"]),bw=_.enum(["unknown","pass","warn","fail"]),zw=_.object({apiRoutePrefix:_.string().min(1).nullable(),artifactPreviewIds:_.array(_.string().min(1)).readonly(),descriptorSurfaceIds:_.array(_.string().min(1)).readonly(),frameSurfaceIds:_.array(_.string().min(1)).readonly(),panelIds:_.array(_.string().min(1)).readonly(),reviewPanelIds:_.array(_.string().min(1)).readonly(),routePaths:_.array(_.string().min(1)).readonly(),shell:Kf.nullable(),surfaceIds:_.array(_.string().min(1)).readonly(),workspaceWidgetIds:_.array(_.string().min(1)).readonly()}),jw=_.object({appId:_.string().min(1),healthMessage:_.string().nullable(),healthStatus:bw,manifest:Hr,manifestDigest:_.string().min(1),mountedContribution:zw,projectedCapabilities:_.array(hw).readonly(),projectedSoul:Nw,sourceKind:qw,sourceRef:_.string().min(1),status:Lw,validationIssues:_.array(hf).readonly(),version:_.string().min(1)})});var lS=W(()=>{sS();Nf();oS();yS()});function S0(D,u,r,A,f,w){return{description:w,id:D,label:u,outputKind:f,prompt:w,scope:r,templateId:A}}var cS;var tS=W(()=>{cS={actions:[S0("summarize-profile","Summarize profile","person","aiworker-hr.person-profile","person-profile","Create a source-backed HR profile snapshot for this person. Separate confirmed facts, missing evidence, risks, and human follow-up notes."),S0("prepare-next-step","Prepare next step","lifecycle","aiworker-hr.lifecycle-next-step","lifecycle-next-step","Prepare the next HR touchpoint for this person. Use the current lifecycle stage, evidence, open questions, and human-owned decision guardrails."),S0("extract-evidence","Extract evidence","person","aiworker-hr.candidate-screen","candidate-screen","Extract source-backed evidence from the supplied role packet, resume, employee notes, interview notes, or lifecycle records. Preserve missing evidence and do not infer protected-class attributes."),S0("draft-interview-kit","Draft interview kit","interview","aiworker-hr.interview-brief","interview-brief","Draft a structured interview kit with evidence-backed questions, focus signals, and scorecard guidance."),S0("draft-onboarding-plan","Draft onboarding plan","employee","aiworker-hr.onboarding-plan","onboarding-plan","Draft a 30/60/90 onboarding or check-in plan with evidence, owner placeholders, open risks, and review notes."),S0("prepare-offboarding-summary","Prepare offboarding summary","alumni","aiworker-hr.offboarding-summary","offboarding-summary","Prepare an offboarding or alumni handoff summary. Keep sensitive details minimized and separate confirmed facts from assumptions."),S0("build-evidence-matrix","Build evidence matrix","pool","aiworker-hr.evidence-matrix","evidence-matrix","Build an evidence matrix across people and role/lifecycle signals. Use source references and mark weak, missing, or conflicting evidence."),S0("check-risky-wording","Check risky wording","artifact","aiworker-hr.hiring-risk","hiring-risk","Review the current artifact for protected-class inference, unsupported personal judgments, privacy leakage, and unreviewed employment commitments.")],artifactKinds:["person-profile","lifecycle-next-step","candidate-screen","interview-brief","onboarding-plan","offboarding-summary","evidence-matrix","hiring-risk"],description:"People-first HR workbench for profile context, lifecycle moments, evidence, reviewable next steps, and memory candidates.",fallback:"generic-worker-studio",id:"hr-people-workbench",name:"People Workbench",primaryObjects:[{description:"A selected person profile with lifecycle stage, evidence coverage, open risks, and next step.",id:"person-profile",label:"Person Profile"},{description:"A recruiting, onboarding, employee-care, or offboarding moment that needs a reviewable next artifact.",id:"lifecycle-moment",label:"Lifecycle Moment"},{description:"Source-backed timeline of sessions, artifacts, reviews, and memory candidates for the person.",id:"profile-timeline",label:"Profile Timeline"},{description:"People-level coverage view across candidates, employees, and alumni without automated ranking.",id:"people-board",label:"People Board"}],reviewChecklist:["Evidence is tied to role-related or lifecycle-relevant criteria and source references.","Missing, weak, and conflicting signals are visible.","Protected-class inference, unsupported personal judgments, and sensitive leakage are absent.","Person-sensitive details are not promoted into durable memory without review.","Hiring and employment decisions remain explicitly human-owned."],soulId:"aiworker-hr",version:"0.1.0",views:[{description:"Lifecycle filters, evidence inventory, and review guardrails.",id:"lifecycle-rail",label:"Lifecycle rail",region:"rail"},{description:"Flex poster wall of people profiles and their next HR moment.",id:"profile-wall",label:"Profile wall",region:"main"},{description:"Selected profile loop with next step, agent proposal, review, and memory status.",id:"profile-loop-panel",label:"Profile loop panel",region:"tray"},{description:"Artifact quality, privacy, compliance, and memory-candidate review.",id:"review-panel",label:"Review panel",region:"review"}],workspaceTypes:[{description:"A people profile workspace that tracks a person through HR lifecycle moments.",id:"people-profile",label:"People Profile",primary:!0},{description:"A hiring role search with rubric, candidates, interviews, evidence matrix, and roundup packet.",id:"role-search",label:"Role Search",primary:!1},{description:"A focused candidate packet inside a recruiting loop.",id:"candidate",label:"Candidate",primary:!1},{description:"An active employee profile for onboarding, check-in, growth, or retention support.",id:"employee",label:"Employee",primary:!1},{description:"A departed employee or alumni profile for offboarding, handoff, or knowledge capture.",id:"alumni",label:"Alumni",primary:!1},{description:"A reusable pool of future candidate evidence.",id:"talent-pool",label:"Talent Pool",primary:!1}]}});var xS,mS,pS,aS,eS,aV;var DB=W(()=>{YD();tS();xS=_.enum(["generic-worker-studio"]),mS=_.object({description:_.string().min(1),id:_.string().min(1),label:_.string().min(1)}),pS=_.object({description:_.string().min(1),id:_.string().min(1),label:_.string().min(1),region:_.enum(["rail","main","tray","review"])}),aS=_.object({description:_.string().min(1),id:_.string().min(1),label:_.string().min(1),outputKind:_.string().min(1),prompt:_.string().min(1),scope:_.enum(["person","role","candidate","employee","alumni","pool","interview","artifact","lifecycle"]),templateId:_.string().min(1)}),eS=_.object({description:_.string().min(1),id:_.string().min(1),label:_.string().min(1),primary:_.boolean().default(!1)}),aV=_.object({actions:_.array(aS).min(1).readonly(),artifactKinds:_.array(_.string().min(1)).min(1).readonly(),description:_.string().min(1),fallback:xS,id:_.string().min(1),name:_.string().min(1),primaryObjects:_.array(mS).min(1).readonly(),reviewChecklist:_.array(_.string().min(1)).min(1).readonly(),soulId:_.string().min(1),version:_.string().min(1),views:_.array(pS).min(1).readonly(),workspaceTypes:_.array(eS).min(1).readonly()})});class sw{packs=new Map;register(D){let u=AB.parse(D);if(this.packs.has(u.id))throw Error(`WorkerPackRegistry: duplicate worker pack id "${u.id}"`);this.packs.set(u.id,u)}get(D){return this.packs.get(D)}require(D){let u=this.get(D);if(!u)throw Error(`WorkerPackRegistry: unknown worker pack id "${D}"`);return u}list(){return Array.from(this.packs.values())}ids(){return Array.from(this.packs.keys())}}function fB(D=[]){let u=new sw;for(let r of D)u.register(r);return u}var eV,uB,rB,AB,FB,DK;var wB=W(()=>{YD();eV=/^[a-z][a-z0-9-]*$/,uB=_.string().min(1).regex(eV,"worker pack id must be kebab-case"),rB=_.object({description:_.string().min(1),id:_.string().min(1),prompt:_.string().min(1),title:_.string().min(1)}),AB=_.object({artifactKinds:_.array(_.string().min(1)).min(1).readonly(),defaultReviewChecklist:_.array(_.string().min(1)).min(1).readonly(),description:_.string().min(1),domain:_.string().min(1),domainMd:_.string().min(1),id:uB,label:_.string().min(1),skillMd:_.string().min(1),workOrderTemplates:_.array(rB).min(1).readonly()}).superRefine((D,u)=>{if(!D.skillMd.includes("# "))u.addIssue({code:_.ZodIssueCode.custom,message:"skillMd must contain a markdown heading",path:["skillMd"]});if(!D.domainMd.includes("# "))u.addIssue({code:_.ZodIssueCode.custom,message:"domainMd must contain a markdown heading",path:["domainMd"]})});FB=[{artifactKinds:["patch-plan","code-review-report","verification-report"],defaultReviewChecklist:["Evidence is grounded in repository files and commands.","Risks and verification gaps are explicit.","Recommended next action is concrete and scoped."],description:"Codebase analysis, implementation planning, and verification reports for software workspaces.",domain:"software-workspace",domainMd:`# Developer Domain
1394
+ `;var LR=()=>{};var u1,r1,A1,f1,F1,w1,$1,E1,g1,D9,u9;var r9=W(()=>{Mf();aw();ew();CR();XR();UR();MR();PR();IR();KR();NR();LR();u1=Mu({brainSkillPacks:Yu("developer"),expectedId:"developer",soulMd:HR,sourcePath:"packages/shared/src/soul/packs/developer/SOUL.md"}),r1=Mu({brainSkillPacks:Yu("project-manager"),expectedId:"project-manager",soulMd:hR,sourcePath:"packages/shared/src/soul/packs/project-manager/SOUL.md"}),A1=Mu({brainSkillPacks:Yu("devops-sre"),expectedId:"devops-sre",soulMd:iR,sourcePath:"packages/shared/src/soul/packs/devops-sre/SOUL.md"}),f1=Mu({brainSkillPacks:Yu("product-designer"),expectedId:"product-designer",soulMd:VR,sourcePath:"packages/shared/src/soul/packs/product-designer/SOUL.md"}),F1=Mu({brainSkillPacks:Yu("qa-reviewer"),expectedId:"qa-reviewer",soulMd:QR,sourcePath:"packages/shared/src/soul/packs/qa-reviewer/SOUL.md"}),w1=Mu({brainSkillPacks:Yu("support-operator"),expectedId:"support-operator",soulMd:qR,sourcePath:"packages/shared/src/soul/packs/support-operator/SOUL.md"}),$1=Mu({brainSkillPacks:Yu("finance-ops"),expectedId:"finance-ops",soulMd:YR,sourcePath:"packages/shared/src/soul/packs/finance-ops/SOUL.md"}),E1=Mu({brainSkillPacks:Yu("hr-recruiting"),expectedId:"hr-recruiting",soulMd:kR,sourcePath:"packages/shared/src/soul/packs/hr-recruiting/SOUL.md"}),g1=Mu({brainSkillPacks:Yu("general-assistant"),expectedId:"general-assistant",soulMd:OR,sourcePath:"packages/shared/src/soul/packs/general-assistant/SOUL.md"}),D9=[u1,r1,A1,f1,F1,w1,$1,E1,g1],u9=D9.map((D)=>D.module)});var zR,jR,TR,vR,ZR,oR,dR,lR,yR;var cR=W(()=>{r9();zR=u1.module,jR=A1.module,TR=$1.module,vR=g1.module,ZR=E1.module,oR=f1.module,dR=r1.module,lR=F1.module,yR=w1.module});var tR=W(()=>{Vf();cR();aw();r9();ew()});function v0(D,u={}){let r=AK(D,u.supportedProtocols??[Qf]);if(r)return{issues:[r],status:"invalid"};let A=Hr.safeParse(D);if(!A.success)return{issues:A.error.issues.map((E)=>({code:fK(E),message:E.message,path:E.path.map(String).join(".")||"<root>",severity:"error"})),status:"invalid"};let f=A.data,w=[];for(let E of _K(f))if(!E.value.startsWith("./")||E.value.includes(".."))w.push({code:"unsafe_engine_asset_source",message:"engine asset source must be a relative app-local path.",path:E.path,severity:"error"});for(let E of f.engineAssets.mcpServers??[]){let $=SK(f,E.package);if($)w.push({code:"unsafe_mcp_server_package",message:$,path:`engineAssets.mcpServers.${E.id}.package`,severity:"error"})}if(u.hostVersion&&!FK(u.hostVersion,f.compatibility.host))w.push({code:"incompatible_host_version",message:`Host ${u.hostVersion} does not satisfy ${f.compatibility.host.minVersion}${f.compatibility.host.maxVersion?`..${f.compatibility.host.maxVersion}`:"+"}.`,path:"compatibility.host",severity:"error"});if(f.storage.namespace!==f.id)w.push({code:"invalid_storage_namespace",message:"storage.namespace must match the Soul App id for v1 discovery.",path:"storage.namespace",severity:"error"});if((u.existingStorageNamespaces??[]).includes(f.storage.namespace))w.push({code:"namespace_collision",message:`storage namespace already exists: ${f.storage.namespace}`,path:"storage.namespace",severity:"error"});let F=new Set(u.availableConnectorIds??[]);if(F.size>0){for(let E of f.connectors.required)if(!F.has(E.id))w.push({code:"missing_required_connector",message:`required connector is not available: ${E.id}`,path:`connectors.required.${E.id}`,severity:"error"})}if(f.modes.hostMounted.supported&&!$K(f))w.push({code:"missing_ui_api_entry",message:"host-mounted Soul Apps must declare at least one UI contribution or API entry.",path:"ui",severity:"error"});if(f.api.entry&&f.api.routePrefix!==`/api/local/apps/${f.id}`)w.push({code:"missing_ui_api_entry",message:`api.routePrefix must equal /api/local/apps/${f.id}.`,path:"api.routePrefix",severity:"error"});if(f.api.localService?.baseUrl&&!b2(f.api.localService.baseUrl))w.push({code:"unsafe_local_service_url",message:"api.localService.baseUrl must use loopback HTTP for mounted local services.",path:"api.localService.baseUrl",severity:"error"});for(let E of f.permissions){let $=EK(E,f);if($)w.push({code:"unsafe_permission_request",message:$,path:`permissions.${E.kind}.${E.target}`,severity:"error"})}for(let E of RK(f)){if(!E.surface)continue;let $=gK(E.surface);if($)w.push({code:"unsafe_ui_surface",message:$,path:`${E.path}.surface`,severity:"error"})}return{issues:w,manifest:f,status:w.some((E)=>E.severity==="error")?"invalid":"valid"}}function B1(D,u={}){let r;try{r=JSON.parse(D)}catch(f){return{error:`Soul App manifest is not valid JSON: ${f instanceof Error?f.message:String(f)}`,issues:[{code:"invalid_manifest",message:"Soul App manifest is not valid JSON.",severity:"error"}],status:"malformed"}}let A=v0(r,u);if(A.status==="valid"&&A.manifest)return{manifest:A.manifest,status:"ok"};return{error:A.issues.map((f)=>`${f.path??"<root>"}: ${f.message}`).join("; "),issues:A.issues,status:"malformed"}}function b2(D){let u;try{u=new URL(D)}catch{return!1}if(u.protocol!=="http:")return!1;let r=u.hostname.toLowerCase();if(r==="localhost"||r==="::1"||r==="[::1]")return!0;let A=r.split(".");if(A.length!==4||A[0]!=="127")return!1;return A.slice(1).every((f)=>/^\d+$/.test(f)&&Number(f)>=0&&Number(f)<=255)}function S1(D,u,r){let A=new Set;for(let f of u){if(A.has(f.id))D.addIssue({code:S.ZodIssueCode.custom,message:`duplicate id "${f.id}"`,path:r});A.add(f.id)}}function AK(D,u){if(typeof D!=="object"||D===null)return null;let r=D.protocol;if(typeof r!=="string"||u.includes(r))return null;return{code:"unsupported_protocol",message:`unsupported Soul App protocol: ${r}`,path:"protocol",severity:"error"}}function fK(D){let[u]=D.path;if(u==="artifactTypes")return"invalid_artifact_schema";if(u==="storage")return"invalid_storage_namespace";if(u==="permissions")return"unsafe_permission_request";if(u==="api"||u==="ui")return"missing_ui_api_entry";return"invalid_manifest"}function FK(D,u){if(!wK(D))return!1;if(pR(D,u.minVersion)<0)return!1;return u.maxVersion?pR(D,u.maxVersion)<=0:!0}function wK(D){return mR.test(D)}function pR(D,u){let r=xR(D),A=xR(u);for(let f=0;f<3;f++){let w=r[f]-A[f];if(w!==0)return w}return 0}function xR(D){let[u="0",r="0",A="0"]=D.split(".");return[Number(u),Number(r),Number(A)]}function $K(D){return Boolean(D.api.entry||D.ui.routes.length>0||D.ui.panels.length>0||D.ui.artifactPreviews.length>0||D.ui.reviewPanels.length>0||(D.ui.workspaceWidgets?.length??0)>0)}function EK(D,u){let r=D.target.toLowerCase();if(r==="*"||r==="global"||r.includes("secret")||r.includes("vault")||r.includes("host-db"))return`unsafe permission target: ${D.target}`;if(D.kind==="storage"&&D.target!==u.storage.namespace)return`storage permission target must match namespace ${u.storage.namespace}`;if(D.kind==="api"&&u.api.routePrefix&&D.target!==u.api.routePrefix)return`api permission target must match route prefix ${u.api.routePrefix}`;return null}function gK(D){if(D.renderer==="trusted-module")return"trusted-module surfaces are reserved for a future signed first-party module loader.";if(D.renderer==="host-descriptor"&&!D.entry.startsWith("/surfaces/"))return"host-descriptor surfaces must use a /surfaces/* mounted service entry.";if(D.renderer==="sandboxed-frame"&&!D.entry.startsWith("/frames/"))return"sandboxed-frame surfaces must use a /frames/* mounted service entry.";return null}function SK(D,u){let r=u.includes("/")?u.split("/").at(-1):u;if(!/^(?:[a-z][a-z0-9]*-)*mcp-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r))return"MCP server packages must use a generic mcp-* package name, for example @zonease/aiworker-mcp-ats.";if(r.includes(D.id))return"MCP server packages must not be private to a Soul App id.";return null}function _K(D){return[{path:"engineAssets.workspace.source",value:D.engineAssets.workspace.source},...D.engineAssets.skills?[{path:"engineAssets.skills.source",value:D.engineAssets.skills.source}]:[],...(D.engineAssets.mcpClients??[]).map((u,r)=>({path:`engineAssets.mcpClients.${r}.source`,value:u.source}))]}function RK(D){return[...D.ui.routes.map((u,r)=>({path:`ui.routes.${r}`,surface:u.surface})),...D.ui.panels.map((u,r)=>({path:`ui.panels.${r}`,surface:u.surface})),...D.ui.artifactPreviews.map((u,r)=>({path:`ui.artifactPreviews.${r}`,surface:u.surface})),...D.ui.reviewPanels.map((u,r)=>({path:`ui.reviewPanels.${r}`,surface:u.surface})),...(D.ui.workspaceWidgets??[]).map((u,r)=>({path:`ui.workspaceWidgets.${r}`,surface:u.surface}))]}var Qf="soul-app/v1",DK,mR,A9,uK,rK,ED,tu,f9,Kf,F9,w9,$9,E9,g9,S9,_9,R9,n9,B9,T0,_1,R1,W9,J9,G9,C9,H9,X9,i9,U9,aR,Lf,Y9,q2,M9,hf,O9,P9,n1,k9,I9,V9,K9,h9,Nf,N9,Q9,L9,q9,b9,s9,z9,j9,T9,Hr,v9,Z9,qf,eR;var bf=W(()=>{YD();DK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,mR=/^\d+\.\d+\.\d+$/,A9=/^\/[a-z0-9][a-z0-9/_:.-]*$/,uK=/^\/api\/local\/apps\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z0-9/_:.-]*)?$/,rK=/^(storage|connector|artifact|review|memory|ui|api|search):(read|write|create|propose|mount|serve):[^:\s].*$/,ED=S.string().min(1).regex(DK,"Soul App id must be kebab-case"),tu=S.string().regex(mR,"version must be major.minor.patch"),f9=S.literal(Qf),Kf=S.object({entry:S.string().min(1).optional(),supported:S.boolean()}),F9=S.object({host:S.object({maxVersion:tu.optional(),minVersion:tu}),sdk:S.object({maxVersion:tu.optional(),minVersion:tu}).optional()}),w9=S.object({description:S.string().min(1),domain:S.string().min(1),id:ED,name:S.string().min(1),version:tu}),$9=S.enum(["embedded","path","package"]),E9=S.object({id:ED,ref:S.string().min(1),source:$9,version:tu.optional()}),g9=S.object({artifactTypes:S.array(ED).min(1).readonly(),description:S.string().min(1),id:ED,name:S.string().min(1),outputKind:ED,packRefs:S.array(ED).readonly().optional(),promptRef:S.string().min(1),reviewRubricRef:S.string().min(1).optional(),version:tu,workspaceTypes:S.array(ED).min(1).readonly()}),S9=S.object({artifactTypes:S.array(ED).min(1).readonly(),defaultCapabilityIds:S.array(ED).readonly().optional(),description:S.string().min(1),id:ED,name:S.string().min(1)}),_9=S.object({description:S.string().min(1),id:ED,name:S.string().min(1),previewRef:S.string().min(1).optional(),reviewPolicyRef:S.string().min(1).optional(),schemaRef:S.string().min(1),schemaSha256:S.string().regex(/^[a-f0-9]{64}$/).optional(),version:tu}),R9=S.enum(["route","panel","workspace-widget","artifact-preview","review-panel"]),n9=S.enum(["host-descriptor","sandboxed-frame","trusted-module"]),B9=S.enum(["app","workspace","session","artifact","review"]),T0=S.string().regex(rK,"requiredPermissions must use kind:action:target"),_1=S.enum(["codex","claude-code"]),R1=S.string().min(1),W9=S.object({source:R1}),J9=S.object({source:R1,targets:S.array(_1).min(1).readonly()}),G9=S.object({source:R1,target:_1}),C9=S.enum(["stdio","http"]),H9=S.object({id:ED,package:S.string().min(1),requiredPermissions:S.array(T0).readonly().optional(),transport:C9}),X9=S.object({mcpClients:S.array(G9).readonly().optional(),mcpServers:S.array(H9).readonly().optional(),skills:J9.optional(),workspace:W9}),i9=S.enum(["workspace-file","native-skill","mcp-client"]),U9=S.object({appId:ED,engineTarget:_1.optional(),generatedAt:S.string().min(1),kind:i9,sha256:S.string().regex(/^[a-f0-9]{64}$/),source:S.string().min(1),target:S.string().min(1)}),aR=S.object({appId:ED,generatedAt:S.string().min(1),projections:S.array(U9).readonly(),version:S.literal(1)}),Lf=S.object({entry:S.string().regex(A9,"surface entry must be an absolute mounted service route"),renderer:n9,requiredPermissions:S.array(T0).readonly().optional(),scope:B9}),Y9=S.object({entry:S.string().min(1),id:ED,label:S.string().min(1),path:S.string().regex(A9,"route path must be an absolute local route"),surface:Lf.optional()}),q2=S.object({entry:S.string().min(1),id:ED,label:S.string().min(1),slot:R9.exclude(["route"]),surface:Lf.optional(),target:ED.optional()}),M9=S.enum(["primary","action","drawer-toggle","refresh","settings"]),hf=S.object({id:ED,label:S.string().min(1),protocolAction:S.string({required_error:"protocolAction is required"}).min(1),requiredPermissions:S.array(T0).readonly().optional(),slot:M9}),O9=S.object({id:ED,label:S.string().min(1),placeholder:S.string().min(1),protocolProvider:S.string({required_error:"protocolProvider is required"}).min(1),requiredPermissions:S.array(T0).readonly().optional()}),P9=S.object({id:ED,label:S.string().min(1),protocolAction:S.string({required_error:"protocolAction is required"}).min(1),requiredPermissions:S.array(T0).readonly().optional()}),n1=S.object({actions:S.array(hf).readonly().optional(),primaryAction:hf.optional(),search:O9.optional(),settings:P9.optional()}).superRefine((D,u)=>{if(D.primaryAction&&D.primaryAction.slot!=="primary")u.addIssue({code:S.ZodIssueCode.custom,message:"primaryAction slot must be primary",path:["primaryAction","slot"]})}),k9=S.object({artifactPreviews:S.array(q2).readonly(),panels:S.array(q2).readonly(),reviewPanels:S.array(q2).readonly(),routes:S.array(Y9).readonly(),shell:n1.optional(),workspaceWidgets:S.array(q2).readonly().optional()}),I9=S.object({entry:S.string().min(1).optional(),localService:S.object({baseUrl:S.string().url().optional(),command:S.array(S.string().min(1)).min(1).readonly().optional(),cwd:S.string().min(1).optional(),healthPath:S.string().regex(A9,"health path must be an absolute local route")}).refine((D)=>D.baseUrl||D.command,{message:"localService must declare baseUrl or command"}).optional(),routePrefix:S.string().regex(uK,"API route prefix must live under /api/local/apps/<appId>").optional()}),V9=S.object({id:ED,path:S.string().min(1),sha256:S.string().regex(/^[a-f0-9]{64}$/).optional()}),K9=S.object({migrations:S.array(V9).readonly(),namespace:ED}),h9=S.enum(["read","write"]),Nf=S.object({access:S.array(h9).min(1).readonly(),id:ED,reason:S.string().min(1),scopes:S.array(S.string().min(1)).readonly()}),N9=S.object({optional:S.array(Nf).readonly(),required:S.array(Nf).readonly()}),Q9=S.enum(["manual-review","host-policy","disabled"]),L9=S.object({admissionPolicy:Q9,namespace:ED}),q9=S.enum(["storage","connector","artifact","review","memory","ui","api","search"]),b9=S.enum(["read","write","create","propose","mount","serve"]),s9=S.object({action:b9,kind:q9,reason:S.string().min(1),target:S.string().min(1)}),z9=S.enum(["protocol-handler","http"]),j9=S.object({kind:z9,ref:S.string().min(1),timeoutMs:S.number().int().positive().max(60000)}),T9=S.object({artifact:S.string().min(1).optional(),connector:S.string().min(1).optional(),event:S.string().min(1).optional(),lifecycle:S.string().min(1).optional(),review:S.string().min(1).optional(),runtime:S.string().min(1).optional(),ui:S.string().min(1).optional()}),Hr=S.object({api:I9,artifactTypes:S.array(_9).min(1).readonly(),capabilities:S.array(g9).min(1).readonly(),compatibility:F9,connectors:N9,description:S.string().min(1),engineAssets:X9,exports:T9,healthcheck:j9,id:ED,memory:L9,modes:S.object({hostMounted:Kf,standalone:Kf}),name:S.string().min(1),pack:S.object({refs:S.array(E9).min(1).readonly()}),permissions:S.array(s9).min(1).readonly(),protocol:f9,soul:w9,storage:K9,ui:k9,version:tu,workspaceTypes:S.array(S9).min(1).readonly()}).superRefine((D,u)=>{if(!D.modes.standalone.supported&&!D.modes.hostMounted.supported)u.addIssue({code:S.ZodIssueCode.custom,message:"at least one mode must be supported",path:["modes"]});S1(u,D.capabilities,["capabilities"]),S1(u,D.workspaceTypes,["workspaceTypes"]),S1(u,D.artifactTypes,["artifactTypes"]),S1(u,D.pack.refs,["pack","refs"]),S1(u,[...D.ui.routes,...D.ui.panels,...D.ui.artifactPreviews,...D.ui.reviewPanels,...D.ui.workspaceWidgets??[]],["ui"])}),v9=S.enum(["invalid_manifest","unsupported_protocol","incompatible_host_version","missing_required_connector","invalid_storage_namespace","unsafe_local_service_url","unsafe_permission_request","unsafe_ui_surface","unsafe_engine_asset_source","unsafe_mcp_server_package","missing_ui_api_entry","invalid_artifact_schema","namespace_collision"]),Z9=S.enum(["warning","error"]),qf=S.object({code:v9,message:S.string().min(1),path:S.string().min(1).optional(),severity:Z9}),eR=S.enum(["valid","invalid"])});var nK="35c14e3d4c0fe9fd95c87e9bc47a210e21f99bcb1b079aa99a95bb93e820c8ab",BK="e8bd207be63eab23073cd47e41092f1d753c38d609383206e94334dd984b309c",WK="6a4f3494764431e8785a82865215eabc4c4678dfb4e447eda4d4684f341892a0",JK="0c953a3453ff235c419600073c70c1f155976f448c4567711b511d83668a09e4",Dn,un;var rn=W(()=>{bf();Dn=Hr.parse({api:{entry:"./host-adapter/api.ts",routePrefix:"/api/local/apps/aiworker-hr"},artifactTypes:[{description:"Source-backed HR lifecycle profile.",id:"person-profile",name:"Person Profile",previewRef:"./product/web/artifact-previews/person-profile-preview.tsx",reviewPolicyRef:"./product/reviews/person-profile.md",schemaRef:"./product/artifacts/schemas/person-profile.schema.json",schemaSha256:nK,version:"0.1.0"},{description:"Role-related candidate screen with missing evidence and risks.",id:"candidate-screen",name:"Candidate Screen",previewRef:"./product/web/artifact-previews/candidate-screen-preview.tsx",reviewPolicyRef:"./product/reviews/candidate-screen.md",schemaRef:"./product/artifacts/schemas/candidate-screen.schema.json",schemaSha256:BK,version:"0.1.0"}],capabilities:[{artifactTypes:["person-profile"],description:"Create a source-backed people profile snapshot.",id:"person-profile",name:"Person Profile",outputKind:"person-profile",packRefs:[],promptRef:"./product/workflows/person-profile/prompt.md",reviewRubricRef:"./product/workflows/person-profile/review.md",version:"0.1.0",workspaceTypes:["people-profile"]},{artifactTypes:["candidate-screen"],description:"Screen candidate evidence against a role rubric.",id:"candidate-screen",name:"Candidate Screen",outputKind:"candidate-screen",packRefs:[],promptRef:"./product/workflows/candidate-screen/prompt.md",reviewRubricRef:"./product/workflows/candidate-screen/review.md",version:"0.1.0",workspaceTypes:["role-search","candidate"]}],compatibility:{host:{minVersion:"0.12.0"},sdk:{minVersion:"0.1.0"}},connectors:{optional:[{access:["read"],id:"calendar",reason:"Collect interview availability and touchpoint context.",scopes:["events.read"]}],required:[{access:["read"],id:"ats",reason:"Read candidate packets and role evidence through the Host connector broker.",scopes:["candidates.read","roles.read"]}]},description:"People operations Soul App for profiles, recruiting evidence, lifecycle touchpoints, and HR review policy.",engineAssets:{skills:{source:"./engine-assets/skills",targets:["codex","claude-code"]},workspace:{source:"./engine-assets/workspace"}},exports:{artifact:"./host-adapter/protocol/artifact.ts",connector:"./host-adapter/protocol/connectors.ts",lifecycle:"./host-adapter/protocol/lifecycle.ts",review:"./host-adapter/protocol/review.ts",runtime:"./host-adapter/protocol/runtime.ts",ui:"./host-adapter/protocol/ui.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:"aiworker-hr",memory:{admissionPolicy:"manual-review",namespace:"aiworker-hr"},modes:{hostMounted:{entry:"./host-adapter/mounted/host-mounted.ts",supported:!0},standalone:{entry:"./host-adapter/standalone/standalone.ts",supported:!0}},name:"AIWorker HR",pack:{refs:[{id:"hr-recruiting",ref:"product/profiles/hr-recruiting/SOUL.md",source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped HR domain metadata.",target:"aiworker-hr"},{action:"write",kind:"storage",reason:"Write app-scoped HR domain metadata.",target:"aiworker-hr"},{action:"read",kind:"search",reason:"Read app-owned HR search descriptors.",target:"aiworker-hr"},{action:"write",kind:"search",reason:"Publish app-owned HR search descriptors.",target:"aiworker-hr"},{action:"read",kind:"connector",reason:"Read HR evidence through Host connector broker.",target:"ats"},{action:"write",kind:"artifact",reason:"Create reviewable HR artifacts.",target:"person-profile"},{action:"create",kind:"review",reason:"Create HR review rubrics and findings.",target:"hr-review"},{action:"propose",kind:"memory",reason:"Propose reviewed HR lessons into the app namespace.",target:"aiworker-hr"},{action:"mount",kind:"ui",reason:"Mount HR workbench contributions.",target:"hr-workbench"},{action:"serve",kind:"api",reason:"Serve HR scoped API routes.",target:"/api/local/apps/aiworker-hr"}],protocol:"soul-app/v1",soul:{description:"HR Soul for people operations, recruiting, onboarding, offboarding, and sensitive evidence review.",domain:"hr-people-ops",id:"hr",name:"HR",version:"0.1.0"},storage:{migrations:[{id:"hr-initial",path:"./migrations/0001_hr.sql"}],namespace:"aiworker-hr"},ui:{artifactPreviews:[{entry:"./product/web/artifact-previews/person-profile-preview.tsx",id:"person-profile-preview",label:"Person profile preview",slot:"artifact-preview",target:"person-profile"}],panels:[{entry:"./product/web/panels/profile-panel.tsx",id:"hr-profile-panel",label:"Profile panel",slot:"panel",surface:{entry:"/surfaces/panels/hr-profile-panel",renderer:"host-descriptor",requiredPermissions:["storage:read:aiworker-hr"],scope:"workspace"}}],reviewPanels:[{entry:"./product/web/panels/review-panel.tsx",id:"hr-review-panel",label:"HR review panel",slot:"review-panel"}],routes:[{entry:"./product/web/routes/hr-route.tsx",id:"hr-home",label:"HR",path:"/hr",surface:{entry:"/surfaces/routes/hr-home",renderer:"host-descriptor",requiredPermissions:["ui:mount:hr-workbench"],scope:"app"}}],shell:{actions:[{id:"refresh-people",label:"Refresh",protocolAction:"people.refresh",requiredPermissions:["storage:read:aiworker-hr"],slot:"refresh"},{id:"toggle-evidence-drawer",label:"Evidence",protocolAction:"drawers.evidence.toggle",requiredPermissions:["connector:read:ats"],slot:"drawer-toggle"}],primaryAction:{id:"create-people-profile",label:"New people profile",protocolAction:"peopleProfiles.create",requiredPermissions:["storage:write:aiworker-hr","search:write:aiworker-hr"],slot:"primary"},search:{id:"people-profile-search",label:"Search people profiles",placeholder:"Search people profiles",protocolProvider:"peopleProfiles.search",requiredPermissions:["search:read:aiworker-hr"]},settings:{id:"hr-settings",label:"HR settings",protocolAction:"settings.open",requiredPermissions:["api:serve:/api/local/apps/aiworker-hr"]}},workspaceWidgets:[{entry:"./product/web/widgets/people-widget.tsx",id:"hr-people-widget",label:"People widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/hr-people-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"people-profile"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["person-profile"],defaultCapabilityIds:["person-profile"],description:"Profile-centered workspace for one person lifecycle.",id:"people-profile",name:"People Profile"},{artifactTypes:["candidate-screen"],defaultCapabilityIds:["candidate-screen"],description:"Recruiting role workspace with candidate evidence and review.",id:"role-search",name:"Role Search"},{artifactTypes:["candidate-screen"],defaultCapabilityIds:["candidate-screen"],description:"Focused candidate packet workspace.",id:"candidate",name:"Candidate"}]}),un=Hr.parse({api:{entry:"./host-adapter/api.ts",routePrefix:"/api/local/apps/aiworker-qa"},artifactTypes:[{description:"Coverage matrix mapped to release risk.",id:"regression-matrix",name:"Regression Matrix",previewRef:"./product/web/artifact-previews/regression-matrix-preview.tsx",reviewPolicyRef:"./product/reviews/regression-matrix.md",schemaRef:"./product/artifacts/schemas/regression-matrix.schema.json",schemaSha256:WK,version:"0.1.0"},{description:"Go/no-go release readiness artifact.",id:"release-gate",name:"Release Gate",previewRef:"./product/web/artifact-previews/release-gate-preview.tsx",reviewPolicyRef:"./product/reviews/release-gate.md",schemaRef:"./product/artifacts/schemas/release-gate.schema.json",schemaSha256:JK,version:"0.1.0"}],capabilities:[{artifactTypes:["regression-matrix"],description:"Build regression coverage from change and test evidence.",id:"regression-matrix",name:"Regression Matrix",outputKind:"regression-matrix",packRefs:[],promptRef:"./product/workflows/regression-matrix/prompt.md",reviewRubricRef:"./product/workflows/regression-matrix/review.md",version:"0.1.0",workspaceTypes:["release","test-suite"]},{artifactTypes:["release-gate"],description:"Summarize release blockers, residual risk, and go/no-go recommendation.",id:"release-gate",name:"Release Gate",outputKind:"release-gate",packRefs:[],promptRef:"./product/workflows/release-gate/prompt.md",reviewRubricRef:"./product/workflows/release-gate/review.md",version:"0.1.0",workspaceTypes:["release"]}],compatibility:{host:{minVersion:"0.12.0"},sdk:{minVersion:"0.1.0"}},connectors:{optional:[{access:["read"],id:"issue-tracker",reason:"Read defect evidence through Host connector broker.",scopes:["issues.read"]}],required:[{access:["read"],id:"ci",reason:"Read CI and test evidence through Host connector broker.",scopes:["runs.read","artifacts.read"]}]},description:"Quality Soul App for release workspaces, regression evidence, defect triage, and release gate review.",engineAssets:{skills:{source:"./engine-assets/skills",targets:["codex","claude-code"]},workspace:{source:"./engine-assets/workspace"}},exports:{artifact:"./host-adapter/protocol/artifact.ts",connector:"./host-adapter/protocol/connectors.ts",lifecycle:"./host-adapter/protocol/lifecycle.ts",review:"./host-adapter/protocol/review.ts",runtime:"./host-adapter/protocol/runtime.ts",ui:"./host-adapter/protocol/ui.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:"aiworker-qa",memory:{admissionPolicy:"manual-review",namespace:"aiworker-qa"},modes:{hostMounted:{entry:"./host-adapter/mounted/host-mounted.ts",supported:!0},standalone:{entry:"./host-adapter/standalone/standalone.ts",supported:!0}},name:"AIWorker QA",pack:{refs:[{id:"qa-reviewer",ref:"product/profiles/qa-reviewer/SOUL.md",source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped QA domain metadata.",target:"aiworker-qa"},{action:"write",kind:"storage",reason:"Write app-scoped QA domain metadata.",target:"aiworker-qa"},{action:"read",kind:"search",reason:"Read app-owned QA search descriptors.",target:"aiworker-qa"},{action:"write",kind:"search",reason:"Publish app-owned QA search descriptors.",target:"aiworker-qa"},{action:"read",kind:"connector",reason:"Read CI evidence through Host connector broker.",target:"ci"},{action:"write",kind:"artifact",reason:"Create reviewable QA release artifacts.",target:"release-gate"},{action:"create",kind:"review",reason:"Create QA review rubrics and findings.",target:"qa-review"},{action:"propose",kind:"memory",reason:"Propose reviewed QA lessons into the app namespace.",target:"aiworker-qa"},{action:"mount",kind:"ui",reason:"Mount QA workbench contributions.",target:"qa-workbench"},{action:"serve",kind:"api",reason:"Serve QA scoped API routes.",target:"/api/local/apps/aiworker-qa"}],protocol:"soul-app/v1",soul:{description:"QA Soul for release evidence, regression coverage, defect triage, and release readiness review.",domain:"quality-assurance",id:"qa",name:"QA",version:"0.1.0"},storage:{migrations:[{id:"qa-initial",path:"./migrations/0001_qa.sql"}],namespace:"aiworker-qa"},ui:{artifactPreviews:[{entry:"./product/web/artifact-previews/release-gate-preview.tsx",id:"release-gate-preview",label:"Release gate preview",slot:"artifact-preview",target:"release-gate"}],panels:[{entry:"./product/web/panels/release-panel.tsx",id:"qa-release-panel",label:"Release panel",slot:"panel",surface:{entry:"/surfaces/panels/qa-release-panel",renderer:"host-descriptor",requiredPermissions:["storage:read:aiworker-qa"],scope:"workspace"}}],reviewPanels:[{entry:"./product/web/panels/review-panel.tsx",id:"qa-review-panel",label:"QA review panel",slot:"review-panel"}],routes:[{entry:"./product/web/routes/qa-route.tsx",id:"qa-home",label:"QA",path:"/qa",surface:{entry:"/surfaces/routes/qa-home",renderer:"host-descriptor",requiredPermissions:["ui:mount:qa-workbench"],scope:"app"}}],shell:{actions:[{id:"refresh-release",label:"Refresh",protocolAction:"release.refresh",requiredPermissions:["storage:read:aiworker-qa"],slot:"refresh"}],primaryAction:{id:"create-release-gate",label:"New release gate",protocolAction:"releaseGates.create",requiredPermissions:["storage:write:aiworker-qa","search:write:aiworker-qa"],slot:"primary"},search:{id:"release-search",label:"Search releases",placeholder:"Search releases",protocolProvider:"releases.search",requiredPermissions:["search:read:aiworker-qa"]},settings:{id:"qa-settings",label:"QA settings",protocolAction:"settings.open",requiredPermissions:["api:serve:/api/local/apps/aiworker-qa"]}},workspaceWidgets:[{entry:"./product/web/widgets/release-widget.tsx",id:"qa-release-widget",label:"Release widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/qa-release-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"release"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["regression-matrix","release-gate"],defaultCapabilityIds:["regression-matrix","release-gate"],description:"Release readiness workspace with test and defect evidence.",id:"release",name:"Release"},{artifactTypes:["regression-matrix"],defaultCapabilityIds:["regression-matrix"],description:"Focused test suite coverage workspace.",id:"test-suite",name:"Test Suite"}]})});var o9,d9,l9,y9,An;var fn=W(()=>{YD();o9=S.enum(["audit","connector","secret","storage"]),d9=S.enum(["active","disabled","not_configured","planned"]),l9=S.object({appScoped:S.boolean(),capabilities:S.array(S.string().min(1)).readonly(),configured:S.boolean(),description:S.string().min(1),enabled:S.boolean(),id:S.string().min(1),kind:o9,label:S.string().min(1),local:S.boolean(),notes:S.array(S.string().min(1)).readonly().optional(),status:d9}),y9=S.object({activeCount:S.number().int().nonnegative(),configuredCount:S.number().int().nonnegative(),plannedCount:S.number().int().nonnegative(),providerCount:S.number().int().nonnegative()}),An=S.object({providers:S.array(l9).readonly(),summary:y9})});function MD(D,u,r,A,f,w,F){return{description:f,id:u,inputHints:w,name:r,outputKind:A,prompt:`Use the ${r} capability template. Produce a ${A} business artifact for the selected ${D.toUpperCase()} Soul project.`,reviewRubric:F,soulId:D}}var Fn,c9,t9,c,Oc;var p9=W(()=>{YD();Fn=S.enum(["available","coming_soon"]),c9=S.object({description:S.string().min(1),id:S.string().min(1),inputHints:S.array(S.string().min(1)).readonly(),name:S.string().min(1),outputKind:S.string().min(1),prompt:S.string().min(1),reviewRubric:S.array(S.string().min(1)).readonly(),soulId:S.string().min(1)}),t9=S.object({defaultTemplates:S.array(S.string().min(1)).readonly(),description:S.string().min(1),domain:S.string().min(1),id:S.string().min(1),name:S.string().min(1),status:Fn}),c={evidence:"Output cites the supplied context and labels missing evidence.",action:"Next action is concrete, owned, and useful for a human reviewer.",risk:"Risks and assumptions are separated from confirmed facts."},Oc=[MD("hr","person-profile","Person Profile","person-profile","Create a source-backed HR profile snapshot with lifecycle stage, evidence, risks, and next steps.",["Person context","Lifecycle stage","Relevant HR notes"],[c.evidence,c.risk,"No protected-class inference or unsupported personal judgment."]),MD("hr","lifecycle-next-step","Lifecycle Next Step","lifecycle-next-step","Prepare the next reviewable HR touchpoint for a person across recruiting, onboarding, employee care, or offboarding.",["Person profile","Current lifecycle moment","Open questions"],[c.evidence,c.action,"Decision and employment commitments remain human-owned."]),MD("hr","candidate-screen","Candidate Screen","candidate-screen","Screen a candidate against a role and identify strengths, gaps, and follow-ups.",["Role requirements","Resume or profile","Relevant notes"],[c.evidence,c.risk,"No protected-class inference."]),MD("hr","interview-brief","Interview Brief","interview-brief","Prepare a structured interviewer brief with evidence-backed questions.",["Role stage","Candidate packet","Interview goals"],[c.evidence,c.action,"Questions target missing signal."]),MD("hr","role-rubric","Role Rubric","role-rubric","Turn role expectations into a hiring rubric and scoring guide.",["Role description","Level expectations","Team constraints"],[c.action,"Criteria are observable and role-related.",c.risk]),MD("hr","onboarding-plan","Onboarding Plan","onboarding-plan","Draft a 30/60/90 onboarding or check-in plan with owners, evidence, risks, and follow-up prompts.",["Employee profile","Role expectations","Team context"],[c.evidence,c.action,"No private or unsupported employment claims."]),MD("hr","offboarding-summary","Offboarding Summary","offboarding-summary","Prepare an offboarding or alumni handoff summary with knowledge-transfer notes, open actions, and privacy guardrails.",["Departing employee context","Handoff notes","Open actions"],[c.evidence,c.action,"Sensitive details are minimized and reviewed."]),MD("hr","evidence-matrix","Evidence Matrix","evidence-matrix","Compare candidates against role signals with source-backed coverage, gaps, and conflicts.",["Role rubric","Candidate evidence packets","Interview notes or scorecards"],[c.evidence,"Coverage states strong, weak, missing, or conflict.","No candidate ranking without human review."]),MD("hr","roundup-packet","Roundup Packet","roundup-packet","Prepare a hiring roundup packet with rubric snapshot, comparison, missing signals, and decision guardrails.",["Role rubric","Evidence matrix","Scorecard summaries"],[c.evidence,c.risk,"Decision placeholders remain human-owned."]),MD("hr","hiring-risk","Hiring Risk","hiring-risk","Summarize hiring risks, uncertainty, and decision guardrails.",["Candidate evidence","Scorecard notes","Decision constraints"],[c.evidence,c.risk,"Decision remains human-owned."]),MD("pm","prd-draft","PRD Draft","prd-draft","Draft a PRD from goals, user evidence, constraints, and success metrics.",["Problem statement","User evidence","Constraints"],[c.action,"Scope and non-goals are explicit.",c.risk]),MD("pm","decision-record","Decision Record","decision-record","Capture options, tradeoffs, decision, and follow-up owners.",["Decision context","Options considered","Stakeholder notes"],[c.evidence,c.action,"Tradeoffs are balanced."]),MD("pm","roadmap-slice","Roadmap Slice","roadmap-slice","Break a goal into a sequenced roadmap slice with dependencies.",["Goal","Time horizon","Dependencies"],[c.action,c.risk,"Milestones are inspectable."]),MD("pm","status-report","Status Report","status-report","Produce a concise stakeholder status report with risks and next decisions.",["Current status","Risks","Decisions needed"],[c.evidence,c.action,"No vague summary filler."]),MD("qa","test-plan","Test Plan","test-plan","Create a test plan matched to release scope and user-facing risk.",["Release scope","Acceptance criteria","Known risks"],[c.action,"Coverage maps to risk.",c.risk]),MD("qa","regression-matrix","Regression Matrix","regression-matrix","Build a regression matrix with coverage, evidence, gaps, and recommendation.",["Changed behavior","Existing tests","Release criteria"],[c.evidence,"Gaps are visible.",c.risk]),MD("qa","defect-triage","Defect Triage","defect-triage","Prioritize defects with reproduction evidence and release impact.",["Bug reports","Logs/screenshots","Release target"],[c.evidence,c.action,"Observed failure and suspected cause are separate."]),MD("qa","release-gate","Release Gate","release-gate","Summarize release readiness, blockers, residual risk, and go/no-go recommendation.",["Test evidence","Known defects","Release policy"],[c.evidence,c.risk,"Recommendation is explicit."]),MD("devops","deploy-checklist","Deploy Checklist","deploy-checklist","Prepare a deploy checklist with rollback, monitoring, and owner steps.",["Change summary","Environment","Rollback plan"],[c.action,c.risk,"Steps are operationally concrete."]),MD("devops","incident-review","Incident Review","incident-review","Produce an incident review with timeline, impact, contributing factors, and actions.",["Timeline","Signals","Impact notes"],[c.evidence,c.action,"Blameless language and source boundaries."]),MD("devops","runbook-update","Runbook Update","runbook-update","Convert new operational learning into a runbook update.",["Current runbook","Observed gap","Operational context"],[c.action,"Procedure is repeatable.",c.risk]),MD("devops","capacity-summary","Capacity Summary","capacity-summary","Summarize capacity signals, thresholds, and scaling recommendations.",["Metrics","Service context","Forecast horizon"],[c.evidence,c.risk,"Recommendation states confidence."])]});function sf(D,u){return`${D}.${u}`}function W1(D,u="available"){return{defaultTemplates:D.workspaceTypes.flatMap((r)=>(r.defaultCapabilityIds??[]).map((A)=>sf(D.id,A))),description:D.description,domain:D.soul.domain,id:D.id,name:D.name,status:u}}function u$(D,u){return{description:u.description,id:sf(D.id,u.id),inputHints:[`Workspace types: ${u.workspaceTypes.join(", ")}`,`Artifact types: ${u.artifactTypes.join(", ")}`,`Prompt ref: ${u.promptRef}`],name:u.name,outputKind:u.outputKind,prompt:[`Use the ${D.name} Soul App capability ${u.name}.`,`Use prompt asset ${u.promptRef}.`,`Produce a ${u.outputKind} business artifact for the selected ${D.soul.name} workspace.`,"Keep Host runtime, connector, artifact, review, and memory ownership intact."].join(" "),reviewRubric:u.reviewRubricRef?[`Review rubric ref: ${u.reviewRubricRef}`,"Evidence, missing facts, risks, and human review notes remain explicit."]:["Evidence, missing facts, risks, and human review notes remain explicit."],soulId:D.id}}function J1(D){return D.capabilities.map((u)=>u$(D,u))}function r$(D){let u=[...D.ui.routes,...D.ui.panels,...D.ui.artifactPreviews,...D.ui.reviewPanels,...D.ui.workspaceWidgets??[]].filter((r)=>r.surface);return{apiRoutePrefix:D.api.routePrefix??null,artifactPreviewIds:D.ui.artifactPreviews.map((r)=>r.id),descriptorSurfaceIds:u.filter((r)=>r.surface?.renderer==="host-descriptor").map((r)=>r.id),frameSurfaceIds:u.filter((r)=>r.surface?.renderer==="sandboxed-frame").map((r)=>r.id),panelIds:D.ui.panels.map((r)=>r.id),reviewPanelIds:D.ui.reviewPanels.map((r)=>r.id),routePaths:D.ui.routes.map((r)=>r.path),shell:D.ui.shell??null,surfaceIds:u.map((r)=>r.id),workspaceWidgetIds:(D.ui.workspaceWidgets??[]).map((r)=>r.id)}}function zf(D){return D$.parse({appId:D.manifest.id,healthMessage:D.healthMessage??null,healthStatus:D.healthStatus??"unknown",manifest:D.manifest,manifestDigest:D.manifestDigest,mountedContribution:r$(D.manifest),projectedCapabilities:J1(D.manifest),projectedSoul:W1(D.manifest,D.status==="enabled"?"available":"coming_soon"),sourceKind:D.sourceKind,sourceRef:D.sourceRef,status:D.status,validationIssues:D.validationIssues??[],version:D.manifest.version})}var x9,m9,a9,e9,D$;var wn=W(()=>{YD();p9();bf();x9=S.enum(["installed","enabled","disabled","error"]),m9=S.enum(["manifest-path","inline"]),a9=S.enum(["unknown","pass","warn","fail"]),e9=S.object({apiRoutePrefix:S.string().min(1).nullable(),artifactPreviewIds:S.array(S.string().min(1)).readonly(),descriptorSurfaceIds:S.array(S.string().min(1)).readonly(),frameSurfaceIds:S.array(S.string().min(1)).readonly(),panelIds:S.array(S.string().min(1)).readonly(),reviewPanelIds:S.array(S.string().min(1)).readonly(),routePaths:S.array(S.string().min(1)).readonly(),shell:n1.nullable(),surfaceIds:S.array(S.string().min(1)).readonly(),workspaceWidgetIds:S.array(S.string().min(1)).readonly()}),D$=S.object({appId:S.string().min(1),healthMessage:S.string().nullable(),healthStatus:a9,manifest:Hr,manifestDigest:S.string().min(1),mountedContribution:e9,projectedCapabilities:S.array(c9).readonly(),projectedSoul:t9,sourceKind:m9,sourceRef:S.string().min(1),status:x9,validationIssues:S.array(qf).readonly(),version:S.string().min(1)})});var $n=W(()=>{rn();bf();fn();wn()});function R0(D,u,r,A,f,w){return{description:w,id:D,label:u,outputKind:f,prompt:w,scope:r,templateId:A}}var En;var gn=W(()=>{En={actions:[R0("summarize-profile","Summarize profile","person","aiworker-hr.person-profile","person-profile","Create a source-backed HR profile snapshot for this person. Separate confirmed facts, missing evidence, risks, and human follow-up notes."),R0("prepare-next-step","Prepare next step","lifecycle","aiworker-hr.lifecycle-next-step","lifecycle-next-step","Prepare the next HR touchpoint for this person. Use the current lifecycle stage, evidence, open questions, and human-owned decision guardrails."),R0("extract-evidence","Extract evidence","person","aiworker-hr.candidate-screen","candidate-screen","Extract source-backed evidence from the supplied role packet, resume, employee notes, interview notes, or lifecycle records. Preserve missing evidence and do not infer protected-class attributes."),R0("draft-interview-kit","Draft interview kit","interview","aiworker-hr.interview-brief","interview-brief","Draft a structured interview kit with evidence-backed questions, focus signals, and scorecard guidance."),R0("draft-onboarding-plan","Draft onboarding plan","employee","aiworker-hr.onboarding-plan","onboarding-plan","Draft a 30/60/90 onboarding or check-in plan with evidence, owner placeholders, open risks, and review notes."),R0("prepare-offboarding-summary","Prepare offboarding summary","alumni","aiworker-hr.offboarding-summary","offboarding-summary","Prepare an offboarding or alumni handoff summary. Keep sensitive details minimized and separate confirmed facts from assumptions."),R0("build-evidence-matrix","Build evidence matrix","pool","aiworker-hr.evidence-matrix","evidence-matrix","Build an evidence matrix across people and role/lifecycle signals. Use source references and mark weak, missing, or conflicting evidence."),R0("check-risky-wording","Check risky wording","artifact","aiworker-hr.hiring-risk","hiring-risk","Review the current artifact for protected-class inference, unsupported personal judgments, privacy leakage, and unreviewed employment commitments.")],artifactKinds:["person-profile","lifecycle-next-step","candidate-screen","interview-brief","onboarding-plan","offboarding-summary","evidence-matrix","hiring-risk"],description:"People-first HR workbench for profile context, lifecycle moments, evidence, reviewable next steps, and memory candidates.",fallback:"generic-worker-studio",id:"hr-people-workbench",name:"People Workbench",primaryObjects:[{description:"A selected person profile with lifecycle stage, evidence coverage, open risks, and next step.",id:"person-profile",label:"Person Profile"},{description:"A recruiting, onboarding, employee-care, or offboarding moment that needs a reviewable next artifact.",id:"lifecycle-moment",label:"Lifecycle Moment"},{description:"Source-backed timeline of sessions, artifacts, reviews, and memory candidates for the person.",id:"profile-timeline",label:"Profile Timeline"},{description:"People-level coverage view across candidates, employees, and alumni without automated ranking.",id:"people-board",label:"People Board"}],reviewChecklist:["Evidence is tied to role-related or lifecycle-relevant criteria and source references.","Missing, weak, and conflicting signals are visible.","Protected-class inference, unsupported personal judgments, and sensitive leakage are absent.","Person-sensitive details are not promoted into durable memory without review.","Hiring and employment decisions remain explicitly human-owned."],soulId:"aiworker-hr",version:"0.1.0",views:[{description:"Lifecycle filters, evidence inventory, and review guardrails.",id:"lifecycle-rail",label:"Lifecycle rail",region:"rail"},{description:"Flex poster wall of people profiles and their next HR moment.",id:"profile-wall",label:"Profile wall",region:"main"},{description:"Selected profile loop with next step, agent proposal, review, and memory status.",id:"profile-loop-panel",label:"Profile loop panel",region:"tray"},{description:"Artifact quality, privacy, compliance, and memory-candidate review.",id:"review-panel",label:"Review panel",region:"review"}],workspaceTypes:[{description:"A people profile workspace that tracks a person through HR lifecycle moments.",id:"people-profile",label:"People Profile",primary:!0},{description:"A hiring role search with rubric, candidates, interviews, evidence matrix, and roundup packet.",id:"role-search",label:"Role Search",primary:!1},{description:"A focused candidate packet inside a recruiting loop.",id:"candidate",label:"Candidate",primary:!1},{description:"An active employee profile for onboarding, check-in, growth, or retention support.",id:"employee",label:"Employee",primary:!1},{description:"A departed employee or alumni profile for offboarding, handoff, or knowledge capture.",id:"alumni",label:"Alumni",primary:!1},{description:"A reusable pool of future candidate evidence.",id:"talent-pool",label:"Talent Pool",primary:!1}]}});var Sn,_n,Rn,nn,Bn,UK;var Wn=W(()=>{YD();gn();Sn=S.enum(["generic-worker-studio"]),_n=S.object({description:S.string().min(1),id:S.string().min(1),label:S.string().min(1)}),Rn=S.object({description:S.string().min(1),id:S.string().min(1),label:S.string().min(1),region:S.enum(["rail","main","tray","review"])}),nn=S.object({description:S.string().min(1),id:S.string().min(1),label:S.string().min(1),outputKind:S.string().min(1),prompt:S.string().min(1),scope:S.enum(["person","role","candidate","employee","alumni","pool","interview","artifact","lifecycle"]),templateId:S.string().min(1)}),Bn=S.object({description:S.string().min(1),id:S.string().min(1),label:S.string().min(1),primary:S.boolean().default(!1)}),UK=S.object({actions:S.array(nn).min(1).readonly(),artifactKinds:S.array(S.string().min(1)).min(1).readonly(),description:S.string().min(1),fallback:Sn,id:S.string().min(1),name:S.string().min(1),primaryObjects:S.array(_n).min(1).readonly(),reviewChecklist:S.array(S.string().min(1)).min(1).readonly(),soulId:S.string().min(1),version:S.string().min(1),views:S.array(Rn).min(1).readonly(),workspaceTypes:S.array(Bn).min(1).readonly()})});class A${packs=new Map;register(D){let u=Cn.parse(D);if(this.packs.has(u.id))throw Error(`WorkerPackRegistry: duplicate worker pack id "${u.id}"`);this.packs.set(u.id,u)}get(D){return this.packs.get(D)}require(D){let u=this.get(D);if(!u)throw Error(`WorkerPackRegistry: unknown worker pack id "${D}"`);return u}list(){return Array.from(this.packs.values())}ids(){return Array.from(this.packs.keys())}}function Hn(D=[]){let u=new A$;for(let r of D)u.register(r);return u}var YK,Jn,Gn,Cn,Xn,MK;var Un=W(()=>{YD();YK=/^[a-z][a-z0-9-]*$/,Jn=S.string().min(1).regex(YK,"worker pack id must be kebab-case"),Gn=S.object({description:S.string().min(1),id:S.string().min(1),prompt:S.string().min(1),title:S.string().min(1)}),Cn=S.object({artifactKinds:S.array(S.string().min(1)).min(1).readonly(),defaultReviewChecklist:S.array(S.string().min(1)).min(1).readonly(),description:S.string().min(1),domain:S.string().min(1),domainMd:S.string().min(1),id:Jn,label:S.string().min(1),skillMd:S.string().min(1),workOrderTemplates:S.array(Gn).min(1).readonly()}).superRefine((D,u)=>{if(!D.skillMd.includes("# "))u.addIssue({code:S.ZodIssueCode.custom,message:"skillMd must contain a markdown heading",path:["skillMd"]});if(!D.domainMd.includes("# "))u.addIssue({code:S.ZodIssueCode.custom,message:"domainMd must contain a markdown heading",path:["domainMd"]})});Xn=[{artifactKinds:["patch-plan","code-review-report","verification-report"],defaultReviewChecklist:["Evidence is grounded in repository files and commands.","Risks and verification gaps are explicit.","Recommended next action is concrete and scoped."],description:"Codebase analysis, implementation planning, and verification reports for software workspaces.",domain:"software-workspace",domainMd:`# Developer Domain
1395
1395
 
1396
1396
  ## Inputs
1397
1397
 
@@ -1491,102 +1491,102 @@ retentionDefaults: []
1491
1491
 
1492
1492
  - Do not mark unverified behavior as passed.
1493
1493
  - Do not expand QA scope without naming the tradeoff.
1494
- `,workOrderTemplates:[{description:"Create a focused regression matrix for a change or release.",id:"regression-matrix",prompt:"Build a regression matrix for this change. Include coverage, risk, test evidence, missing checks, and release recommendation.",title:"Regression matrix"}]}],DK=fB(FB)});var z2=W(()=>{nf();nf();Hf();OR();VR();KR();yR();tR();pR();hS();lS();DB();Qw();wB()});import{createHash as uK}from"crypto";import{readFile as rK,stat as AK}from"fs/promises";import $B from"path";async function JA(D,u={}){let r=await wK(D),A=await rK(r,"utf8");return qf({manifest:EK(A,r),sourceKind:"manifest-path",sourceRef:r},u)}function qf(D,u={}){let r=Hr.parse(D.manifest),A=v0(r,ow(u,r.id)),f=e4({id:r.id,name:r.name,version:r.version,protocol:r.protocol,soulId:r.soul.id,status:A.status==="valid"?"installed":"error",sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:$K(r),manifestJson:r,validationIssuesJson:A.issues,healthStatus:A.status==="valid"?"unknown":"fail",healthMessage:A.status==="valid"?null:dw(A.issues),at:nr(u)});return zr(f)}function WA(D,u={}){let r=yw(D),A=v0(r.manifestJson,ow(u,r.id));if(A.status!=="valid"){let F=F2({id:r.id,status:"error",validationIssuesJson:A.issues,healthStatus:"fail",healthMessage:dw(A.issues),lastHealthcheckAt:nr(u),at:nr(u)});return zr(F)}let f=EB(r.manifestJson,u),w=F2({id:r.id,status:"enabled",validationIssuesJson:[],healthStatus:f.status,healthMessage:f.message,lastHealthcheckAt:nr(u),at:nr(u)});return zr(w)}function GA(D,u={}){let r=yw(D),A=F2({id:r.id,status:"disabled",healthStatus:"unknown",healthMessage:"Soul App is disabled. Existing metadata is retained for audit.",at:nr(u)});return zr(A)}function Zw(D,u={}){let r=yw(D),A=v0(r.manifestJson,ow(u,r.id));if(A.status!=="valid"){let F=F2({id:r.id,status:"error",validationIssuesJson:A.issues,healthStatus:"fail",healthMessage:dw(A.issues),lastHealthcheckAt:nr(u),at:nr(u)});return zr(F)}let f=r.status==="disabled"?{message:"Soul App is disabled. Existing metadata is retained for audit.",status:"warn"}:EB(r.manifestJson,u),w=F2({id:r.id,status:r.status==="error"?"installed":r.status,validationIssuesJson:[],healthStatus:f.status,healthMessage:f.message,lastHealthcheckAt:nr(u),at:nr(u)});return zr(w)}function bf(){return qF().map((D)=>zr(D))}function Ou(D){let u=P0(D);return u?zr(u):null}function j2(){let D=bf(),u=D.map((A)=>SA(A.manifest,A.status==="enabled"?"available":"coming_soon")),r=D.filter((A)=>A.status==="enabled").flatMap((A)=>BA(A.manifest));return{apps:D,souls:u,templates:r}}function CA(D){return j2().souls.find((u)=>u.id===D)}function zf(D){return j2().templates.find((u)=>u.id===D)}function jf(D){return j2().templates.filter((u)=>u.soulId===D)}function zr(D){return Lf({healthMessage:D.healthMessage,healthStatus:D.healthStatus,manifest:D.manifestJson,manifestDigest:D.manifestDigest,sourceKind:D.sourceKind,sourceRef:D.sourceRef,status:D.status,validationIssues:D.validationIssuesJson})}async function wK(D){let u=$B.resolve(D),r=await AK(u);if(r.isDirectory())return $B.join(u,FK);if(r.isFile())return u;throw Error(`Soul App manifest path is not a file: ${D}`)}function ow(D,u){return{availableConnectorIds:D.availableConnectorIds,existingStorageNamespaces:qF().filter((r)=>r.id!==u).map((r)=>r.manifestJson.storage.namespace),hostVersion:D.hostVersion&&fK.test(D.hostVersion)?D.hostVersion:void 0}}function EB(D,u){let r=new Set(u.enabledConnectorIds??[]);if(r.size>0){let A=D.connectors.required.filter((f)=>!r.has(f.id));if(A.length>0)return{message:`Required connectors are not enabled: ${A.map((f)=>f.id).join(", ")}`,status:"warn"}}return{message:"Static manifest validation passed. No Soul App code was executed.",status:"pass"}}function $K(D){return uK("sha256").update(JSON.stringify(D)).digest("hex")}function EK(D,u){try{return JSON.parse(D)}catch(r){throw Error(`Soul App manifest is not valid JSON at ${u}: ${r instanceof Error?r.message:String(r)}`)}}function dw(D){return D.map((u)=>`${u.code}: ${u.message}`).join("; ")||"Soul App manifest validation failed."}function yw(D){let u=P0(D);if(!u)throw Error(`Soul App not found: ${D}`);return u}function nr(D){return D.now?.()??new Date().toISOString()}var fK,FK="soul-app.manifest.json";var HA=W(()=>{z2();Sr();fK=/^\d+\.\d+\.\d+$/});import nA from"path";import{fileURLToPath as gK}from"url";async function lw(D={}){let u=D.definitions??gB,r=[];for(let A of u){let f=RK(A,D),w=Ou(A.id),F=w?.status==="disabled";try{let E=await JA(f,D);if(F){E=GA(A.id,D),r.push({action:"preserved_disabled",app:E,appId:A.id,manifestPath:f});continue}if(E.status==="error"){r.push({action:"error",app:E,appId:A.id,errorMessage:E.healthMessage??"Official Soul App manifest validation failed.",manifestPath:f});continue}E=WA(A.id,D),r.push({action:w?w.status==="enabled"?"refreshed":"enabled":"installed_enabled",app:E,appId:A.id,manifestPath:f})}catch(E){r.push({action:"error",app:Ou(A.id),appId:A.id,errorMessage:E instanceof Error?E.message:String(E),manifestPath:f})}}return r}function cw(D){return d4({at:D,soulIds:["hr","qa"]})}function RK(D,u){if(nA.isAbsolute(D.manifestPath))return D.manifestPath;if(u.officialAppsRoot)return nA.resolve(u.officialAppsRoot,D.id,_K);return nA.resolve(u.repoRoot??SK(),D.manifestPath)}function SK(){let D=nA.dirname(gK(import.meta.url));return nA.resolve(D,"..","..","..","..")}var gB,_K="soul-app.manifest.json";var tw=W(()=>{Sr();HA();gB=[{id:"aiworker-hr",manifestPath:"apps/aiworker-hr/soul-app.manifest.json"},{id:"aiworker-qa",manifestPath:"apps/aiworker-qa/soul-app.manifest.json"}]});function xw(D,u={}){let r=u.availableConnectorIds?new Set(u.availableConnectorIds):null,A=u.enabledConnectorIds?new Set(u.enabledConnectorIds):null,f=D.manifest.connectors.required.map((R)=>_B(R,!0,r,A)),w=D.manifest.connectors.optional.map((R)=>_B(R,!1,r,A)),F=BK(D),E=f.filter((R)=>!R.available).map((R)=>R.id),$=f.filter((R)=>R.available&&!R.enabled).map((R)=>R.id),g=[];if(E.length>0)g.push(`Required connectors are not available: ${E.join(", ")}`);if($.length>0)g.push(`Required connectors are not enabled: ${$.join(", ")}`);return{appId:D.appId,connectors:{optional:w,required:f},descriptorPermissions:F,healthStatus:D.healthStatus,manifestPermissions:D.manifest.permissions,status:D.status,summary:{canEnable:D.status!=="error"&&E.length===0,descriptorPermissionCount:F.reduce((R,S)=>R+S.requiredPermissions.length,0),disabledRequiredConnectorIds:$,manifestPermissionCount:D.manifest.permissions.length,missingRequiredConnectorIds:E,optionalConnectorCount:w.length,requiredConnectorCount:f.length,warnings:g}}}function _B(D,u,r,A){return{access:D.access,available:r?r.has(D.id):!0,enabled:A?A.has(D.id):!1,id:D.id,reason:D.reason,required:u,scopes:D.scopes}}function BK(D){let u=D.manifest.ui.shell,r=[];if(u?.primaryAction?.requiredPermissions?.length)r.push({id:u.primaryAction.id,label:u.primaryAction.label,requiredPermissions:u.primaryAction.requiredPermissions,surface:"shell.primaryAction"});for(let A of u?.actions??[])if(A.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.requiredPermissions,surface:"shell.action"});if(u?.search?.requiredPermissions?.length)r.push({id:u.search.id,label:u.search.label,requiredPermissions:u.search.requiredPermissions,surface:"shell.search"});if(u?.settings?.requiredPermissions?.length)r.push({id:u.settings.id,label:u.settings.label,requiredPermissions:u.settings.requiredPermissions,surface:"shell.settings"});for(let A of D.manifest.ui.routes)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.route"});for(let A of D.manifest.ui.panels)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.panel"});for(let A of D.manifest.ui.artifactPreviews)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.artifactPreview"});for(let A of D.manifest.ui.reviewPanels)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.reviewPanel"});for(let A of D.manifest.ui.workspaceWidgets??[])if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.workspaceWidget"});return r}class Tf{#D=new Set;subscribe(D){return this.#D.add(D),()=>this.#D.delete(D)}emit(D){for(let u of[...this.#D])u(D)}}function SB(D,u){if(D==="claude")return XK(u);return JK(D,u)}function JK(D,u){let r="",A={codexToolUses:new Set,cursorTextSoFar:"",openCodeToolUses:new Set},f=(w)=>{let F;try{F=JSON.parse(w)}catch{u({line:w,type:"raw"});return}if(D==="codex"&&GK(F,u,A))return;if(D==="cursor-agent"&&HK(F,u,A))return;if(D==="gemini"&&CK(F,u))return;if(D==="opencode"&&WK(F,u,A))return;u({line:w,type:"raw"})};return{feed(w){r+=w;let F=r.indexOf(`
1494
+ `,workOrderTemplates:[{description:"Create a focused regression matrix for a change or release.",id:"regression-matrix",prompt:"Build a regression matrix for this change. Include coverage, risk, test evidence, missing checks, and release recommendation.",title:"Regression matrix"}]}],MK=Hn(Xn)});var s2=W(()=>{Mf();Mf();Yf();v_();y_();c_();ER();_R();BR();tR();$n();Wn();p9();Un()});import{createHash as OK}from"crypto";import{readFile as PK,stat as kK}from"fs/promises";import Yn from"path";async function G1(D,u={}){let r=await KK(D),A=await PK(r,"utf8");return jf({manifest:NK(A,r),sourceKind:"manifest-path",sourceRef:r},u)}function jf(D,u={}){let r=Hr.parse(D.manifest),A=v0(r,F$(u,r.id)),f=JE({id:r.id,name:r.name,version:r.version,protocol:r.protocol,soulId:r.soul.id,status:A.status==="valid"?"installed":"error",sourceKind:D.sourceKind,sourceRef:D.sourceRef,manifestDigest:hK(r),manifestJson:r,validationIssuesJson:A.issues,healthStatus:A.status==="valid"?"unknown":"fail",healthMessage:A.status==="valid"?null:w$(A.issues),at:Xr(u)});return zr(f)}function C1(D,u={}){let r=$$(D),A=v0(r.manifestJson,F$(u,r.id));if(A.status!=="valid"){let F=w2({id:r.id,status:"error",validationIssuesJson:A.issues,healthStatus:"fail",healthMessage:w$(A.issues),lastHealthcheckAt:Xr(u),at:Xr(u)});return zr(F)}let f=Mn(r.manifestJson,u),w=w2({id:r.id,status:"enabled",validationIssuesJson:[],healthStatus:f.status,healthMessage:f.message,lastHealthcheckAt:Xr(u),at:Xr(u)});return zr(w)}function H1(D,u={}){let r=$$(D),A=w2({id:r.id,status:"disabled",healthStatus:"unknown",healthMessage:"Soul App is disabled. Existing metadata is retained for audit.",at:Xr(u)});return zr(A)}function f$(D,u={}){let r=$$(D),A=v0(r.manifestJson,F$(u,r.id));if(A.status!=="valid"){let F=w2({id:r.id,status:"error",validationIssuesJson:A.issues,healthStatus:"fail",healthMessage:w$(A.issues),lastHealthcheckAt:Xr(u),at:Xr(u)});return zr(F)}let f=r.status==="disabled"?{message:"Soul App is disabled. Existing metadata is retained for audit.",status:"warn"}:Mn(r.manifestJson,u),w=w2({id:r.id,status:r.status==="error"?"installed":r.status,validationIssuesJson:[],healthStatus:f.status,healthMessage:f.message,lastHealthcheckAt:Xr(u),at:Xr(u)});return zr(w)}function Tf(){return vF().map((D)=>zr(D))}function Ou(D){let u=O0(D);return u?zr(u):null}function z2(){let D=Tf(),u=D.map((A)=>W1(A.manifest,A.status==="enabled"?"available":"coming_soon")),r=D.filter((A)=>A.status==="enabled").flatMap((A)=>J1(A.manifest));return{apps:D,souls:u,templates:r}}function X1(D){return z2().souls.find((u)=>u.id===D)}function vf(D){return z2().templates.find((u)=>u.id===D)}function Zf(D){return z2().templates.filter((u)=>u.soulId===D)}function zr(D){return zf({healthMessage:D.healthMessage,healthStatus:D.healthStatus,manifest:D.manifestJson,manifestDigest:D.manifestDigest,sourceKind:D.sourceKind,sourceRef:D.sourceRef,status:D.status,validationIssues:D.validationIssuesJson})}async function KK(D){let u=Yn.resolve(D),r=await kK(u);if(r.isDirectory())return Yn.join(u,VK);if(r.isFile())return u;throw Error(`Soul App manifest path is not a file: ${D}`)}function F$(D,u){return{availableConnectorIds:D.availableConnectorIds,existingStorageNamespaces:vF().filter((r)=>r.id!==u).map((r)=>r.manifestJson.storage.namespace),hostVersion:D.hostVersion&&IK.test(D.hostVersion)?D.hostVersion:void 0}}function Mn(D,u){let r=new Set(u.enabledConnectorIds??[]);if(r.size>0){let A=D.connectors.required.filter((f)=>!r.has(f.id));if(A.length>0)return{message:`Required connectors are not enabled: ${A.map((f)=>f.id).join(", ")}`,status:"warn"}}return{message:"Static manifest validation passed. No Soul App code was executed.",status:"pass"}}function hK(D){return OK("sha256").update(JSON.stringify(D)).digest("hex")}function NK(D,u){try{return JSON.parse(D)}catch(r){throw Error(`Soul App manifest is not valid JSON at ${u}: ${r instanceof Error?r.message:String(r)}`)}}function w$(D){return D.map((u)=>`${u.code}: ${u.message}`).join("; ")||"Soul App manifest validation failed."}function $$(D){let u=O0(D);if(!u)throw Error(`Soul App not found: ${D}`);return u}function Xr(D){return D.now?.()??new Date().toISOString()}var IK,VK="soul-app.manifest.json";var i1=W(()=>{s2();nr();IK=/^\d+\.\d+\.\d+$/});import U1 from"path";import{fileURLToPath as QK}from"url";async function E$(D={}){let u=D.definitions??On,r=[];for(let A of u){let f=qK(A,D),w=Ou(A.id),F=w?.status==="disabled";try{let E=await G1(f,D);if(F){E=H1(A.id,D),r.push({action:"preserved_disabled",app:E,appId:A.id,manifestPath:f});continue}if(E.status==="error"){r.push({action:"error",app:E,appId:A.id,errorMessage:E.healthMessage??"Official Soul App manifest validation failed.",manifestPath:f});continue}E=C1(A.id,D),r.push({action:w?w.status==="enabled"?"refreshed":"enabled":"installed_enabled",app:E,appId:A.id,manifestPath:f})}catch(E){r.push({action:"error",app:Ou(A.id),appId:A.id,errorMessage:E instanceof Error?E.message:String(E),manifestPath:f})}}return r}function g$(D){return $E({at:D,soulIds:["hr","qa"]})}function qK(D,u){if(U1.isAbsolute(D.manifestPath))return D.manifestPath;if(u.officialAppsRoot)return U1.resolve(u.officialAppsRoot,D.id,LK);return U1.resolve(u.repoRoot??bK(),D.manifestPath)}function bK(){let D=U1.dirname(QK(import.meta.url));return U1.resolve(D,"..","..","..","..")}var On,LK="soul-app.manifest.json";var S$=W(()=>{nr();i1();On=[{id:"aiworker-hr",manifestPath:"apps/aiworker-hr/soul-app.manifest.json"},{id:"aiworker-qa",manifestPath:"apps/aiworker-qa/soul-app.manifest.json"}]});function _$(D,u={}){let r=u.availableConnectorIds?new Set(u.availableConnectorIds):null,A=u.enabledConnectorIds?new Set(u.enabledConnectorIds):null,f=D.manifest.connectors.required.map((_)=>Pn(_,!0,r,A)),w=D.manifest.connectors.optional.map((_)=>Pn(_,!1,r,A)),F=sK(D),E=f.filter((_)=>!_.available).map((_)=>_.id),$=f.filter((_)=>_.available&&!_.enabled).map((_)=>_.id),g=[];if(E.length>0)g.push(`Required connectors are not available: ${E.join(", ")}`);if($.length>0)g.push(`Required connectors are not enabled: ${$.join(", ")}`);return{appId:D.appId,connectors:{optional:w,required:f},descriptorPermissions:F,healthStatus:D.healthStatus,manifestPermissions:D.manifest.permissions,status:D.status,summary:{canEnable:D.status!=="error"&&E.length===0,descriptorPermissionCount:F.reduce((_,R)=>_+R.requiredPermissions.length,0),disabledRequiredConnectorIds:$,manifestPermissionCount:D.manifest.permissions.length,missingRequiredConnectorIds:E,optionalConnectorCount:w.length,requiredConnectorCount:f.length,warnings:g}}}function Pn(D,u,r,A){return{access:D.access,available:r?r.has(D.id):!0,enabled:A?A.has(D.id):!1,id:D.id,reason:D.reason,required:u,scopes:D.scopes}}function sK(D){let u=D.manifest.ui.shell,r=[];if(u?.primaryAction?.requiredPermissions?.length)r.push({id:u.primaryAction.id,label:u.primaryAction.label,requiredPermissions:u.primaryAction.requiredPermissions,surface:"shell.primaryAction"});for(let A of u?.actions??[])if(A.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.requiredPermissions,surface:"shell.action"});if(u?.search?.requiredPermissions?.length)r.push({id:u.search.id,label:u.search.label,requiredPermissions:u.search.requiredPermissions,surface:"shell.search"});if(u?.settings?.requiredPermissions?.length)r.push({id:u.settings.id,label:u.settings.label,requiredPermissions:u.settings.requiredPermissions,surface:"shell.settings"});for(let A of D.manifest.ui.routes)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.route"});for(let A of D.manifest.ui.panels)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.panel"});for(let A of D.manifest.ui.artifactPreviews)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.artifactPreview"});for(let A of D.manifest.ui.reviewPanels)if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.reviewPanel"});for(let A of D.manifest.ui.workspaceWidgets??[])if(A.surface?.requiredPermissions?.length)r.push({id:A.id,label:A.label,requiredPermissions:A.surface.requiredPermissions,surface:"ui.workspaceWidget"});return r}import{createHash as zK}from"crypto";import{mkdir as kn,readdir as jK,readFile as R$,stat as TK,writeFile as In}from"fs/promises";import KD from"path";async function Kn(D){let u=KD.resolve(D.sourceRoot),r=KD.resolve(D.workspaceRoot),A=D.now,f=[];await kn(KD.join(r,".aiworker"),{recursive:!0}),f.push(...await dK({...D,generatedAt:A,sourceRoot:u,workspaceRoot:r})),f.push(...await lK({...D,generatedAt:A,sourceRoot:u,workspaceRoot:r})),f.push(...await yK({...D,generatedAt:A,sourceRoot:u,workspaceRoot:r}));let w={appId:D.appId,generatedAt:A,projections:f,version:1};return await In(KD.join(r,...Vn.split("/")),`${JSON.stringify(w,null,2)}
1495
+ `,"utf8"),w}function hn(){return Vn}function Nn(D){if(!D)return null;if(D==="codex"||D.startsWith("codex/"))return"codex";if(D==="claude-code"||D.startsWith("claude-code/"))return"claude-code";return null}async function dK(D){let u=KD.join(D.sourceRoot,"engine-assets","workspace"),r=await Qn(u),A=[];for(let f of r){let w=KD.relative(u,f).split(KD.sep).join("/"),F=KD.posix.join("engine-assets","workspace",w),E=aK(await R$(f,"utf8"),D.variables);await B$(D.workspaceRoot,w,E),A.push(n$(D,"workspace-file",F,w,E))}return A}async function lK(D){let u=KD.join(D.sourceRoot,"engine-assets","skills"),r=await Ln(u),A=[],f=new Set(D.engineAssets?.skills?.targets??["codex","claude-code"]);for(let w of r){if(!w.isDirectory()||!vK.test(w.name))continue;let F=KD.join(u,w.name,of);if(!await qn(F))continue;let E=await R$(F,"utf8"),$=`${D.appId}-${w.name}`,g=[{engineTarget:"codex",path:KD.posix.join(".agents","skills",$,of)},{engineTarget:"claude-code",path:KD.posix.join(".claude","skills",$,of)}].filter((_)=>f.has(_.engineTarget));for(let _ of g)await B$(D.workspaceRoot,_.path,E),A.push(n$(D,"native-skill",KD.posix.join("engine-assets","skills",w.name,of),_.path,E,_.engineTarget))}return A}async function yK(D){if(!D.engineTarget)return[];let u=(D.engineAssets?.mcpClients??[]).filter((f)=>f.target===D.engineTarget),r=cK(D.engineTarget),A=[];for(let f of u){let w=tK(f.source),F=KD.posix.join(w,r.sourceFile),E=KD.join(D.sourceRoot,...F.split("/"));if(!await qn(E))throw Error(`MCP client config not found for ${D.engineTarget}: ${F}`);let $=await R$(E,"utf8");pK($,F),await B$(D.workspaceRoot,r.targetPath,$),A.push(n$(D,"mcp-client",F,r.targetPath,$,D.engineTarget))}return A}function cK(D){if(D==="codex")return{sourceFile:"config.toml",targetPath:KD.posix.join(".codex","config.toml")};return{sourceFile:".mcp.json",targetPath:".mcp.json"}}function tK(D){return D.replace(/^\.\//,"").split("/").filter(Boolean).join("/")}function pK(D,u){if(xK(D)||oK.test(D))throw Error(`MCP client config must not contain literal secrets: ${u}`)}function xK(D){for(let u of D.matchAll(ZK)){let r=u[2]?.trim()??"";if(!mK(r))return!0}return!1}function mK(D){return D.startsWith("$")||D.startsWith("env:")||D.startsWith("secretRef:")}function n$(D,u,r,A,f,w){return{appId:D.appId,generatedAt:D.generatedAt,kind:u,sha256:zK("sha256").update(f).digest("hex"),source:r,target:A,...w?{engineTarget:w}:{}}}function aK(D,u){return D.replace(/\{\{([a-z][a-z0-9]*)\}\}/gi,(r,A)=>u[A]??"")}async function B$(D,u,r){let A=KD.join(D,...u.split("/"));await kn(KD.dirname(A),{recursive:!0}),await In(A,r,"utf8")}async function Qn(D){let u=await Ln(D),r=[];for(let A of u){let f=KD.join(D,A.name);if(A.isDirectory()){r.push(...await Qn(f));continue}if(A.isFile())r.push(f)}return r.sort((A,f)=>A.localeCompare(f))}async function Ln(D){try{return await jK(D,{withFileTypes:!0})}catch(u){if(bn(u))return[];throw u}}async function qn(D){try{return(await TK(D)).isFile()}catch(u){if(bn(u))return!1;throw u}}function bn(D){return typeof D==="object"&&D!==null&&"code"in D&&D.code==="ENOENT"}var vK,of="SKILL.md",Vn,ZK,oK;var sn=W(()=>{vK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Vn=KD.posix.join(".aiworker","projections.json"),ZK=/["']?([\w-]*(?:api[_-]?key|authorization|password|secret|token)[\w-]*)["']?\s*[:=]\s*["']([^"'\n]+)["']/gi,oK=/Bearer\s+[\w.~+/-]{12,}|sk-[\w-]{8,}/i});class df{#D=new Set;subscribe(D){return this.#D.add(D),()=>this.#D.delete(D)}emit(D){for(let u of[...this.#D])u(D)}}function jn(D,u){if(D==="claude")return wh(u);return eK(D,u)}function eK(D,u){let r="",A={codexToolUses:new Set,cursorTextSoFar:"",openCodeToolUses:new Set},f=(w)=>{let F;try{F=JSON.parse(w)}catch{u({line:w,type:"raw"});return}if(D==="codex"&&uh(F,u,A))return;if(D==="cursor-agent"&&Ah(F,u,A))return;if(D==="gemini"&&rh(F,u))return;if(D==="opencode"&&Dh(F,u,A))return;u({line:w,type:"raw"})};return{feed(w){r+=w;let F=r.indexOf(`
1495
1496
  `);while(F!==-1){let E=r.slice(0,F).trim();if(r=r.slice(F+1),E)f(E);F=r.indexOf(`
1496
- `)}},flush(){let w=r.trim();if(r="",w)f(w)}}}function WK(D,u,r){let A=BD(D);if(!A)return!1;let f=BD(A.part);if(A.type==="step_start")return u({label:"running",type:"status"}),!0;if(A.type==="text"){let w=fD(f?.text);if(w)return u({delta:w,type:"text_delta"}),!0}if(A.type==="tool_use"){let w=fD(f?.tool),F=fD(f?.callID);if(!w||!F)return!1;let E=BD(f?.state),$=`${fD(A.sessionID,"session")}:${F}`;if(!r.openCodeToolUses.has($))r.openCodeToolUses.add($),u({id:F,input:MK(E?.input)??E?.input??null,name:w,type:"tool_use"});if(E?.status==="completed")u({content:mw(E.output),isError:!1,toolUseId:F,type:"tool_result"});return!0}if(A.type==="step_finish"){let w=BD(f?.tokens);if(w)return u({costUsd:aD(f?.cost),inputTokens:aD(w.input),outputTokens:aD(w.output),type:"usage"}),!0}return!1}function GK(D,u,r){let A=BD(D);if(!A)return!1;let f=fD(A.type);if(f==="thread.started")return u({label:"initializing",type:"status"}),!0;if(f==="turn.started")return u({label:"running",type:"status"}),!0;let w=BD(A.item);if(f==="item.started"&&w?.type==="command_execution"){if(!fD(w.id))return!1;return RB(w,u,r),!0}if(f==="item.completed"&&w?.type==="command_execution"){let F=fD(w.id);if(!F)return!1;return RB(w,u,r),u({content:mw(w.aggregated_output??w.output??""),isError:typeof w.exit_code==="number"?w.exit_code!==0:w.status==="failed",toolUseId:F,type:"tool_result"}),!0}if((f==="item.started"||f==="item.completed")&&w?.type==="file_change"){let F=Array.isArray(w.changes)?w.changes:[];for(let E of F){let $=BD(E),g=fD($?.path);if(!g)continue;u({action:fD($?.kind,"change"),path:g,status:fD(w.status)||(f==="item.started"?"in_progress":"completed"),type:"file_change"})}return F.length>0}if(f==="item.completed"&&w?.type==="agent_message"){let F=fD(w.text??w.content);if(F)return u({delta:F,type:"text_delta"}),!0}if(f==="turn.completed"){let F=BD(A.usage);if(F)return u({inputTokens:aD(F.input_tokens),outputTokens:aD(F.output_tokens),type:"usage"}),!0}return!1}function RB(D,u,r){let A=fD(D.id);if(!A||r.codexToolUses.has(A))return;r.codexToolUses.add(A),u({id:A,input:{command:fD(D.command)},name:"Bash",type:"tool_use"})}function CK(D,u){let r=BD(D);if(!r)return!1;if(r.type==="init")return u({detail:fD(r.model)||void 0,label:"initializing",type:"status"}),!0;if(r.type==="message"&&r.role==="assistant"){let A=fD(r.content);if(A)return u({delta:A,type:"text_delta"}),!0}if(r.type==="result"){let A=BD(r.stats);if(A)return u({durationMs:aD(A.duration_ms),inputTokens:aD(A.input_tokens),outputTokens:aD(A.output_tokens),type:"usage"}),!0}return!1}function HK(D,u,r){let A=BD(D);if(!A)return!1;if(A.type==="system"){if(fD(A.subtype)==="init")return u({detail:fD(A.model)||void 0,label:"initializing",type:"status"}),!0}if(A.type==="assistant"){let f=nK(BD(A.message));if(!f)return!1;return UK(f,u,r),!0}if(A.type==="result"){let f=BD(A.usage);if(f)return u({durationMs:aD(A.duration_ms),inputTokens:aD(f.inputTokens),outputTokens:aD(f.outputTokens),type:"usage"}),!0}return!1}function nK(D){return(Array.isArray(D?.content)?D.content:[]).map((r)=>BD(r)).filter((r)=>r?.type==="text").map((r)=>fD(r?.text)).join("")}function UK(D,u,r){if(!r.cursorTextSoFar){r.cursorTextSoFar=D,u({delta:D,type:"text_delta"});return}if(D===r.cursorTextSoFar)return;if(D.startsWith(r.cursorTextSoFar)){let A=D.slice(r.cursorTextSoFar.length);if(r.cursorTextSoFar=D,A)u({delta:A,type:"text_delta"});return}r.cursorTextSoFar+=D,u({delta:D,type:"text_delta"})}function XK(D){let u="",r=new Map,A=new Set,f=null,w=($)=>`${f??"anon"}:${String($)}`,F=($)=>{let g=BD($);if(!g)return;if(g.type==="system"&&g.subtype==="init"){D({detail:fD(g.model)||void 0,label:"initializing",type:"status"});return}if(g.type==="system"&&g.subtype==="status"){D({label:fD(g.status,"working"),type:"status"});return}if(g.type==="stream_event"){YK(BD(g.event),{blockKey:w,blocks:r,currentMessageId:()=>f,onEvent:D,setCurrentMessageId:(R)=>f=R,textStreamed:A});return}if(g.type==="assistant"){let R=BD(g.message),S=Array.isArray(R?.content)?R.content:[],B=fD(R?.id);if(B)f=B;let J=B?A.has(B):!1;for(let H of S){let G=BD(H);if(!G)continue;if(G.type==="tool_use")D({id:fD(G.id),input:G.input??null,name:fD(G.name,"Tool"),type:"tool_use"});else if(!J&&G.type==="text"){let U=fD(G.text);if(U)D({delta:U,type:"text_delta"})}else if(!J&&G.type==="thinking"){let U=fD(G.thinking);if(U)D({delta:U,type:"thinking_delta"})}}return}if(g.type==="user"){let R=BD(g.message),S=Array.isArray(R?.content)?R.content:[];for(let B of S){let J=BD(B);if(J?.type==="tool_result")D({content:mw(J.content),isError:J.is_error===!0,toolUseId:fD(J.tool_use_id),type:"tool_result"})}return}if(g.type==="result"){let R=BD(g.usage);D({costUsd:aD(g.total_cost_usd),durationMs:aD(g.duration_ms),inputTokens:aD(R?.input_tokens),outputTokens:aD(R?.output_tokens),type:"usage"})}},E=($)=>{try{F(JSON.parse($))}catch{D({line:$,type:"raw"})}};return{feed($){u+=$;let g=u.indexOf(`
1497
- `);while(g!==-1){let R=u.slice(0,g).trim();if(u=u.slice(g+1),R)E(R);g=u.indexOf(`
1498
- `)}},flush(){let $=u.trim();if(u="",$)E($)}}}function YK(D,u){if(!D)return;if(D.type==="message_start"){let r=BD(D.message);if(u.setCurrentMessageId(fD(r?.id)||null),typeof D.ttft_ms==="number")u.onEvent({detail:`first token in ${Math.round(D.ttft_ms/100)/10}s`,label:"streaming",type:"status"});return}if(D.type==="content_block_start"){let r=BD(D.content_block),A=u.blockKey(D.index);if(u.blocks.set(A,{id:fD(r?.id)||void 0,input:"",name:fD(r?.name)||void 0,type:fD(r?.type)||void 0}),r?.type==="thinking")u.onEvent({type:"thinking_start"});return}if(D.type==="content_block_delta"){let r=BD(D.delta);if(r?.type==="text_delta"){let A=u.currentMessageId();if(A)u.textStreamed.add(A);u.onEvent({delta:fD(r.text),type:"text_delta"});return}if(r?.type==="thinking_delta"){let A=u.currentMessageId();if(A)u.textStreamed.add(A);u.onEvent({delta:fD(r.thinking),type:"thinking_delta"});return}if(r?.type==="input_json_delta"){let A=u.blocks.get(u.blockKey(D.index));if(A)A.input+=fD(r.partial_json)}}if(D.type==="content_block_stop")u.blocks.delete(u.blockKey(D.index))}function mw(D){if(typeof D==="string")return D;if(Array.isArray(D))return D.map((u)=>{let r=BD(u);return r?.type==="text"?fD(r.text):JSON.stringify(u)}).join(`
1499
- `);if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}}function MK(D){if(D==null)return null;if(typeof D==="object")return D;if(typeof D!=="string")return null;try{return JSON.parse(D)}catch{return null}}function BD(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)?D:null}function fD(D,u=""){return typeof D==="string"&&D.length>0?D:u}function aD(D){return typeof D==="number"&&Number.isFinite(D)?D:void 0}import{spawn as OK,spawnSync as PK}from"child_process";import{randomUUID as iK}from"crypto";import{mkdir as kK,readdir as IK,readFile as VK,stat as KK,writeFile as pw}from"fs/promises";import Ur from"path";import T2 from"process";function aw(){return{async invoke(D){if(cu(D.metadata?.executionMode,"local-cli")==="byok")return QK(D);return NK(D)}}}async function NK(D){let u=D.engineCommand||D.engineId;if(!u||u==="internal")throw Error("Local CLI execution requires an external engine command.");let r=hK[D.engineId];if(!r)throw Error(`Local CLI engine is not wired yet: ${D.engineId}. Select a supported local engine or BYOK in Settings.`);await kK(D.invocationRoot,{recursive:!0});let A=cu(D.metadata?.outputKind,"business-artifact"),f=cu(D.metadata?.skillName,"Soul artifact"),w=Ur.posix.join("artifacts",D.sessionId,`${D.turnId}-${WB(A)}.md`),F=[D.prompt,"","AIWorker session contract:","- Continue the current AIWorker workspace session as the selected external engine.","- Current working directory is the AIWorker workspace/project root.",`- If this turn produces a durable business artifact, write markdown under artifacts/${D.sessionId}/.`,`- Prefer ${w} for a new ${A} artifact.`,"- Text-only clarification, analysis, or follow-up is allowed; do not create a fake artifact just to satisfy the protocol.","- Keep evidence, assumptions, risks, review notes, and next actions separated in any durable artifact.","- Return a concise assistant message for the session timeline."].join(`
1500
- `);await pw(Ur.join(D.invocationRoot,"prompt.md"),F,"utf8"),B0(D,{kind:"status",label:"initializing",detail:`${r.name} via local CLI`});let E=r.buildArgs({command:u,input:D,model:cu(D.metadata?.model,""),reasoning:cu(D.metadata?.reasoning,"")}),$="",g=Date.now(),R=r.parser?SB(r.parser,(J)=>{let H=bK(J);if(H.kind==="text")$+=H.text;B0(D,H)}):null,S=await qK(u,E,F,300000,{cwd:D.workspaceRoot,env:{...T2.env,...r.env??{}},onStderr:void 0,onStdout:(J)=>{if(R){R.feed(J);return}$+=J,B0(D,{kind:"text",text:J})}});if(R?.flush(),await pw(Ur.join(D.invocationRoot,"stdout.log"),S.stdout,"utf8"),await pw(Ur.join(D.invocationRoot,"stderr.log"),S.stderr,"utf8"),S.code!==0){let J=vK(S.stderr||S.stdout);if(J.trim())B0(D,{chunk:JB(J,8000),kind:"log",stream:S.stderr?"stderr":"stdout"});throw Error(`${u} exited with code ${S.code}: ${JB(J||S.stderr||S.stdout,2000)}`)}$=$.trim();let B=await zK({fallbackKind:A,fallbackTitle:f,sessionId:D.sessionId,sinceMs:g,turnId:D.turnId,workspaceRoot:D.workspaceRoot});return B0(D,{kind:"status",label:"completed",detail:B.length>0?`${B.length} artifact${B.length===1?"":"s"}`:"text response"}),{artifacts:B,lessons:[],metadata:{executionSource:"local-cli",finalMessage:$,processId:iK(),stderrLog:Ur.join(D.invocationRoot,"stderr.log"),stdoutLog:Ur.join(D.invocationRoot,"stdout.log")},review:B.length>0?{findings:[{message:"External engine artifact generated; human review is required before memory admission."}],risks:[],verdict:"needs_review"}:void 0,summary:$||`${r.name} completed without a durable artifact.`}}async function QK(D){let u=GB(D.metadata?.byok)?D.metadata.byok:{},r=cu(u.apiKeyRef,""),A=sK(r),f=cu(u.baseUrl,"https://api.openai.com/v1").replace(/\/+$/,""),w=cu(u.model,"gpt-4o");B0(D,{kind:"status",label:"requesting",detail:w});let F=await LK({apiKey:A,baseUrl:f,input:D,model:w}),E=cu(D.metadata?.outputKind,"business-artifact"),$=cu(D.metadata?.skillName,"Soul artifact");return B0(D,{kind:"text",text:`Generated ${$} with BYOK provider ${w}.`}),B0(D,{kind:"status",label:"completed",detail:E}),{artifacts:[{content:F,kind:E,path:Ur.posix.join("artifacts",D.sessionId,`${D.turnId}-${WB(E)}.md`),title:$}],lessons:[],metadata:{executionSource:"byok",model:w},review:{findings:[{message:"BYOK artifact generated; human review is required before memory admission."}],risks:[],verdict:"needs_review"},summary:`Generated ${$} with BYOK provider ${w}.`}}async function LK({apiKey:D,baseUrl:u,input:r,model:A}){let f=cu(r.metadata?.skillName,"Soul artifact"),w=await fetch(`${u}/chat/completions`,{body:JSON.stringify({messages:[{content:"You are AIWorker external engine mode. Return one concise markdown business artifact. Keep evidence, assumptions, risks, review notes, and next actions separated.",role:"system"},{content:r.prompt,role:"user"}],model:A,temperature:0.2}),headers:{authorization:`Bearer ${D}`,"content-type":"application/json"},method:"POST"});if(!w.ok)throw Error(`BYOK provider failed for ${f}: HTTP ${w.status}`);let E=(await w.json()).choices?.[0]?.message?.content?.trim();if(!E)throw Error(`BYOK provider returned no artifact content for ${f}.`);return E}function qK(D,u,r,A,f={}){return new Promise((w,F)=>{let E=OK(D,u,{cwd:f.cwd??T2.cwd(),env:f.env??T2.env,stdio:["pipe","pipe","pipe"]}),$="",g="",R=!1,S=setTimeout(()=>{R=!0,E.kill("SIGTERM")},A);E.stdout.setEncoding("utf8"),E.stderr.setEncoding("utf8"),E.stdout.on("data",(B)=>{$+=B,f.onStdout?.(B)}),E.stderr.on("data",(B)=>{g+=B,f.onStderr?.(B)}),E.stdin.on("error",(B)=>{if(B.code!=="EPIPE")clearTimeout(S),F(B)}),E.on("error",(B)=>{clearTimeout(S),F(B)}),E.on("close",(B)=>{if(clearTimeout(S),R)g+=`
1501
- Process exceeded ${A}ms and was terminated.`;w({code:B,stdout:$,stderr:g})}),E.stdin.end(r)})}function bK(D){if(D.type==="status")return{detail:D.detail,kind:"status",label:D.label};if(D.type==="text_delta")return{kind:"text",text:D.delta};if(D.type==="thinking_delta")return{kind:"thinking",text:D.delta};if(D.type==="thinking_start")return{detail:"external engine reasoning started",kind:"status",label:"thinking"};if(D.type==="file_change")return{detail:`${D.action} ${D.path}${D.status?` (${D.status})`:""}`,kind:"status",label:"file_change"};if(D.type==="tool_use")return{id:D.id,input:GB(D.input)?D.input:{value:D.input},kind:"tool_use",name:D.name};if(D.type==="tool_result")return{content:D.content,id:D.toolUseId,isError:D.isError,kind:"tool_result"};if(D.type==="usage")return{costUsd:D.costUsd,inputTokens:D.inputTokens,kind:"usage",outputTokens:D.outputTokens};return{kind:"raw",line:D.line}}async function zK({fallbackKind:D,fallbackTitle:u,sessionId:r,sinceMs:A,turnId:f,workspaceRoot:w}){let F=Ur.join(w,"artifacts",r),E=[];try{E=await IK(F)}catch{return[]}let $=[];for(let g of E.sort()){if(!g.endsWith(".md")&&!g.endsWith(".markdown"))continue;let R=Ur.join(F,g),S=await KK(R).catch(()=>null);if(!S?.isFile())continue;if(!(g.includes(f)||S.mtimeMs>=A-1000))continue;let J=Ur.posix.join("artifacts",r,g);$.push({content:await VK(R,"utf8"),kind:D,path:J,title:u})}return $}function jK(D,u,r){let A=`${D}\x00${u.join("\x00")}\x00${r}`,f=BB.get(A);if(f!==void 0)return f;let w=PK(D,u,{encoding:"utf8",timeout:5000}),F=`${w.stdout??""}
1502
- ${w.stderr??""}`,E=w.status===0&&F.includes(r);return BB.set(A,E),E}function TK(D,u){let r=D.includes("/")?D.split("/").at(-1)??D:D;if((!r||r==="default"||r.startsWith("gpt-5.2")||r.startsWith("gpt-5.3")||r.startsWith("gpt-5.4")||r.startsWith("gpt-5.5"))&&u==="minimal")return"low";if(r==="gpt-5.1"&&u==="xhigh")return"high";if(r==="gpt-5.1-codex-mini")return u==="high"||u==="xhigh"?"high":"medium";return u}function B0(D,u){D.onEvent?.(u)}function JB(D,u){if(D.length<=u)return D;return`${D.slice(0,u)}
1503
- ...[truncated]`}function vK(D){if(D.includes("failed to warm featured plugin ids cache")&&D.includes("/backend-api/plugins/featured")){let u=D.indexOf("OpenAI Codex v");return u===-1?"":D.slice(u)}return D}function sK(D){let u=D.trim();if(!u)throw Error("BYOK mode requires an API key reference such as env:OPENAI_API_KEY.");let r=u.startsWith("env:")?u.slice(4):u;if(!/^[A-Z_]\w*$/i.test(r))throw Error("BYOK API key reference must be env:NAME or NAME.");let A=T2.env[r];if(!A)throw Error(`BYOK API key environment variable is not set: ${r}.`);return A}function WB(D){return D.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function cu(D,u){return typeof D==="string"&&D.trim().length>0?D.trim():u}function GB(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}var hK,BB;var ew=W(()=>{hK={"claude-code":{buildArgs({command:D,model:u}){let r=["-p","--output-format","stream-json","--verbose"];if(jK(D,["-p","--help"],"--include-partial-messages"))r.push("--include-partial-messages");if(u&&u!=="default")r.push("--model",u);return r.push("--permission-mode","bypassPermissions"),r},name:"Claude Code",parser:"claude"},codex:{buildArgs({input:D,model:u,reasoning:r}){let A=["exec","--json","--skip-git-repo-check","--sandbox","workspace-write","-c","sandbox_workspace_write.network_access=true","-C",D.workspaceRoot];if(T2.env.AIWORKER_CODEX_DISABLE_PLUGINS==="1"||T2.env.OD_CODEX_DISABLE_PLUGINS==="1")A.push("--disable","plugins");if(u&&u!=="default")A.push("--model",u);if(r&&r!=="default")A.push("-c",`model_reasoning_effort="${TK(u,r)}"`);return A},name:"Codex CLI",parser:"codex"},cursor:{buildArgs({input:D,model:u}){let r=["--print","--output-format","stream-json","--stream-partial-output","--force","--trust","--workspace",D.workspaceRoot];if(u&&u!=="default")r.push("--model",u);return r},name:"Cursor Agent",parser:"cursor-agent"},gemini:{buildArgs({model:D}){let u=["--output-format","stream-json","--yolo"];if(D&&D!=="default")u.push("--model",D);return u},env:{GEMINI_CLI_TRUST_WORKSPACE:"true"},name:"Gemini CLI",parser:"gemini"},opencode:{buildArgs({model:D}){let u=["run","--format","json","--dangerously-skip-permissions"];if(D&&D!=="default")u.push("--model",D);return u.push("-"),u},name:"OpenCode",parser:"opencode"},qwen:{buildArgs({model:D}){let u=["--yolo"];if(D&&D!=="default")u.push("--model",D);return u.push("-"),u},name:"Qwen Code"}};BB=new Map});import{createHash as ZK}from"crypto";import{mkdir as CB,readdir as oK,readFile as HB,rm as dK,stat as yK,writeFile as lK}from"fs/promises";import UA from"path";class J0{#D;constructor(D){this.#D=UA.resolve(D)}get root(){return this.#D}async ensureRoot(){await CB(this.#D,{recursive:!0})}resolve(D){let u=UA.resolve(this.#D,D),r=`${this.#D}${UA.sep}`;if(u!==this.#D&&!u.startsWith(r))throw Error(`Path escapes workspace root: ${D}`);return u}async write(D){let u=this.resolve(D.path);return await CB(UA.dirname(u),{recursive:!0}),await lK(u,D.content),this.describe(D.path)}async read(D){return HB(this.resolve(D),"utf8")}async delete(D){await dK(this.resolve(D),{force:!0,recursive:!0})}async describe(D){let u=this.resolve(D),r=await yK(u),A=r.isDirectory()?"directory":"file",f=A==="file"?await HB(u):null;return{path:D,kind:A,size:A==="file"?r.size:null,mtime:Math.trunc(r.mtimeMs),hash:f?ZK("sha256").update(f).digest("hex"):null}}async list(D=""){await this.ensureRoot();let u=this.resolve(D),r=await oK(u);return Promise.all(r.map((A)=>this.describe(UA.posix.join(D,A))))}}var D$=()=>{};import{createHash as cK}from"crypto";import{mkdir as nB,readdir as tK,readFile as xK,stat as mK,writeFile as UB}from"fs/promises";import Ju from"path";async function YB(D){let u=Ju.resolve(D.sourceRoot),r=Ju.resolve(D.workspaceRoot),A=await aK(u),f=[];await nB(Ju.join(r,".aiworker"),{recursive:!0});for(let F of A){let E=`${D.appId}-${F.skillId}`,$=[Ju.posix.join(".agents","skills",E,u$),Ju.posix.join(".claude","skills",E,u$)];for(let g of $){let R=Ju.join(r,...g.split("/"));await nB(Ju.dirname(R),{recursive:!0}),await UB(R,F.content,"utf8")}f.push({projectionId:E,sha256:cK("sha256").update(F.content).digest("hex"),skillId:F.skillId,source:Ju.relative(u,F.sourcePath).split(Ju.sep).join("/"),targets:$})}let w={appId:D.appId,generatedAt:D.now,skills:f,sourceRoot:u};return await UB(Ju.join(r,...XB.split("/")),`${JSON.stringify(w,null,2)}
1504
- `,"utf8"),w}function MB(){return XB}async function aK(D){let u=Ju.join(D,"skills"),r=await eK(u),A=[];for(let f of r){if(!f.isDirectory()||!pK.test(f.name))continue;let w=Ju.join(u,f.name,u$);if(!await Dh(w))continue;A.push({content:await xK(w,"utf8"),skillId:f.name,sourcePath:w})}return A.sort((f,w)=>f.skillId.localeCompare(w.skillId))}async function eK(D){try{return await tK(D,{withFileTypes:!0})}catch(u){if(OB(u))return[];throw u}}async function Dh(D){try{return(await mK(D)).isFile()}catch(u){if(OB(u))return!1;throw u}}function OB(D){return typeof D==="object"&&D!==null&&"code"in D&&D.code==="ENOENT"}var pK,u$="SKILL.md",XB;var PB=W(()=>{pK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,XB=Ju.posix.join(".aiworker","native-skill-projections.json")});import{spawnSync as VB}from"child_process";import{mkdir as W0,readFile as uh,stat as rh,writeFile as vf}from"fs/promises";import eD from"path";async function KB(D){let u=eD.resolve(D.rootPath);return await W0(u,{recursive:!0}),await W0(eD.join(u,"artifacts"),{recursive:!0}),await W0(eD.join(u,r$),{recursive:!0}),await W0(eD.join(u,"evidence","descriptors"),{recursive:!0}),await W0(eD.join(u,"evidence","raw"),{recursive:!0}),await W0(eD.join(u,".aiworker","sessions"),{recursive:!0}),await iB(eD.join(u,v2),wh(D.name)),await iB(eD.join(u,"evidence","README.md"),$h()),await gh(u),{git:_h(u,[v2,".gitignore","evidence/README.md"]),profilePath:v2}}async function hB(D){if(D.verdict!=="pass"&&D.verdict!=="warn")throw Error("Only pass or warn reviews can promote a profile revision.");let u=eD.resolve(D.workspaceRoot),r=eD.posix.join(r$,`${D.reviewId}.md`);await W0(eD.join(u,r$),{recursive:!0}),await vf(kB(u,v2),Sh(D.profileMarkdown),"utf8"),await vf(kB(u,r),Eh(D),"utf8");let A=NB(u,[v2,D.artifactPath,r],`profile: approve ${D.workspaceName} revision`),f=D.tagName?Rh(u,D.tagName,`Approved profile version for ${D.workspaceName}`):null;return{git:A,profilePath:v2,reviewPath:r,tag:f}}function wh(D){return[`# ${D}`,"","> Canonical accepted profile for this Soul workspace. Session outputs remain proposals until review.","","## Current Profile Summary","","No approved profile revision yet.","","## Evidence And Review","","- Proposed changes live in `artifacts/`.","- Human review records live in `reviews/`.","- Evidence descriptors live in `evidence/descriptors/`.","","## Revision Notes","","Approve a profile revision to update this README.",""].join(`
1505
- `)}function $h(){return["# Evidence","","Store source descriptors in `descriptors/`. Keep raw sensitive evidence in `raw/`, which is ignored by the profile git ledger by default.",""].join(`
1506
- `)}function Eh(D){return[`# Profile Review ${D.reviewId}`,"",`- Verdict: ${D.verdict}`,`- Artifact: ${D.artifactTitle} (${D.artifactPath})`,`- Reviewed At: ${D.now}`,"","## Findings",IB(D.findingsJson),"","## Risks",IB(D.risksJson),""].join(`
1507
- `)}async function iB(D,u){if(await Bh(D))return;await W0(eD.dirname(D),{recursive:!0}),await vf(D,u,"utf8")}async function gh(D){let u=eD.join(D,".gitignore"),r=await Jh(u),A=Ah.filter((w)=>!r.split(/\r?\n/).includes(w));if(A.length===0)return;let f=[r.trimEnd(),r.trim().length>0?"":null,"# AIWorker profile ledger",...A,""].filter((w)=>w!==null).join(`
1508
- `);await vf(u,f,"utf8")}function _h(D,u){if(!f$())return{message:"git is not available on PATH.",status:"unavailable"};if(!F$(D)){let r=jr(D,["init"]);if(r.status!==0)return{message:r.stderr||r.stdout||"git init failed.",status:"failed"}}return QB(D),NB(D,u,"profile: initialize workspace")}function NB(D,u,r){if(!f$())return{message:"git is not available on PATH.",status:"unavailable"};if(!F$(D))return{message:"workspace is not a git repository.",status:"failed"};QB(D);let A=jr(D,["add","--",...u]);if(A.status!==0)return{message:A.stderr||A.stdout||"git add failed.",status:"failed"};if(jr(D,["diff","--cached","--quiet"]).status===0)return{hash:A$(D),status:"skipped"};let w=jr(D,["commit","-m",r]);if(w.status!==0)return{message:w.stderr||w.stdout||"git commit failed.",status:"failed"};return{hash:A$(D),status:"created"}}function Rh(D,u,r){if(!f$())return{message:"git is not available on PATH.",status:"unavailable"};if(!F$(D))return{message:"workspace is not a git repository.",status:"failed"};let A=jr(D,["tag","-a",u,"-m",r]);if(A.status!==0)return{message:A.stderr||A.stdout||"git tag failed.",status:"failed"};return{hash:A$(D),status:"created"}}function QB(D){jr(D,["config","user.name",fh]),jr(D,["config","user.email",Fh])}function A$(D){let u=jr(D,["rev-parse","--verify","HEAD"]);return u.status===0?u.stdout.trim():void 0}function f$(){return VB("git",["--version"],{encoding:"utf8"}).status===0}function F$(D){return jr(D,["rev-parse","--is-inside-work-tree"]).status===0}function jr(D,u){let r=VB("git",u,{cwd:D,encoding:"utf8"});return{status:r.status,stderr:r.stderr??"",stdout:r.stdout??""}}function kB(D,u){let r=eD.resolve(D,u),A=`${D}${eD.sep}`;if(r!==D&&!r.startsWith(A))throw Error(`Path escapes workspace root: ${u}`);return r}function Sh(D){return`${D.trimEnd()}
1509
- `}function IB(D){if(D.length===0)return"- None.";return D.map((u)=>`- ${JSON.stringify(u)}`).join(`
1510
- `)}async function Bh(D){try{return await rh(D),!0}catch(u){if(LB(u))return!1;throw u}}async function Jh(D){try{return await uh(D,"utf8")}catch(u){if(LB(u))return"";throw u}}function LB(D){return typeof D==="object"&&D!==null&&"code"in D&&D.code==="ENOENT"}var v2="README.md",r$="reviews",Ah,fh="AIWorker Profile Ledger",Fh="aiworker@local";var qB=W(()=>{Ah=[".aiworker/sessions/",".aiworker/native-skill-projections.json",".agents/skills/aiworker-*",".claude/skills/aiworker-*","evidence/raw/"]});import{randomUUID as Tr}from"crypto";import{mkdir as sf,writeFile as bB}from"fs/promises";import G0 from"path";class $${#D;#r;#A;#F;#u;bus=new Tf;constructor(D){this.#D=D.worker,this.#r=G0.resolve(D.workspacesRoot),this.#A=D.executor??aw(),this.#F=D.nativeSkillSource??null,this.#u=D.now??(()=>new Date().toISOString())}get workerId(){return this.#D.id}get workspacesRoot(){return this.#r}async init(){await sf(this.#r,{recursive:!0});let D=r2({id:this.#D.id,soulId:this.#D.soulId,name:this.#D.name,defaultEngineId:this.#D.defaultEngineId??null,metadataJson:this.#D.metadata??{},at:this.#u()});return await this.repairWorkspaceLayouts(),D}async createWorkspace(D){this.requireWorker();let u=Tr(),r=G0.join(this.#r,u),A=await this.prepareWorkspaceLayout({name:D.name,rootPath:r});return Z4({id:u,workerId:this.workerId,name:D.name,rootPath:r,type:D.type??"workspace",sourcePointersJson:D.sourcePointers??[],metadataJson:{...D.metadata??{},nativeSkillProjection:A.nativeSkills?{projectionCount:A.nativeSkills.skills.length,projectionManifestPath:MB()}:null,profileLedger:{git:A.profile.git,profilePath:A.profile.profilePath}},at:this.#u()})}async createSession(D){let u=this.requireWorkspace(D.workspaceId),r=o4({id:Tr(),workerId:this.workerId,workspaceId:u.id,capabilityTemplateId:D.capabilityTemplateId,title:D.title,context:D.context??"",status:"active",metadataJson:D.metadata??{},startedAt:this.#u(),at:this.#u()});return await this.materializeSessionContext(u,r,D.metadata??{}),this.appendEvent(r.id,"status",{status:"active"}),this.bus.emit({kind:"session",workspaceId:u.id,sessionId:r.id,payload:{status:"active"},at:this.#u()}),r}async startTurn(D){let u=this.requireSession(D.sessionId),r=this.requireWorkspace(u.workspaceId),A=l4(u.id),f=y4({id:Tr(),sessionId:u.id,seq:A,input:D.input,status:"running",metadataJson:D.metadata??{},at:this.#u()}),w=this.buildInvocationPrompt(u,f,D.metadata??{}),F=c4({id:Tr(),sessionId:u.id,turnId:f.id,seq:x4(u.id),engineId:D.engineId,engineCommand:D.engineCommand??null,prompt:w,status:"running",metadataJson:D.metadata??{},startedAt:this.#u(),at:this.#u()});this.appendEvent(u.id,"status",{status:"running",turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"running",turn:f},at:this.#u()});try{let E=await this.ensureInvocationRoot(r,u,F),$=await this.#A.invoke({engineCommand:D.engineCommand??null,engineId:D.engineId,invocationId:F.id,invocationRoot:E,onEvent:(J)=>this.appendAgentEvent(u.id,J,f.id,F.id),prompt:w,sessionId:u.id,turnId:f.id,workspaceId:r.id,workspaceRoot:r.rootPath,metadata:{...u.metadataJson??{},...D.metadata??{},capabilityTemplateId:u.capabilityTemplateId,sessionId:u.id,turnId:f.id,workerId:this.workerId,workspaceId:r.id}}),g=await this.captureResult(r,u,f,F,$,D.metadata??{}),R=LF({id:F.id,status:"succeeded",summary:$.summary,metadataJson:{...D.metadata??{},...$.metadata??{}},finishedAt:this.#u(),at:this.#u()}),S=QF({id:f.id,status:"succeeded",response:$.summary,at:this.#u()}),B=NF({id:u.id,status:"active",at:this.#u()});return this.appendEvent(u.id,"status",{status:"succeeded",turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"succeeded",turn:S},at:this.#u()}),{session:B,turn:S,invocation:R,events:_r(u.id),...g}}catch(E){let $=E instanceof Error?E.message:String(E),g=LF({id:F.id,status:"failed",error:$,finishedAt:this.#u(),at:this.#u()}),R=QF({id:f.id,status:"failed",error:$,at:this.#u()}),S=NF({id:u.id,status:"failed",endedAt:this.#u(),at:this.#u()});return this.appendEvent(u.id,"error",{message:$,turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"failed",turn:R},at:this.#u()}),{session:S,turn:R,invocation:g,events:_r(u.id),files:[],artifacts:[],review:null,lessons:[]}}}snapshot(){let D=this.requireWorker(),u=nu(D.id),r=new Set(u.map((F)=>F.id)),A=tr().filter((F)=>r.has(F.workspaceId)),f=new Set(A.map((F)=>F.id)),w=gr().filter((F)=>f.has(F.sessionId));return{worker:D,workspaces:u,sessions:A,turns:w,invocations:t4().filter((F)=>f.has(F.sessionId)),files:bu().filter((F)=>r.has(F.workspaceId)),artifacts:Rr().filter((F)=>r.has(F.workspaceId)),reviews:A2().filter((F)=>r.has(F.workspaceId)),lessons:f2().filter((F)=>r.has(F.workspaceId)),events:_r().filter((F)=>f.has(F.sessionId))}}files(D){let u=this.requireWorkspace(D);return new J0(u.rootPath)}async promoteProfileRevision(D){let u=this.requireWorkspace(D.workspaceId),r=xr(D.artifactId);if(!r||r.workspaceId!==u.id)throw Error(`Artifact not found for workspace ${u.id}: ${D.artifactId}`);let A=D.verdict??"pass",f=Tr(),F=await new J0(u.rootPath).read(r.path),E=this.#u(),$=await hB({artifactPath:r.path,artifactTitle:r.title,findingsJson:D.findingsJson??[{message:"Profile revision approved."}],now:E,profileMarkdown:D.profileMarkdown??F,reviewId:f,risksJson:D.risksJson??[],tagName:D.tagName,verdict:A,workspaceName:u.name,workspaceRoot:u.rootPath}),g=i0({id:f,workspaceId:u.id,sessionId:r.sessionId,turnId:r.turnId,artifactId:r.id,verdict:A,findingsJson:D.findingsJson??[{message:"Profile revision approved."}],risksJson:D.risksJson??[],at:E});if(g.sessionId)this.appendEvent(g.sessionId,"review",{reviewId:g.id,verdict:g.verdict,profilePath:$.profilePath},g.turnId,null),this.bus.emit({kind:"review",workspaceId:u.id,sessionId:g.sessionId,turnId:g.turnId??void 0,payload:{reviewId:g.id,profilePath:$.profilePath},at:this.#u()});return{...$,review:g}}dispose(){return}async captureResult(D,u,r,A,f,w){let F=new J0(D.rootPath),E=[],$=[];for(let S of f.artifacts??[]){let B=await F.write({path:S.path,content:S.content}),J=C1({id:Tr(),workspaceId:D.id,path:B.path,kind:"generated",size:B.size,mtime:B.mtime,hash:B.hash,source:"session",at:this.#u()});E.push(J);let H=a4({id:Tr(),workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,path:S.path,kind:S.kind??"file",title:S.title??S.path,metadataJson:{capabilityTemplateId:u.capabilityTemplateId,fileId:J.id,outputKind:S.kind??w.outputKind,...typeof w.soulAppId==="string"?{soulAppId:w.soulAppId}:{},workerId:this.workerId},at:this.#u()});$.push(H),this.appendEvent(u.id,"artifact",{artifactId:H.id,path:H.path},r.id,A.id),this.bus.emit({kind:"artifact",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{artifactId:H.id},at:this.#u()})}let g=f.review?i0({id:Tr(),workspaceId:D.id,sessionId:u.id,turnId:r.id,artifactId:$[0]?.id??null,verdict:f.review.verdict??"needs_review",findingsJson:f.review.findings??[],risksJson:f.review.risks??[],at:this.#u()}):null;if(g)this.appendEvent(u.id,"review",{reviewId:g.id,verdict:g.verdict},r.id,A.id),this.bus.emit({kind:"review",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{reviewId:g.id},at:this.#u()});let R=(f.lessons??[]).map((S)=>mr({id:Tr(),workspaceId:D.id,sourceReviewId:g?.id??null,statement:S.statement,evidenceJson:S.evidence??[],at:this.#u()}));for(let S of R)this.appendEvent(u.id,"lesson",{lessonId:S.id},r.id,A.id),this.bus.emit({kind:"lesson",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{lessonId:S.id},at:this.#u()});return{files:E,artifacts:$,review:g,lessons:R}}appendAgentEvent(D,u,r,A){if(u.kind==="text")return this.appendEvent(D,"assistant_delta",{agentEvent:u,delta:u.text,text:u.text},r,A);if(u.kind==="thinking"||u.kind==="log"||u.kind==="raw")return this.appendEvent(D,"log",{agentEvent:u},r,A);if(u.kind==="tool_use"||u.kind==="tool_result")return this.appendEvent(D,"tool",{agentEvent:u},r,A);return this.appendEvent(D,u.kind==="status"||u.kind==="usage"?"status":"log",{agentEvent:u},r,A)}appendEvent(D,u,r,A,f){let w=m4({sessionId:D,turnId:A??null,invocationId:f??null,seq:p4(D),type:u,payloadJson:r,at:this.#u()}),F=fu(D);if(F)this.bus.emit({at:w.createdAt,invocationId:f??void 0,kind:"event",payload:{event:w},sessionId:D,turnId:A??void 0,workspaceId:F.workspaceId});return w}buildInvocationPrompt(D,u,r){let A=[`Soul worker: ${this.#D.name}`,`Soul id: ${this.#D.soulId}`,`Workspace session: ${D.title}`,`Capability template: ${D.capabilityTemplateId}`,`Output kind: ${w$(r.outputKind,"business-artifact")}`,"","Workspace profile ledger:","- README.md is the accepted profile for this workspace.",`- Proposed changes should be written under artifacts/${D.id}/ before review.`,"- Human review records live under reviews/.","- Native skills may be projected under .agents/skills and .claude/skills when the Soul App provides them.","","Session context:",D.context||"(no prior context)","","Turn request:",u.input.trim()],f=Array.isArray(r.inputHints)?r.inputHints:[],w=Array.isArray(r.reviewRubric)?r.reviewRubric:[];if(f.length>0)A.push("","Input hints:",...f.map((F)=>`- ${String(F)}`));if(w.length>0)A.push("","Review rubric:",...w.map((F)=>`- ${String(F)}`));return A.join(`
1511
- `)}async materializeSessionContext(D,u,r){let A=new J0(D.rootPath),f=G0.posix.join(".aiworker","sessions",u.id);await sf(A.resolve(G0.posix.join(f,"context","capability")),{recursive:!0}),await bB(A.resolve(G0.posix.join(f,"context","active-context.md")),this.buildActiveContext(u,r),"utf8"),await bB(A.resolve(G0.posix.join(f,"context","capability","SKILL.md")),this.buildCapabilitySkill(u,r),"utf8"),await sf(A.resolve(G0.posix.join(f,"invocations")),{recursive:!0})}buildActiveContext(D,u){return[`# ${D.title}`,"",`- Worker: ${this.#D.name}`,`- Soul: ${this.#D.soulId}`,`- Capability template: ${D.capabilityTemplateId}`,`- Output kind: ${w$(u.outputKind,"business-artifact")}`,"- Accepted profile: README.md",`- Proposed change directory: artifacts/${D.id}/`,"- Native skill projections: .agents/skills and .claude/skills when available","","## Context",D.context||"No context supplied."].join(`
1512
- `)}buildCapabilitySkill(D,u){let r=w$(u.skillName,D.capabilityTemplateId),A=Array.isArray(u.reviewRubric)?u.reviewRubric.map(String):[];return[`# ${r}`,"","Use this capability in the current AIWorker session only.","","## Review Rubric",...A.length>0?A.map((f)=>`- ${f}`):["- Separate facts, assumptions, risks, and next actions."]].join(`
1513
- `)}async ensureInvocationRoot(D,u,r){let A=new J0(D.rootPath),f=String(r.seq).padStart(4,"0"),w=A.resolve(G0.posix.join(".aiworker","sessions",u.id,"invocations",f));return await sf(w,{recursive:!0}),w}requireWorker(){let D=PD(this.workerId);if(!D)throw Error("Local Soul worker is not initialized.");return D}requireWorkspace(D){let u=pD(D);if(!u||u.workerId!==this.workerId)throw Error(`Workspace not found for worker ${this.workerId}: ${D}`);return u}requireSession(D){let u=fu(D);if(!u||u.workerId!==this.workerId)throw Error(`Session not found for worker ${this.workerId}: ${D}`);return u}async repairWorkspaceLayouts(){for(let D of nu(this.workerId))await this.prepareWorkspaceLayout({name:D.name,rootPath:D.rootPath})}async prepareWorkspaceLayout(D){let u=await KB({name:D.name,now:this.#u(),rootPath:D.rootPath});return{nativeSkills:this.#F?await YB({appId:this.#F.appId,now:this.#u(),sourceRoot:this.#F.sourceRoot,workspaceRoot:D.rootPath}):null,profile:u}}}function E$(D){return new $$(D)}function w$(D,u){return typeof D==="string"&&D.trim().length>0?D.trim():u}var g$=W(()=>{Sr();ew();D$();PB();qB()});import zB from"path";function XA(D){return new _$(D)}class _${options;constructor(D){this.options=D}listCatalog(){return j2()}listApps(){return bf()}getApp(D){return Ou(D)}reviewAppSecurity(D){let u=Ou(D);if(!u)throw Error(`Soul App not found: ${D}`);return xw(u,this.registryContext())}async installAppFromPath(D){return JA(D,this.registryContext())}installAppManifest(D){return qf(D,this.registryContext())}enableApp(D){return WA(D,this.registryContext())}disableApp(D){return GA(D,this.registryContext())}healthcheckApp(D){return Zw(D,this.registryContext())}async bootstrapOfficialSoulApps(){let D=await lw({...this.registryContext(),officialAppsRoot:this.options.officialAppsRoot}),u=cw(this.options.now?.());return{catalog:this.listCatalog(),legacyMetadataDiscard:u,results:D,scope:"official",status:D.some((r)=>r.action==="error")?"fail":"pass"}}listSouls(){return this.listCatalog().souls}findSoul(D){return CA(D)}requireAvailableSoul(D){let u=Zf(D,"soulId"),r=CA(u);if(!r||r.status!=="available")throw yu.badRequest(`Available Soul not found: ${u}`,"SOUL_NOT_AVAILABLE");return r}listCapabilityTemplates(D){return D?jf(D):this.listCatalog().templates}listCapabilityTemplatesForWorker(D){let u=this.requireWorker(D);return jf(u.soulId)}requireCapabilityTemplateForWorker(D,u){let r=this.requireWorker(D),A=Zf(u,"capabilityTemplateId"),f=zf(A);if(!f||f.soulId!==r.soulId)throw yu.badRequest(`Template ${A} does not belong to worker ${D}.`,"TEMPLATE_NOT_AVAILABLE");return f}async createSoulWorker(D){let u=this.requireAvailableSoul(D.soulId),r=Zf(D.name,"name"),A=D.id?Zf(D.id,"id"):k9();if(PD(A))throw new yu("CONFLICT",409,`Worker already exists: ${A}`);let f=r2({id:A,soulId:u.id,name:r,defaultEngineId:D.defaultEngineId??"codex",metadataJson:{defaultTemplates:[...u.defaultTemplates],description:u.description,domain:u.domain,soulAppId:Ou(u.id)?.appId??null,...D.metadata??{}}}),w=this.createRuntimeForWorker(f);return await w.init(),{runtime:w,snapshot:w.snapshot(),worker:f}}createRuntimeForWorker(D){return E$({worker:{id:D.id,soulId:D.soulId,name:D.name,defaultEngineId:D.defaultEngineId,metadata:D.metadataJson},executor:this.options.executor,nativeSkillSource:this.nativeSkillSourceForWorker(D),now:this.options.now,workspacesRoot:zB.join(this.options.workersRoot,D.id,"workspaces")})}enrichTemplateMetadata(D,u,r){let A=PD(D),f=A?CA(A.soulId):null,w=zf(u);if(!A||!f||!w)return r;return{...r,capabilityTemplateId:w.id,inputHints:w.inputHints,outputKind:w.outputKind,reviewRubric:w.reviewRubric,skillName:w.name,soulAppId:Ou(f.id)?.appId??null,soulName:f.name,workerId:A.id}}registryContext(){return{now:this.options.now,...this.options.registryContext?.()??{}}}nativeSkillSourceForWorker(D){let u=Ou(D.soulId);if(!u||u.status!=="enabled"||u.sourceKind!=="manifest-path")return null;return{appId:u.appId,sourceRoot:zB.dirname(u.sourceRef)}}requireWorker(D){let u=PD(D);if(!u)throw Error(`Worker not found: ${D}`);return u}}function Zf(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`Missing required field: ${u}`);return D.trim()}var jB=W(()=>{z2();Sr();tw();HA();g$()});function TB(D={}){let u=[{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!0,description:"Local app-scoped Soul App storage backed by worker.db metadata records.",enabled:!0,id:"storage.local-sqlite",kind:"storage",label:"Local SQLite storage",local:!0,status:"active"},{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!1,description:"Future app-scoped object storage provider for S3-compatible buckets.",enabled:!1,id:"storage.s3",kind:"storage",label:"S3 bucket storage",local:!1,notes:["Planned provider metadata only; no cloud SDK is loaded by the local Host."],status:"planned"},{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!1,description:"Future app-scoped object storage provider for Google Cloud Storage buckets.",enabled:!1,id:"storage.gcp-bucket",kind:"storage",label:"GCP bucket storage",local:!1,notes:["Planned provider metadata only; no cloud SDK is loaded by the local Host."],status:"planned"},{appScoped:!0,capabilities:["audit.read","audit.write"],configured:!0,description:"Local Host audit ledger for broker decisions and platform actions.",enabled:!0,id:"audit.local-sqlite",kind:"audit",label:"Local SQLite audit ledger",local:!0,status:"active"},{appScoped:!0,capabilities:["secret.reference"],configured:!1,description:"Future secret reference resolver for app-scoped broker grants.",enabled:!1,id:"secret.vault-ref",kind:"secret",label:"Vault secret references",local:!1,notes:["Planned provider metadata only; registry never returns raw secret values."],status:"planned"},...(D.connectors??[]).map(Wh)];return{providers:u,summary:{activeCount:u.filter((r)=>r.status==="active").length,configuredCount:u.filter((r)=>r.configured).length,plannedCount:u.filter((r)=>r.status==="planned").length,providerCount:u.length}}}function Wh(D){let u=D.status==="configured",r=u?D.enabled?"active":"disabled":"not_configured";return{appScoped:!0,capabilities:["connector.read"],configured:u,description:`Host connector broker metadata for ${D.name}.`,enabled:D.enabled,id:`connector.${D.id}`,kind:"connector",label:D.name,local:!1,status:r}}function ZB(D,u,r,A=new Date().toISOString()){let f={appId:D,artifactId:r.artifactId??null,authority:"soul-app",cache:{freshness:"non-authoritative"},id:u,kind:r.kind,reference:r.reference?Ch(r.reference):null,reviewId:r.reviewId??null,sessionId:r.sessionId??null,summary:r.summary??null,title:r.title,updatedAt:A,workspaceId:r.workspaceId??null};return sB.set(Gh(D,u),f),f}function oB(D,u){let r=vB(u),A=[...sB.values()].filter((f)=>f.appId===D).filter((f)=>!r||vB(Hh(f)).includes(r));return{appId:D,authority:"soul-app",items:A,query:u}}function Gh(D,u){return`${D}:${u}`}function Ch(D){return{id:D.id,type:D.type,...D.url?{url:D.url}:{}}}function Hh(D){return[D.id,D.kind,D.title,D.summary,D.reference?.id,D.reference?.type].filter(Boolean).join(`
1514
- `)}function vB(D){return D.trim().toLowerCase()}var sB;var dB=W(()=>{sB=new Map});function R$(){return{get(D,u){return J8(D,u)},list(D){return uE(D)},put(D){return DE(D)}}}var S$=W(()=>{Sr()});import{randomUUID as yB}from"crypto";function Eu(D){let u=D.storageProvider??R$();return{artifacts:{list(r=D.workspaceId){let A=Xr(D,"artifact","read","*");if(Yr(D,A,"artifact","read",r??"*",{workspaceId:r}),!A.allowed)return Mr(A);return Rr(r)}},audit:{list(){return AE(D.appId)}},connectors:{readEvidence(r,A){let f=Xr(D,"connector","read",r);if(Yr(D,f,"connector","read",r,{query:A}),!f.allowed)return Mr(f);return{appId:D.appId,connectorId:r,query:A,records:[{appId:D.appId,connectorId:r,query:A,redacted:!0,source:"host-connector-broker"}],redacted:!0}}},engine:{createInvocation(r){let A=ND("engine_owned_by_host","Soul Apps cannot create raw engine invocations; Host owns engine scheduling and audit.");return Yr(D,A,"engine","create","invocation",{promptLength:r.prompt.length}),Mr(A)}},memory:{propose(r){let A=Xr(D,"memory","propose",D.appId);if(Yr(D,A,"memory","propose",D.appId,{sourceReviewId:r.sourceReviewId??null,workspaceId:r.workspaceId}),!A.allowed)return Mr(A);return mr({evidenceJson:[...r.evidenceJson??[],{appId:D.appId,namespace:D.appId,source:"soul-app-broker"}],id:`lesson_${yB()}`,sourceReviewId:r.sourceReviewId??null,statement:r.statement,status:"proposed",workspaceId:r.workspaceId})}},permissions:{decide(r,A,f){return Xr(D,r,A,f)},list(){return B$(D)?.manifest.permissions??[]}},providers:{list(){return TB({connectors:D.connectorProviders})}},reviews:{create(r){let A=Xr(D,"review","create","review");if(Yr(D,A,"review","create",r.artifactId??"review",{artifactId:r.artifactId??null,workspaceId:r.workspaceId}),!A.allowed)return Mr(A);return i0({artifactId:r.artifactId??null,findingsJson:r.findingsJson??[],id:`review_${yB()}`,risksJson:r.risksJson??[],sessionId:r.sessionId??D.sessionId??null,turnId:r.turnId??null,verdict:r.verdict??"needs_review",workspaceId:r.workspaceId})}},search:{query(r){let A=Xr(D,"search","read",D.appId);if(Yr(D,A,"search","read",D.appId,{query:r}),!A.allowed)return Mr(A);return oB(D.appId,r)},upsert(r,A){let f=Xr(D,"search","write",D.appId);if(Yr(D,f,"search","write",r,{artifactId:A.artifactId??null,kind:A.kind,reviewId:A.reviewId??null,sessionId:A.sessionId??null,workspaceId:A.workspaceId??null}),!f.allowed)return Mr(f);return ZB(D.appId,r,A,D.now?.())}},storage:{get(r){let A=Xr(D,"storage","read",D.appId);if(Yr(D,A,"storage","read",r,{key:r}),!A.allowed)return Mr(A);return u.get(D.appId,r)},list(){let r=Xr(D,"storage","read",D.appId);if(Yr(D,r,"storage","read",D.appId,{}),!r.allowed)return Mr(r);return u.list(D.appId)},put(r,A,f={}){let w=f.namespace??D.appId,F=B$(D),E=F&&w!==F.manifest.storage.namespace?ND("permission_denied",`Requested storage namespace ${w} does not match app namespace ${F.manifest.storage.namespace}.`):Xr(D,"storage","write",w);if(Yr(D,E,"storage","write",w,{key:r,namespace:w}),!E.allowed)return Mr(E);return u.put({appId:D.appId,key:r,namespace:w,operatorId:D.operatorId??null,sessionId:D.sessionId??null,valueJson:A,workerId:D.workerId??null,workspaceId:D.workspaceId??null,at:D.now?.()})}}}}function Xr(D,u,r,A){let f=B$(D);if(!f)return ND("app_not_found",`Soul App is not installed: ${D.appId}`);if(f.status!=="enabled")return ND("app_disabled",`Soul App is not enabled: ${D.appId}`);let w=nh(D,f);if(w)return w;if(u==="engine")return ND("engine_owned_by_host","Soul Apps cannot create raw engine invocations; Host owns engine scheduling and audit.");if(u==="connector"&&!(D.enabledConnectorIds??[]).includes(A))return ND("connector_not_enabled",`Connector is not enabled for brokered access: ${A}`);if(!f.manifest.permissions.some((E)=>E.kind===u&&E.action===r&&Uh(f,E,A)))return ND("permission_denied",`Soul App manifest does not declare ${u}:${A}:${r}.`);return{allowed:!0,code:"allowed",reason:"Permission is declared in the Soul App manifest and enforced by Host broker."}}function nh(D,u){if(!D.workerId&&!D.workspaceId&&!D.sessionId)return null;let r=D.workerId?PD(D.workerId):null;if(D.workerId&&!r)return ND("scope_not_found",`Worker scope was not found: ${D.workerId}`);if(r&&r.soulId!==u.appId)return ND("scope_mismatch",`Worker ${r.id} belongs to ${r.soulId}, not ${u.appId}.`);let A=D.workspaceId?pD(D.workspaceId):null;if(D.workspaceId&&!A)return ND("scope_not_found",`Workspace scope was not found: ${D.workspaceId}`);if(A&&D.workerId&&A.workerId!==D.workerId)return ND("scope_mismatch",`Workspace ${A.id} belongs to worker ${A.workerId}, not ${D.workerId}.`);if(A&&!D.workerId){let w=PD(A.workerId);if(!w)return ND("scope_not_found",`Workspace worker was not found: ${A.workerId}`);if(w.soulId!==u.appId)return ND("scope_mismatch",`Workspace ${A.id} belongs to ${w.soulId}, not ${u.appId}.`)}let f=D.sessionId?fu(D.sessionId):null;if(D.sessionId&&!f)return ND("scope_not_found",`Session scope was not found: ${D.sessionId}`);if(f&&D.workerId&&f.workerId!==D.workerId)return ND("scope_mismatch",`Session ${f.id} belongs to worker ${f.workerId}, not ${D.workerId}.`);if(f&&D.workspaceId&&f.workspaceId!==D.workspaceId)return ND("scope_mismatch",`Session ${f.id} belongs to workspace ${f.workspaceId}, not ${D.workspaceId}.`);if(f&&!D.workerId){let w=PD(f.workerId);if(!w)return ND("scope_not_found",`Session worker was not found: ${f.workerId}`);if(w.soulId!==u.appId)return ND("scope_mismatch",`Session ${f.id} belongs to ${w.soulId}, not ${u.appId}.`)}return null}function Uh(D,u,r){if(u.target===r)return!0;if(u.kind==="review"&&u.action==="create")return!0;if(u.kind==="artifact"&&D.manifest.artifactTypes.some((A)=>A.id===r))return!0;if(u.kind==="memory"&&r===D.manifest.memory.namespace)return!0;return!1}function Yr(D,u,r,A,f,w){rE({action:A,appId:D.appId,decision:u.allowed?"allowed":"denied",operatorId:D.operatorId??null,reason:u.reason,requestJson:w,sessionId:D.sessionId??null,target:f,targetKind:r,workerId:D.workerId??null,workspaceId:D.workspaceId??null,at:D.now?.()})}function B$(D){return Ou(D.appId)}function ND(D,u){return{allowed:!1,code:D,reason:u}}function Mr(D){return{decision:D.allowed?ND("permission_denied","Broker request was denied."):D}}var lB=W(()=>{Sr();HA();dB();S$()});var J$=W(()=>{nE();XE();jB();lB();tw();HA();S$();ew();D$();g$()});function H$(D){if(D===null||typeof D!=="object")return!1;let u=Object.getPrototypeOf(D);if(u!==null&&u!==Object.prototype&&Object.getPrototypeOf(u)!==null)return!1;if(Symbol.iterator in D)return!1;if(Symbol.toStringTag in D)return Object.prototype.toString.call(D)==="[object Module]";return!0}function Y$(D,u,r=".",A){if(!H$(u))return Y$(D,{},r,A);let f=Object.assign({},u);for(let w in D){if(w==="__proto__"||w==="constructor")continue;let F=D[w];if(F===null||F===void 0)continue;if(A&&A(f,w,F,r))continue;if(Array.isArray(F)&&Array.isArray(f[w]))f[w]=[...F,...f[w]];else if(H$(F)&&H$(f[w]))f[w]=Y$(F,f[w],(r?`${r}.`:"")+w.toString(),A);else f[w]=F}return f}function Qh(D){return(...u)=>u.reduce((r,A)=>Y$(r,A,"",D),{})}function qh(D){return Object.prototype.toString.call(D)==="[object Object]"}function bh(D){if(!qh(D))return!1;if(!D.message&&!D.args)return!1;if(D.stack)return!1;return!0}class vD{options;_lastLog;_mockFn;constructor(D={}){let u=D.types||X$;this.options=Lh({...D,defaults:{...D.defaults},level:U$(D.level,u),reporters:[...D.reporters||[]]},{types:X$,throttle:1000,throttleMin:5,formatOptions:{date:!0,colors:!1,compact:!0}});for(let r in u){let A={type:r,...this.options.defaults,...u[r]};this[r]=this._wrapLogFn(A),this[r].raw=this._wrapLogFn(A,!0)}if(this.options.mockFn)this.mockTypes();this._lastLog={}}get level(){return this.options.level}set level(D){this.options.level=U$(D,this.options.types,this.options.level)}prompt(D,u){if(!this.options.prompt)throw Error("prompt is not supported!");return this.options.prompt(D,u)}create(D){let u=new vD({...this.options,...D});if(this._mockFn)u.mockTypes(this._mockFn);return u}withDefaults(D){return this.create({...this.options,defaults:{...this.options.defaults,...D}})}withTag(D){return this.withDefaults({tag:this.options.defaults.tag?this.options.defaults.tag+":"+D:D})}addReporter(D){return this.options.reporters.push(D),this}removeReporter(D){if(D){let u=this.options.reporters.indexOf(D);if(u!==-1)return this.options.reporters.splice(u,1)}else this.options.reporters.splice(0);return this}setReporters(D){return this.options.reporters=Array.isArray(D)?D:[D],this}wrapAll(){this.wrapConsole(),this.wrapStd()}restoreAll(){this.restoreConsole(),this.restoreStd()}wrapConsole(){for(let D in this.options.types){if(!console["__"+D])console["__"+D]=console[D];console[D]=this[D].raw}}restoreConsole(){for(let D in this.options.types)if(console["__"+D])console[D]=console["__"+D],delete console["__"+D]}wrapStd(){this._wrapStream(this.options.stdout,"log"),this._wrapStream(this.options.stderr,"log")}_wrapStream(D,u){if(!D)return;if(!D.__write)D.__write=D.write;D.write=(r)=>{this[u].raw(String(r).trim())}}restoreStd(){this._restoreStream(this.options.stdout),this._restoreStream(this.options.stderr)}_restoreStream(D){if(!D)return;if(D.__write)D.write=D.__write,delete D.__write}pauseLogs(){n$=!0}resumeLogs(){n$=!1;let D=DJ.splice(0);for(let u of D)u[0]._logFn(u[1],u[2])}mockTypes(D){let u=D||this.options.mockFn;if(this._mockFn=u,typeof u!=="function")return;for(let r in this.options.types)this[r]=u(r,this.options.types[r])||this[r],this[r].raw=this[r]}_wrapLogFn(D,u){return(...r)=>{if(n$){DJ.push([this,D,r,u]);return}return this._logFn(D,r,u)}}_logFn(D,u,r){if((D.level||0)>this.level)return!1;let A={date:new Date,args:[],...D,level:U$(D.level,this.options.types)};if(!r&&u.length===1&&bh(u[0]))Object.assign(A,u[0]);else A.args=[...u];if(A.message)A.args.unshift(A.message),delete A.message;if(A.additional){if(!Array.isArray(A.additional))A.additional=A.additional.split(`
1497
+ `)}},flush(){let w=r.trim();if(r="",w)f(w)}}}function Dh(D,u,r){let A=nD(D);if(!A)return!1;let f=nD(A.part);if(A.type==="step_start")return u({label:"running",type:"status"}),!0;if(A.type==="text"){let w=fD(f?.text);if(w)return u({delta:w,type:"text_delta"}),!0}if(A.type==="tool_use"){let w=fD(f?.tool),F=fD(f?.callID);if(!w||!F)return!1;let E=nD(f?.state),$=`${fD(A.sessionID,"session")}:${F}`;if(!r.openCodeToolUses.has($))r.openCodeToolUses.add($),u({id:F,input:Eh(E?.input)??E?.input??null,name:w,type:"tool_use"});if(E?.status==="completed")u({content:W$(E.output),isError:!1,toolUseId:F,type:"tool_result"});return!0}if(A.type==="step_finish"){let w=nD(f?.tokens);if(w)return u({costUsd:uu(f?.cost),inputTokens:uu(w.input),outputTokens:uu(w.output),type:"usage"}),!0}return!1}function uh(D,u,r){let A=nD(D);if(!A)return!1;let f=fD(A.type);if(f==="thread.started")return u({label:"initializing",type:"status"}),!0;if(f==="turn.started")return u({label:"running",type:"status"}),!0;let w=nD(A.item);if(f==="item.started"&&w?.type==="command_execution"){if(!fD(w.id))return!1;return zn(w,u,r),!0}if(f==="item.completed"&&w?.type==="command_execution"){let F=fD(w.id);if(!F)return!1;return zn(w,u,r),u({content:W$(w.aggregated_output??w.output??""),isError:typeof w.exit_code==="number"?w.exit_code!==0:w.status==="failed",toolUseId:F,type:"tool_result"}),!0}if((f==="item.started"||f==="item.completed")&&w?.type==="file_change"){let F=Array.isArray(w.changes)?w.changes:[];for(let E of F){let $=nD(E),g=fD($?.path);if(!g)continue;u({action:fD($?.kind,"change"),path:g,status:fD(w.status)||(f==="item.started"?"in_progress":"completed"),type:"file_change"})}return F.length>0}if(f==="item.completed"&&w?.type==="agent_message"){let F=fD(w.text??w.content);if(F)return u({delta:F,type:"text_delta"}),!0}if(f==="turn.completed"){let F=nD(A.usage);if(F)return u({inputTokens:uu(F.input_tokens),outputTokens:uu(F.output_tokens),type:"usage"}),!0}return!1}function zn(D,u,r){let A=fD(D.id);if(!A||r.codexToolUses.has(A))return;r.codexToolUses.add(A),u({id:A,input:{command:fD(D.command)},name:"Bash",type:"tool_use"})}function rh(D,u){let r=nD(D);if(!r)return!1;if(r.type==="init")return u({detail:fD(r.model)||void 0,label:"initializing",type:"status"}),!0;if(r.type==="message"&&r.role==="assistant"){let A=fD(r.content);if(A)return u({delta:A,type:"text_delta"}),!0}if(r.type==="result"){let A=nD(r.stats);if(A)return u({durationMs:uu(A.duration_ms),inputTokens:uu(A.input_tokens),outputTokens:uu(A.output_tokens),type:"usage"}),!0}return!1}function Ah(D,u,r){let A=nD(D);if(!A)return!1;if(A.type==="system"){if(fD(A.subtype)==="init")return u({detail:fD(A.model)||void 0,label:"initializing",type:"status"}),!0}if(A.type==="assistant"){let f=fh(nD(A.message));if(!f)return!1;return Fh(f,u,r),!0}if(A.type==="result"){let f=nD(A.usage);if(f)return u({durationMs:uu(A.duration_ms),inputTokens:uu(f.inputTokens),outputTokens:uu(f.outputTokens),type:"usage"}),!0}return!1}function fh(D){return(Array.isArray(D?.content)?D.content:[]).map((r)=>nD(r)).filter((r)=>r?.type==="text").map((r)=>fD(r?.text)).join("")}function Fh(D,u,r){if(!r.cursorTextSoFar){r.cursorTextSoFar=D,u({delta:D,type:"text_delta"});return}if(D===r.cursorTextSoFar)return;if(D.startsWith(r.cursorTextSoFar)){let A=D.slice(r.cursorTextSoFar.length);if(r.cursorTextSoFar=D,A)u({delta:A,type:"text_delta"});return}r.cursorTextSoFar+=D,u({delta:D,type:"text_delta"})}function wh(D){let u="",r=new Map,A=new Set,f=null,w=($)=>`${f??"anon"}:${String($)}`,F=($)=>{let g=nD($);if(!g)return;if(g.type==="system"&&g.subtype==="init"){D({detail:fD(g.model)||void 0,label:"initializing",type:"status"});return}if(g.type==="system"&&g.subtype==="status"){D({label:fD(g.status,"working"),type:"status"});return}if(g.type==="stream_event"){$h(nD(g.event),{blockKey:w,blocks:r,currentMessageId:()=>f,onEvent:D,setCurrentMessageId:(_)=>f=_,textStreamed:A});return}if(g.type==="assistant"){let _=nD(g.message),R=Array.isArray(_?.content)?_.content:[],n=fD(_?.id);if(n)f=n;let B=n?A.has(n):!1;for(let C of R){let J=nD(C);if(!J)continue;if(J.type==="tool_use")D({id:fD(J.id),input:J.input??null,name:fD(J.name,"Tool"),type:"tool_use"});else if(!B&&J.type==="text"){let X=fD(J.text);if(X)D({delta:X,type:"text_delta"})}else if(!B&&J.type==="thinking"){let X=fD(J.thinking);if(X)D({delta:X,type:"thinking_delta"})}}return}if(g.type==="user"){let _=nD(g.message),R=Array.isArray(_?.content)?_.content:[];for(let n of R){let B=nD(n);if(B?.type==="tool_result")D({content:W$(B.content),isError:B.is_error===!0,toolUseId:fD(B.tool_use_id),type:"tool_result"})}return}if(g.type==="result"){let _=nD(g.usage);D({costUsd:uu(g.total_cost_usd),durationMs:uu(g.duration_ms),inputTokens:uu(_?.input_tokens),outputTokens:uu(_?.output_tokens),type:"usage"})}},E=($)=>{try{F(JSON.parse($))}catch{D({line:$,type:"raw"})}};return{feed($){u+=$;let g=u.indexOf(`
1498
+ `);while(g!==-1){let _=u.slice(0,g).trim();if(u=u.slice(g+1),_)E(_);g=u.indexOf(`
1499
+ `)}},flush(){let $=u.trim();if(u="",$)E($)}}}function $h(D,u){if(!D)return;if(D.type==="message_start"){let r=nD(D.message);if(u.setCurrentMessageId(fD(r?.id)||null),typeof D.ttft_ms==="number")u.onEvent({detail:`first token in ${Math.round(D.ttft_ms/100)/10}s`,label:"streaming",type:"status"});return}if(D.type==="content_block_start"){let r=nD(D.content_block),A=u.blockKey(D.index);if(u.blocks.set(A,{id:fD(r?.id)||void 0,input:"",name:fD(r?.name)||void 0,type:fD(r?.type)||void 0}),r?.type==="thinking")u.onEvent({type:"thinking_start"});return}if(D.type==="content_block_delta"){let r=nD(D.delta);if(r?.type==="text_delta"){let A=u.currentMessageId();if(A)u.textStreamed.add(A);u.onEvent({delta:fD(r.text),type:"text_delta"});return}if(r?.type==="thinking_delta"){let A=u.currentMessageId();if(A)u.textStreamed.add(A);u.onEvent({delta:fD(r.thinking),type:"thinking_delta"});return}if(r?.type==="input_json_delta"){let A=u.blocks.get(u.blockKey(D.index));if(A)A.input+=fD(r.partial_json)}}if(D.type==="content_block_stop")u.blocks.delete(u.blockKey(D.index))}function W$(D){if(typeof D==="string")return D;if(Array.isArray(D))return D.map((u)=>{let r=nD(u);return r?.type==="text"?fD(r.text):JSON.stringify(u)}).join(`
1500
+ `);if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}}function Eh(D){if(D==null)return null;if(typeof D==="object")return D;if(typeof D!=="string")return null;try{return JSON.parse(D)}catch{return null}}function nD(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)?D:null}function fD(D,u=""){return typeof D==="string"&&D.length>0?D:u}function uu(D){return typeof D==="number"&&Number.isFinite(D)?D:void 0}import{spawn as gh,spawnSync as Sh}from"child_process";import{randomUUID as _h}from"crypto";import{mkdir as Rh,readdir as nh,readFile as Bh,stat as Wh,writeFile as J$}from"fs/promises";import ir from"path";import j2 from"process";function G$(){return{async invoke(D){if(pu(D.metadata?.executionMode,"local-cli")==="byok")return Ch(D);return Gh(D)}}}async function Gh(D){let u=D.engineCommand||D.engineId;if(!u||u==="internal")throw Error("Local CLI execution requires an external engine command.");let r=Jh[D.engineId];if(!r)throw Error(`Local CLI engine is not wired yet: ${D.engineId}. Select a supported local engine or BYOK in Settings.`);await Rh(D.invocationRoot,{recursive:!0});let A=pu(D.metadata?.outputKind,"business-artifact"),f=pu(D.metadata?.skillName,"Soul artifact"),w=ir.posix.join("artifacts",D.sessionId,`${D.turnId}-${Zn(A)}.md`),F=[D.prompt,"","AIWorker session contract:","- Continue the current AIWorker workspace session as the selected external engine.","- Current working directory is the AIWorker workspace/project root.",`- If this turn produces a durable business artifact, write markdown under artifacts/${D.sessionId}/.`,`- Prefer ${w} for a new ${A} artifact.`,"- Text-only clarification, analysis, or follow-up is allowed; do not create a fake artifact just to satisfy the protocol.","- Keep evidence, assumptions, risks, review notes, and next actions separated in any durable artifact.","- Return a concise assistant message for the session timeline."].join(`
1501
+ `);await J$(ir.join(D.invocationRoot,"prompt.md"),F,"utf8"),n0(D,{kind:"status",label:"initializing",detail:`${r.name} via local CLI`});let E=r.buildArgs({command:u,input:D,model:pu(D.metadata?.model,""),reasoning:pu(D.metadata?.reasoning,"")}),$="",g=Date.now(),_=r.parser?jn(r.parser,(B)=>{let C=ih(B);if(C.kind==="text")$+=C.text;n0(D,C)}):null,R=await Xh(u,E,F,300000,{cwd:D.workspaceRoot,env:{...j2.env,...r.env??{}},onStderr:void 0,onStdout:(B)=>{if(_){_.feed(B);return}$+=B,n0(D,{kind:"text",text:B})}});if(_?.flush(),await J$(ir.join(D.invocationRoot,"stdout.log"),R.stdout,"utf8"),await J$(ir.join(D.invocationRoot,"stderr.log"),R.stderr,"utf8"),R.code!==0){let B=Oh(R.stderr||R.stdout);if(B.trim())n0(D,{chunk:vn(B,8000),kind:"log",stream:R.stderr?"stderr":"stdout"});throw Error(`${u} exited with code ${R.code}: ${vn(B||R.stderr||R.stdout,2000)}`)}$=$.trim();let n=await Uh({fallbackKind:A,fallbackTitle:f,sessionId:D.sessionId,sinceMs:g,turnId:D.turnId,workspaceRoot:D.workspaceRoot});return n0(D,{kind:"status",label:"completed",detail:n.length>0?`${n.length} artifact${n.length===1?"":"s"}`:"text response"}),{artifacts:n,lessons:[],metadata:{executionSource:"local-cli",finalMessage:$,processId:_h(),stderrLog:ir.join(D.invocationRoot,"stderr.log"),stdoutLog:ir.join(D.invocationRoot,"stdout.log")},review:n.length>0?{findings:[{message:"External engine artifact generated; human review is required before memory admission."}],risks:[],verdict:"needs_review"}:void 0,summary:$||`${r.name} completed without a durable artifact.`}}async function Ch(D){let u=on(D.metadata?.byok)?D.metadata.byok:{},r=pu(u.apiKeyRef,""),A=Ph(r),f=pu(u.baseUrl,"https://api.openai.com/v1").replace(/\/+$/,""),w=pu(u.model,"gpt-4o");n0(D,{kind:"status",label:"requesting",detail:w});let F=await Hh({apiKey:A,baseUrl:f,input:D,model:w}),E=pu(D.metadata?.outputKind,"business-artifact"),$=pu(D.metadata?.skillName,"Soul artifact");return n0(D,{kind:"text",text:`Generated ${$} with BYOK provider ${w}.`}),n0(D,{kind:"status",label:"completed",detail:E}),{artifacts:[{content:F,kind:E,path:ir.posix.join("artifacts",D.sessionId,`${D.turnId}-${Zn(E)}.md`),title:$}],lessons:[],metadata:{executionSource:"byok",model:w},review:{findings:[{message:"BYOK artifact generated; human review is required before memory admission."}],risks:[],verdict:"needs_review"},summary:`Generated ${$} with BYOK provider ${w}.`}}async function Hh({apiKey:D,baseUrl:u,input:r,model:A}){let f=pu(r.metadata?.skillName,"Soul artifact"),w=await fetch(`${u}/chat/completions`,{body:JSON.stringify({messages:[{content:"You are AIWorker external engine mode. Return one concise markdown business artifact. Keep evidence, assumptions, risks, review notes, and next actions separated.",role:"system"},{content:r.prompt,role:"user"}],model:A,temperature:0.2}),headers:{authorization:`Bearer ${D}`,"content-type":"application/json"},method:"POST"});if(!w.ok)throw Error(`BYOK provider failed for ${f}: HTTP ${w.status}`);let E=(await w.json()).choices?.[0]?.message?.content?.trim();if(!E)throw Error(`BYOK provider returned no artifact content for ${f}.`);return E}function Xh(D,u,r,A,f={}){return new Promise((w,F)=>{let E=gh(D,u,{cwd:f.cwd??j2.cwd(),env:f.env??j2.env,stdio:["pipe","pipe","pipe"]}),$="",g="",_=!1,R=setTimeout(()=>{_=!0,E.kill("SIGTERM")},A);E.stdout.setEncoding("utf8"),E.stderr.setEncoding("utf8"),E.stdout.on("data",(n)=>{$+=n,f.onStdout?.(n)}),E.stderr.on("data",(n)=>{g+=n,f.onStderr?.(n)}),E.stdin.on("error",(n)=>{if(n.code!=="EPIPE")clearTimeout(R),F(n)}),E.on("error",(n)=>{clearTimeout(R),F(n)}),E.on("close",(n)=>{if(clearTimeout(R),_)g+=`
1502
+ Process exceeded ${A}ms and was terminated.`;w({code:n,stdout:$,stderr:g})}),E.stdin.end(r)})}function ih(D){if(D.type==="status")return{detail:D.detail,kind:"status",label:D.label};if(D.type==="text_delta")return{kind:"text",text:D.delta};if(D.type==="thinking_delta")return{kind:"thinking",text:D.delta};if(D.type==="thinking_start")return{detail:"external engine reasoning started",kind:"status",label:"thinking"};if(D.type==="file_change")return{detail:`${D.action} ${D.path}${D.status?` (${D.status})`:""}`,kind:"status",label:"file_change"};if(D.type==="tool_use")return{id:D.id,input:on(D.input)?D.input:{value:D.input},kind:"tool_use",name:D.name};if(D.type==="tool_result")return{content:D.content,id:D.toolUseId,isError:D.isError,kind:"tool_result"};if(D.type==="usage")return{costUsd:D.costUsd,inputTokens:D.inputTokens,kind:"usage",outputTokens:D.outputTokens};return{kind:"raw",line:D.line}}async function Uh({fallbackKind:D,fallbackTitle:u,sessionId:r,sinceMs:A,turnId:f,workspaceRoot:w}){let F=ir.join(w,"artifacts",r),E=[];try{E=await nh(F)}catch{return[]}let $=[];for(let g of E.sort()){if(!g.endsWith(".md")&&!g.endsWith(".markdown"))continue;let _=ir.join(F,g),R=await Wh(_).catch(()=>null);if(!R?.isFile())continue;if(!(g.includes(f)||R.mtimeMs>=A-1000))continue;let B=ir.posix.join("artifacts",r,g);$.push({content:await Bh(_,"utf8"),kind:D,path:B,title:u})}return $}function Yh(D,u,r){let A=`${D}\x00${u.join("\x00")}\x00${r}`,f=Tn.get(A);if(f!==void 0)return f;let w=Sh(D,u,{encoding:"utf8",timeout:5000}),F=`${w.stdout??""}
1503
+ ${w.stderr??""}`,E=w.status===0&&F.includes(r);return Tn.set(A,E),E}function Mh(D,u){let r=D.includes("/")?D.split("/").at(-1)??D:D;if((!r||r==="default"||r.startsWith("gpt-5.2")||r.startsWith("gpt-5.3")||r.startsWith("gpt-5.4")||r.startsWith("gpt-5.5"))&&u==="minimal")return"low";if(r==="gpt-5.1"&&u==="xhigh")return"high";if(r==="gpt-5.1-codex-mini")return u==="high"||u==="xhigh"?"high":"medium";return u}function n0(D,u){D.onEvent?.(u)}function vn(D,u){if(D.length<=u)return D;return`${D.slice(0,u)}
1504
+ ...[truncated]`}function Oh(D){if(D.includes("failed to warm featured plugin ids cache")&&D.includes("/backend-api/plugins/featured")){let u=D.indexOf("OpenAI Codex v");return u===-1?"":D.slice(u)}return D}function Ph(D){let u=D.trim();if(!u)throw Error("BYOK mode requires an API key reference such as env:OPENAI_API_KEY.");let r=u.startsWith("env:")?u.slice(4):u;if(!/^[A-Z_]\w*$/i.test(r))throw Error("BYOK API key reference must be env:NAME or NAME.");let A=j2.env[r];if(!A)throw Error(`BYOK API key environment variable is not set: ${r}.`);return A}function Zn(D){return D.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function pu(D,u){return typeof D==="string"&&D.trim().length>0?D.trim():u}function on(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}var Jh,Tn;var C$=W(()=>{Jh={"claude-code":{buildArgs({command:D,model:u}){let r=["-p","--output-format","stream-json","--verbose"];if(Yh(D,["-p","--help"],"--include-partial-messages"))r.push("--include-partial-messages");if(u&&u!=="default")r.push("--model",u);return r.push("--permission-mode","bypassPermissions"),r},name:"Claude Code",parser:"claude"},codex:{buildArgs({input:D,model:u,reasoning:r}){let A=["exec","--json","--skip-git-repo-check","--sandbox","workspace-write","-c","sandbox_workspace_write.network_access=true","-C",D.workspaceRoot];if(j2.env.AIWORKER_CODEX_DISABLE_PLUGINS==="1"||j2.env.OD_CODEX_DISABLE_PLUGINS==="1")A.push("--disable","plugins");if(u&&u!=="default")A.push("--model",u);if(r&&r!=="default")A.push("-c",`model_reasoning_effort="${Mh(u,r)}"`);return A},name:"Codex CLI",parser:"codex"},cursor:{buildArgs({input:D,model:u}){let r=["--print","--output-format","stream-json","--stream-partial-output","--force","--trust","--workspace",D.workspaceRoot];if(u&&u!=="default")r.push("--model",u);return r},name:"Cursor Agent",parser:"cursor-agent"},gemini:{buildArgs({model:D}){let u=["--output-format","stream-json","--yolo"];if(D&&D!=="default")u.push("--model",D);return u},env:{GEMINI_CLI_TRUST_WORKSPACE:"true"},name:"Gemini CLI",parser:"gemini"},opencode:{buildArgs({model:D}){let u=["run","--format","json","--dangerously-skip-permissions"];if(D&&D!=="default")u.push("--model",D);return u.push("-"),u},name:"OpenCode",parser:"opencode"},qwen:{buildArgs({model:D}){let u=["--yolo"];if(D&&D!=="default")u.push("--model",D);return u.push("-"),u},name:"Qwen Code"}};Tn=new Map});import{createHash as kh}from"crypto";import{mkdir as dn,readdir as Ih,readFile as ln,rm as Vh,stat as Kh,writeFile as hh}from"fs/promises";import Y1 from"path";class B0{#D;constructor(D){this.#D=Y1.resolve(D)}get root(){return this.#D}async ensureRoot(){await dn(this.#D,{recursive:!0})}resolve(D){let u=Y1.resolve(this.#D,D),r=`${this.#D}${Y1.sep}`;if(u!==this.#D&&!u.startsWith(r))throw Error(`Path escapes workspace root: ${D}`);return u}async write(D){let u=this.resolve(D.path);return await dn(Y1.dirname(u),{recursive:!0}),await hh(u,D.content),this.describe(D.path)}async read(D){return ln(this.resolve(D),"utf8")}async delete(D){await Vh(this.resolve(D),{force:!0,recursive:!0})}async describe(D){let u=this.resolve(D),r=await Kh(u),A=r.isDirectory()?"directory":"file",f=A==="file"?await ln(u):null;return{path:D,kind:A,size:A==="file"?r.size:null,mtime:Math.trunc(r.mtimeMs),hash:f?kh("sha256").update(f).digest("hex"):null}}async list(D=""){await this.ensureRoot();let u=this.resolve(D),r=await Ih(u);return Promise.all(r.map((A)=>this.describe(Y1.posix.join(D,A))))}}var H$=()=>{};import{spawnSync as pn}from"child_process";import{mkdir as W0,readFile as Nh,stat as Qh,writeFile as yf}from"fs/promises";import aD from"path";async function xn(D){let u=aD.resolve(D.rootPath);if(await W0(u,{recursive:!0}),await W0(aD.join(u,"artifacts"),{recursive:!0}),await W0(aD.join(u,X$),{recursive:!0}),await W0(aD.join(u,"evidence","descriptors"),{recursive:!0}),await W0(aD.join(u,"evidence","raw"),{recursive:!0}),await W0(aD.join(u,".aiworker","sessions"),{recursive:!0}),D.seedProfileFiles!==!1)await yn(aD.join(u,T2),sh(D.name)),await yn(aD.join(u,"evidence","README.md"),zh()),await Th(u);return{git:Zh(u,await vh(u)),profilePath:T2}}async function mn(D){if(D.verdict!=="pass"&&D.verdict!=="warn")throw Error("Only pass or warn reviews can promote a profile revision.");let u=aD.resolve(D.workspaceRoot),r=aD.posix.join(X$,`${D.reviewId}.md`);await W0(aD.join(u,X$),{recursive:!0}),await yf(cn(u,T2),dh(D.profileMarkdown),"utf8"),await yf(cn(u,r),jh(D),"utf8");let A=an(u,[T2,D.artifactPath,r],`profile: approve ${D.workspaceName} revision`),f=D.tagName?oh(u,D.tagName,`Approved profile version for ${D.workspaceName}`):null;return{git:A,profilePath:T2,reviewPath:r,tag:f}}function sh(D){return[`# ${D}`,"","> Canonical accepted profile for this Soul workspace. Session outputs remain proposals until review.","","## Current Profile Summary","","No approved profile revision yet.","","## Evidence And Review","","- Proposed changes live in `artifacts/`.","- Human review records live in `reviews/`.","- Evidence descriptors live in `evidence/descriptors/`.","","## Revision Notes","","Approve a profile revision to update this README.",""].join(`
1505
+ `)}function zh(){return["# Evidence","","Store source descriptors in `descriptors/`. Keep raw sensitive evidence in `raw/`, which is ignored by the profile git ledger by default.",""].join(`
1506
+ `)}function jh(D){return[`# Profile Review ${D.reviewId}`,"",`- Verdict: ${D.verdict}`,`- Artifact: ${D.artifactTitle} (${D.artifactPath})`,`- Reviewed At: ${D.now}`,"","## Findings",tn(D.findingsJson),"","## Risks",tn(D.risksJson),""].join(`
1507
+ `)}async function yn(D,u){if(await DB(D))return;await W0(aD.dirname(D),{recursive:!0}),await yf(D,u,"utf8")}async function Th(D){let u=aD.join(D,".gitignore"),r=await lh(u),A=Lh.filter((w)=>!r.split(/\r?\n/).includes(w));if(A.length===0)return;let f=[r.trimEnd(),r.trim().length>0?"":null,"# AIWorker profile ledger",...A,""].filter((w)=>w!==null).join(`
1508
+ `);await yf(u,f,"utf8")}async function vh(D){let u=[T2,".gitignore","evidence/README.md"],r=[];for(let A of u)if(await DB(aD.join(D,A)))r.push(A);return r}function Zh(D,u){if(!i$())return{message:"git is not available on PATH.",status:"unavailable"};if(!U$(D)){let r=jr(D,["init"]);if(r.status!==0)return{message:r.stderr||r.stdout||"git init failed.",status:"failed"}}return en(D),an(D,u,"profile: initialize workspace")}function an(D,u,r){if(!i$())return{message:"git is not available on PATH.",status:"unavailable"};if(!U$(D))return{message:"workspace is not a git repository.",status:"failed"};if(u.length===0)return{hash:lf(D),message:"no bootstrap files to commit.",status:"skipped"};en(D);let A=jr(D,["add","--",...u]);if(A.status!==0)return{message:A.stderr||A.stdout||"git add failed.",status:"failed"};if(jr(D,["diff","--cached","--quiet"]).status===0)return{hash:lf(D),status:"skipped"};let w=jr(D,["commit","-m",r]);if(w.status!==0)return{message:w.stderr||w.stdout||"git commit failed.",status:"failed"};return{hash:lf(D),status:"created"}}function oh(D,u,r){if(!i$())return{message:"git is not available on PATH.",status:"unavailable"};if(!U$(D))return{message:"workspace is not a git repository.",status:"failed"};let A=jr(D,["tag","-a",u,"-m",r]);if(A.status!==0)return{message:A.stderr||A.stdout||"git tag failed.",status:"failed"};return{hash:lf(D),status:"created"}}function en(D){jr(D,["config","user.name",qh]),jr(D,["config","user.email",bh])}function lf(D){let u=jr(D,["rev-parse","--verify","HEAD"]);return u.status===0?u.stdout.trim():void 0}function i$(){return pn("git",["--version"],{encoding:"utf8"}).status===0}function U$(D){return jr(D,["rev-parse","--is-inside-work-tree"]).status===0}function jr(D,u){let r=pn("git",u,{cwd:D,encoding:"utf8"});return{status:r.status,stderr:r.stderr??"",stdout:r.stdout??""}}function cn(D,u){let r=aD.resolve(D,u),A=`${D}${aD.sep}`;if(r!==D&&!r.startsWith(A))throw Error(`Path escapes workspace root: ${u}`);return r}function dh(D){return`${D.trimEnd()}
1509
+ `}function tn(D){if(D.length===0)return"- None.";return D.map((u)=>`- ${JSON.stringify(u)}`).join(`
1510
+ `)}async function DB(D){try{return await Qh(D),!0}catch(u){if(uB(u))return!1;throw u}}async function lh(D){try{return await Nh(D,"utf8")}catch(u){if(uB(u))return"";throw u}}function uB(D){return typeof D==="object"&&D!==null&&"code"in D&&D.code==="ENOENT"}var T2="README.md",X$="reviews",Lh,qh="AIWorker Profile Ledger",bh="aiworker@local";var rB=W(()=>{Lh=[".aiworker/sessions/",".aiworker/projections.json","evidence/raw/"]});import{randomUUID as Tr}from"crypto";import{mkdir as cf,writeFile as AB}from"fs/promises";import J0 from"path";class M${#D;#r;#A;#F;#u;bus=new df;constructor(D){this.#D=D.worker,this.#r=J0.resolve(D.workspacesRoot),this.#A=D.executor??G$(),this.#F=D.engineAssetSource??null,this.#u=D.now??(()=>new Date().toISOString())}get workerId(){return this.#D.id}get workspacesRoot(){return this.#r}async init(){await cf(this.#r,{recursive:!0});let D=A2({id:this.#D.id,soulId:this.#D.soulId,name:this.#D.name,defaultEngineId:this.#D.defaultEngineId??null,metadataJson:this.#D.metadata??{},at:this.#u()});return await this.repairWorkspaceLayouts(),D}async createWorkspace(D){this.requireWorker();let u=Tr(),r=J0.join(this.#r,u),A=await this.prepareWorkspaceLayout({name:D.name,rootPath:r});return FE({id:u,workerId:this.workerId,name:D.name,rootPath:r,type:D.type??"workspace",sourcePointersJson:D.sourcePointers??[],metadataJson:{...D.metadata??{},engineAssetProjection:A.engineAssets?{projectionCount:A.engineAssets.projections.length,projectionManifestPath:hn()}:null,profileLedger:{git:A.profile.git,profilePath:A.profile.profilePath}},at:this.#u()})}async createSession(D){let u=this.requireWorkspace(D.workspaceId),r=wE({id:Tr(),workerId:this.workerId,workspaceId:u.id,capabilityTemplateId:D.capabilityTemplateId,title:D.title,context:D.context??"",status:"active",metadataJson:D.metadata??{},startedAt:this.#u(),at:this.#u()});return await this.materializeSessionContext(u,r,D.metadata??{}),this.appendEvent(r.id,"status",{status:"active"}),this.bus.emit({kind:"session",workspaceId:u.id,sessionId:r.id,payload:{status:"active"},at:this.#u()}),r}async startTurn(D){let u=this.requireSession(D.sessionId),r=this.requireWorkspace(u.workspaceId),A=gE(u.id),f=EE({id:Tr(),sessionId:u.id,seq:A,input:D.input,status:"running",metadataJson:D.metadata??{},at:this.#u()}),w=this.buildInvocationPrompt(u,f,D.metadata??{}),F=SE({id:Tr(),sessionId:u.id,turnId:f.id,seq:RE(u.id),engineId:D.engineId,engineCommand:D.engineCommand??null,prompt:w,status:"running",metadataJson:D.metadata??{},startedAt:this.#u(),at:this.#u()});this.appendEvent(u.id,"status",{status:"running",turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"running",turn:f},at:this.#u()});try{let E=await this.ensureInvocationRoot(r,u,F),$=await this.#A.invoke({engineCommand:D.engineCommand??null,engineId:D.engineId,invocationId:F.id,invocationRoot:E,onEvent:(B)=>this.appendAgentEvent(u.id,B,f.id,F.id),prompt:w,sessionId:u.id,turnId:f.id,workspaceId:r.id,workspaceRoot:r.rootPath,metadata:{...u.metadataJson??{},...D.metadata??{},capabilityTemplateId:u.capabilityTemplateId,sessionId:u.id,turnId:f.id,workerId:this.workerId,workspaceId:r.id}}),g=await this.captureResult(r,u,f,F,$,D.metadata??{}),_=TF({id:F.id,status:"succeeded",summary:$.summary,metadataJson:{...D.metadata??{},...$.metadata??{}},finishedAt:this.#u(),at:this.#u()}),R=jF({id:f.id,status:"succeeded",response:$.summary,at:this.#u()}),n=zF({id:u.id,status:"active",at:this.#u()});return this.appendEvent(u.id,"status",{status:"succeeded",turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"succeeded",turn:R},at:this.#u()}),{session:n,turn:R,invocation:_,events:_r(u.id),...g}}catch(E){let $=E instanceof Error?E.message:String(E),g=TF({id:F.id,status:"failed",error:$,finishedAt:this.#u(),at:this.#u()}),_=jF({id:f.id,status:"failed",error:$,at:this.#u()}),R=zF({id:u.id,status:"failed",endedAt:this.#u(),at:this.#u()});return this.appendEvent(u.id,"error",{message:$,turnId:f.id},f.id,F.id),this.bus.emit({kind:"turn",workspaceId:r.id,sessionId:u.id,turnId:f.id,invocationId:F.id,payload:{status:"failed",turn:_},at:this.#u()}),{session:R,turn:_,invocation:g,events:_r(u.id),files:[],artifacts:[],review:null,lessons:[]}}}snapshot(){let D=this.requireWorker(),u=Xu(D.id),r=new Set(u.map((F)=>F.id)),A=tr().filter((F)=>r.has(F.workspaceId)),f=new Set(A.map((F)=>F.id)),w=Sr().filter((F)=>f.has(F.sessionId));return{worker:D,workspaces:u,sessions:A,turns:w,invocations:_E().filter((F)=>f.has(F.sessionId)),files:zu().filter((F)=>r.has(F.workspaceId)),artifacts:Rr().filter((F)=>r.has(F.workspaceId)),reviews:f2().filter((F)=>r.has(F.workspaceId)),lessons:F2().filter((F)=>r.has(F.workspaceId)),events:_r().filter((F)=>f.has(F.sessionId))}}files(D){let u=this.requireWorkspace(D);return new B0(u.rootPath)}async promoteProfileRevision(D){let u=this.requireWorkspace(D.workspaceId),r=pr(D.artifactId);if(!r||r.workspaceId!==u.id)throw Error(`Artifact not found for workspace ${u.id}: ${D.artifactId}`);let A=D.verdict??"pass",f=Tr(),F=await new B0(u.rootPath).read(r.path),E=this.#u(),$=await mn({artifactPath:r.path,artifactTitle:r.title,findingsJson:D.findingsJson??[{message:"Profile revision approved."}],now:E,profileMarkdown:D.profileMarkdown??F,reviewId:f,risksJson:D.risksJson??[],tagName:D.tagName,verdict:A,workspaceName:u.name,workspaceRoot:u.rootPath}),g=P0({id:f,workspaceId:u.id,sessionId:r.sessionId,turnId:r.turnId,artifactId:r.id,verdict:A,findingsJson:D.findingsJson??[{message:"Profile revision approved."}],risksJson:D.risksJson??[],at:E});if(g.sessionId)this.appendEvent(g.sessionId,"review",{reviewId:g.id,verdict:g.verdict,profilePath:$.profilePath},g.turnId,null),this.bus.emit({kind:"review",workspaceId:u.id,sessionId:g.sessionId,turnId:g.turnId??void 0,payload:{reviewId:g.id,profilePath:$.profilePath},at:this.#u()});return{...$,review:g}}dispose(){return}async captureResult(D,u,r,A,f,w){let F=new B0(D.rootPath),E=[],$=[];for(let R of f.artifacts??[]){let n=await F.write({path:R.path,content:R.content}),B=GA({id:Tr(),workspaceId:D.id,path:n.path,kind:"generated",size:n.size,mtime:n.mtime,hash:n.hash,source:"session",at:this.#u()});E.push(B);let C=WE({id:Tr(),workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,path:R.path,kind:R.kind??"file",title:R.title??R.path,metadataJson:{capabilityTemplateId:u.capabilityTemplateId,fileId:B.id,outputKind:R.kind??w.outputKind,...typeof w.soulAppId==="string"?{soulAppId:w.soulAppId}:{},workerId:this.workerId},at:this.#u()});$.push(C),this.appendEvent(u.id,"artifact",{artifactId:C.id,path:C.path},r.id,A.id),this.bus.emit({kind:"artifact",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{artifactId:C.id},at:this.#u()})}let g=f.review?P0({id:Tr(),workspaceId:D.id,sessionId:u.id,turnId:r.id,artifactId:$[0]?.id??null,verdict:f.review.verdict??"needs_review",findingsJson:f.review.findings??[],risksJson:f.review.risks??[],at:this.#u()}):null;if(g)this.appendEvent(u.id,"review",{reviewId:g.id,verdict:g.verdict},r.id,A.id),this.bus.emit({kind:"review",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{reviewId:g.id},at:this.#u()});let _=(f.lessons??[]).map((R)=>xr({id:Tr(),workspaceId:D.id,sourceReviewId:g?.id??null,statement:R.statement,evidenceJson:R.evidence??[],at:this.#u()}));for(let R of _)this.appendEvent(u.id,"lesson",{lessonId:R.id},r.id,A.id),this.bus.emit({kind:"lesson",workspaceId:D.id,sessionId:u.id,turnId:r.id,invocationId:A.id,payload:{lessonId:R.id},at:this.#u()});return{files:E,artifacts:$,review:g,lessons:_}}appendAgentEvent(D,u,r,A){if(u.kind==="text")return this.appendEvent(D,"assistant_delta",{agentEvent:u,delta:u.text,text:u.text},r,A);if(u.kind==="thinking"||u.kind==="log"||u.kind==="raw")return this.appendEvent(D,"log",{agentEvent:u},r,A);if(u.kind==="tool_use"||u.kind==="tool_result")return this.appendEvent(D,"tool",{agentEvent:u},r,A);return this.appendEvent(D,u.kind==="status"||u.kind==="usage"?"status":"log",{agentEvent:u},r,A)}appendEvent(D,u,r,A,f){let w=nE({sessionId:D,turnId:A??null,invocationId:f??null,seq:BE(D),type:u,payloadJson:r,at:this.#u()}),F=wu(D);if(F)this.bus.emit({at:w.createdAt,invocationId:f??void 0,kind:"event",payload:{event:w},sessionId:D,turnId:A??void 0,workspaceId:F.workspaceId});return w}buildInvocationPrompt(D,u,r){let A=[`Soul worker: ${this.#D.name}`,`Soul id: ${this.#D.soulId}`,`Workspace session: ${D.title}`,`Capability template: ${D.capabilityTemplateId}`,`Output kind: ${Y$(r.outputKind,"business-artifact")}`,"","Workspace profile ledger:","- README.md is the accepted profile for this workspace.",`- Proposed changes should be written under artifacts/${D.id}/ before review.`,"- Human review records live under reviews/.","- Native skills may be projected under .agents/skills and .claude/skills when the Soul App provides them.","","Session context:",D.context||"(no prior context)","","Turn request:",u.input.trim()],f=Array.isArray(r.inputHints)?r.inputHints:[],w=Array.isArray(r.reviewRubric)?r.reviewRubric:[];if(f.length>0)A.push("","Input hints:",...f.map((F)=>`- ${String(F)}`));if(w.length>0)A.push("","Review rubric:",...w.map((F)=>`- ${String(F)}`));return A.join(`
1511
+ `)}async materializeSessionContext(D,u,r){let A=new B0(D.rootPath),f=J0.posix.join(".aiworker","sessions",u.id);await cf(A.resolve(J0.posix.join(f,"context","capability")),{recursive:!0}),await AB(A.resolve(J0.posix.join(f,"context","active-context.md")),this.buildActiveContext(u,r),"utf8"),await AB(A.resolve(J0.posix.join(f,"context","capability","SKILL.md")),this.buildCapabilitySkill(u,r),"utf8"),await cf(A.resolve(J0.posix.join(f,"invocations")),{recursive:!0})}buildActiveContext(D,u){return[`# ${D.title}`,"",`- Worker: ${this.#D.name}`,`- Soul: ${this.#D.soulId}`,`- Capability template: ${D.capabilityTemplateId}`,`- Output kind: ${Y$(u.outputKind,"business-artifact")}`,"- Accepted profile: README.md",`- Proposed change directory: artifacts/${D.id}/`,"- Native skill projections: .agents/skills and .claude/skills when available","","## Context",D.context||"No context supplied."].join(`
1512
+ `)}buildCapabilitySkill(D,u){let r=Y$(u.skillName,D.capabilityTemplateId),A=Array.isArray(u.reviewRubric)?u.reviewRubric.map(String):[];return[`# ${r}`,"","Use this capability in the current AIWorker session only.","","## Review Rubric",...A.length>0?A.map((f)=>`- ${f}`):["- Separate facts, assumptions, risks, and next actions."]].join(`
1513
+ `)}async ensureInvocationRoot(D,u,r){let A=new B0(D.rootPath),f=String(r.seq).padStart(4,"0"),w=A.resolve(J0.posix.join(".aiworker","sessions",u.id,"invocations",f));return await cf(w,{recursive:!0}),w}requireWorker(){let D=PD(this.workerId);if(!D)throw Error("Local Soul worker is not initialized.");return D}requireWorkspace(D){let u=Du(D);if(!u||u.workerId!==this.workerId)throw Error(`Workspace not found for worker ${this.workerId}: ${D}`);return u}requireSession(D){let u=wu(D);if(!u||u.workerId!==this.workerId)throw Error(`Session not found for worker ${this.workerId}: ${D}`);return u}async repairWorkspaceLayouts(){for(let D of Xu(this.workerId))await this.prepareWorkspaceLayout({name:D.name,rootPath:D.rootPath})}async prepareWorkspaceLayout(D){let u=this.#F?await Kn({appId:this.#F.appId,engineAssets:this.#F.engineAssets,engineTarget:Nn(this.#D.defaultEngineId),now:this.#u(),sourceRoot:this.#F.sourceRoot,variables:{appId:this.#F.appId,soulId:this.#D.soulId,workerName:this.#D.name,workspaceName:D.name},workspaceRoot:D.rootPath}):null,r=await xn({name:D.name,now:this.#u(),rootPath:D.rootPath,seedProfileFiles:!this.#F,soulId:this.#D.soulId,workerName:this.#D.name});return{engineAssets:u,profile:r}}}function O$(D){return new M$(D)}function Y$(D,u){return typeof D==="string"&&D.trim().length>0?D.trim():u}var P$=W(()=>{nr();sn();C$();H$();rB()});import fB from"path";function M1(D){return new k$(D)}class k${options;constructor(D){this.options=D}listCatalog(){return z2()}listApps(){return Tf()}getApp(D){return Ou(D)}reviewAppSecurity(D){let u=Ou(D);if(!u)throw Error(`Soul App not found: ${D}`);return _$(u,this.registryContext())}async installAppFromPath(D){return G1(D,this.registryContext())}installAppManifest(D){return jf(D,this.registryContext())}enableApp(D){return C1(D,this.registryContext())}disableApp(D){return H1(D,this.registryContext())}healthcheckApp(D){return f$(D,this.registryContext())}async bootstrapOfficialSoulApps(){let D=await E$({...this.registryContext(),officialAppsRoot:this.options.officialAppsRoot}),u=g$(this.options.now?.());return{catalog:this.listCatalog(),legacyMetadataDiscard:u,results:D,scope:"official",status:D.some((r)=>r.action==="error")?"fail":"pass"}}listSouls(){return this.listCatalog().souls}findSoul(D){return X1(D)}requireAvailableSoul(D){let u=tf(D,"soulId"),r=X1(u);if(!r||r.status!=="available")throw cu.badRequest(`Available Soul not found: ${u}`,"SOUL_NOT_AVAILABLE");return r}listCapabilityTemplates(D){return D?Zf(D):this.listCatalog().templates}listCapabilityTemplatesForWorker(D){let u=this.requireWorker(D);return Zf(u.soulId)}requireCapabilityTemplateForWorker(D,u){let r=this.requireWorker(D),A=tf(u,"capabilityTemplateId"),f=vf(A);if(!f||f.soulId!==r.soulId)throw cu.badRequest(`Template ${A} does not belong to worker ${D}.`,"TEMPLATE_NOT_AVAILABLE");return f}async createSoulWorker(D){let u=this.requireAvailableSoul(D.soulId),r=tf(D.name,"name"),A=D.id?tf(D.id,"id"):Qw();if(PD(A))throw new cu("CONFLICT",409,`Worker already exists: ${A}`);let f=A2({id:A,soulId:u.id,name:r,defaultEngineId:D.defaultEngineId??"codex",metadataJson:{defaultTemplates:[...u.defaultTemplates],description:u.description,domain:u.domain,soulAppId:Ou(u.id)?.appId??null,...D.metadata??{}}}),w=this.createRuntimeForWorker(f);return await w.init(),{runtime:w,snapshot:w.snapshot(),worker:f}}createRuntimeForWorker(D){return O$({worker:{id:D.id,soulId:D.soulId,name:D.name,defaultEngineId:D.defaultEngineId,metadata:D.metadataJson},executor:this.options.executor,engineAssetSource:this.engineAssetSourceForWorker(D),now:this.options.now,workspacesRoot:fB.join(this.options.workersRoot,D.id,"workspaces")})}enrichTemplateMetadata(D,u,r){let A=PD(D),f=A?X1(A.soulId):null,w=vf(u);if(!A||!f||!w)return r;return{...r,capabilityTemplateId:w.id,inputHints:w.inputHints,outputKind:w.outputKind,reviewRubric:w.reviewRubric,skillName:w.name,soulAppId:Ou(f.id)?.appId??null,soulName:f.name,workerId:A.id}}registryContext(){return{now:this.options.now,...this.options.registryContext?.()??{}}}engineAssetSourceForWorker(D){let u=Ou(D.soulId);if(!u||u.status!=="enabled"||u.sourceKind!=="manifest-path")return null;return{appId:u.appId,engineAssets:u.manifest.engineAssets,sourceRoot:fB.dirname(u.sourceRef)}}requireWorker(D){let u=PD(D);if(!u)throw Error(`Worker not found: ${D}`);return u}}function tf(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`Missing required field: ${u}`);return D.trim()}var FB=W(()=>{s2();nr();S$();i1();P$()});function wB(D={}){let u=[{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!0,description:"Local app-scoped Soul App storage backed by worker.db metadata records.",enabled:!0,id:"storage.local-sqlite",kind:"storage",label:"Local SQLite storage",local:!0,status:"active"},{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!1,description:"Future app-scoped object storage provider for S3-compatible buckets.",enabled:!1,id:"storage.s3",kind:"storage",label:"S3 bucket storage",local:!1,notes:["Planned provider metadata only; no cloud SDK is loaded by the local Host."],status:"planned"},{appScoped:!0,capabilities:["storage.read","storage.write","storage.list"],configured:!1,description:"Future app-scoped object storage provider for Google Cloud Storage buckets.",enabled:!1,id:"storage.gcp-bucket",kind:"storage",label:"GCP bucket storage",local:!1,notes:["Planned provider metadata only; no cloud SDK is loaded by the local Host."],status:"planned"},{appScoped:!0,capabilities:["audit.read","audit.write"],configured:!0,description:"Local Host audit ledger for broker decisions and platform actions.",enabled:!0,id:"audit.local-sqlite",kind:"audit",label:"Local SQLite audit ledger",local:!0,status:"active"},{appScoped:!0,capabilities:["secret.reference"],configured:!1,description:"Future secret reference resolver for app-scoped broker grants.",enabled:!1,id:"secret.vault-ref",kind:"secret",label:"Vault secret references",local:!1,notes:["Planned provider metadata only; registry never returns raw secret values."],status:"planned"},...(D.connectors??[]).map(yh)];return{providers:u,summary:{activeCount:u.filter((r)=>r.status==="active").length,configuredCount:u.filter((r)=>r.configured).length,plannedCount:u.filter((r)=>r.status==="planned").length,providerCount:u.length}}}function yh(D){let u=D.status==="configured",r=u?D.enabled?"active":"disabled":"not_configured";return{appScoped:!0,capabilities:["connector.read"],configured:u,description:`Host connector broker metadata for ${D.name}.`,enabled:D.enabled,id:`connector.${D.id}`,kind:"connector",label:D.name,local:!1,status:r}}function gB(D,u,r,A=new Date().toISOString()){let f={appId:D,artifactId:r.artifactId??null,authority:"soul-app",cache:{freshness:"non-authoritative"},id:u,kind:r.kind,reference:r.reference?th(r.reference):null,reviewId:r.reviewId??null,sessionId:r.sessionId??null,summary:r.summary??null,title:r.title,updatedAt:A,workspaceId:r.workspaceId??null};return EB.set(ch(D,u),f),f}function SB(D,u){let r=$B(u),A=[...EB.values()].filter((f)=>f.appId===D).filter((f)=>!r||$B(ph(f)).includes(r));return{appId:D,authority:"soul-app",items:A,query:u}}function ch(D,u){return`${D}:${u}`}function th(D){return{id:D.id,type:D.type,...D.url?{url:D.url}:{}}}function ph(D){return[D.id,D.kind,D.title,D.summary,D.reference?.id,D.reference?.type].filter(Boolean).join(`
1514
+ `)}function $B(D){return D.trim().toLowerCase()}var EB;var _B=W(()=>{EB=new Map});function I$(){return{get(D,u){return C8(D,u)},list(D){return CE(D)},put(D){return GE(D)}}}var V$=W(()=>{nr()});import{randomUUID as RB}from"crypto";function Su(D){let u=D.storageProvider??I$();return{artifacts:{list(r=D.workspaceId){let A=Ur(D,"artifact","read","*");if(Yr(D,A,"artifact","read",r??"*",{workspaceId:r}),!A.allowed)return Mr(A);return Rr(r)}},audit:{list(){return XE(D.appId)}},connectors:{readEvidence(r,A){let f=Ur(D,"connector","read",r);if(Yr(D,f,"connector","read",r,{query:A}),!f.allowed)return Mr(f);return{appId:D.appId,connectorId:r,query:A,records:[{appId:D.appId,connectorId:r,query:A,redacted:!0,source:"host-connector-broker"}],redacted:!0}}},engine:{createInvocation(r){let A=LD("engine_owned_by_host","Soul Apps cannot create raw engine invocations; Host owns engine scheduling and audit.");return Yr(D,A,"engine","create","invocation",{promptLength:r.prompt.length}),Mr(A)}},memory:{propose(r){let A=Ur(D,"memory","propose",D.appId);if(Yr(D,A,"memory","propose",D.appId,{sourceReviewId:r.sourceReviewId??null,workspaceId:r.workspaceId}),!A.allowed)return Mr(A);return xr({evidenceJson:[...r.evidenceJson??[],{appId:D.appId,namespace:D.appId,source:"soul-app-broker"}],id:`lesson_${RB()}`,sourceReviewId:r.sourceReviewId??null,statement:r.statement,status:"proposed",workspaceId:r.workspaceId})}},permissions:{decide(r,A,f){return Ur(D,r,A,f)},list(){return K$(D)?.manifest.permissions??[]}},providers:{list(){return wB({connectors:D.connectorProviders})}},reviews:{create(r){let A=Ur(D,"review","create","review");if(Yr(D,A,"review","create",r.artifactId??"review",{artifactId:r.artifactId??null,workspaceId:r.workspaceId}),!A.allowed)return Mr(A);return P0({artifactId:r.artifactId??null,findingsJson:r.findingsJson??[],id:`review_${RB()}`,risksJson:r.risksJson??[],sessionId:r.sessionId??D.sessionId??null,turnId:r.turnId??null,verdict:r.verdict??"needs_review",workspaceId:r.workspaceId})}},search:{query(r){let A=Ur(D,"search","read",D.appId);if(Yr(D,A,"search","read",D.appId,{query:r}),!A.allowed)return Mr(A);return SB(D.appId,r)},upsert(r,A){let f=Ur(D,"search","write",D.appId);if(Yr(D,f,"search","write",r,{artifactId:A.artifactId??null,kind:A.kind,reviewId:A.reviewId??null,sessionId:A.sessionId??null,workspaceId:A.workspaceId??null}),!f.allowed)return Mr(f);return gB(D.appId,r,A,D.now?.())}},storage:{get(r){let A=Ur(D,"storage","read",D.appId);if(Yr(D,A,"storage","read",r,{key:r}),!A.allowed)return Mr(A);return u.get(D.appId,r)},list(){let r=Ur(D,"storage","read",D.appId);if(Yr(D,r,"storage","read",D.appId,{}),!r.allowed)return Mr(r);return u.list(D.appId)},put(r,A,f={}){let w=f.namespace??D.appId,F=K$(D),E=F&&w!==F.manifest.storage.namespace?LD("permission_denied",`Requested storage namespace ${w} does not match app namespace ${F.manifest.storage.namespace}.`):Ur(D,"storage","write",w);if(Yr(D,E,"storage","write",w,{key:r,namespace:w}),!E.allowed)return Mr(E);return u.put({appId:D.appId,key:r,namespace:w,operatorId:D.operatorId??null,sessionId:D.sessionId??null,valueJson:A,workerId:D.workerId??null,workspaceId:D.workspaceId??null,at:D.now?.()})}}}}function Ur(D,u,r,A){let f=K$(D);if(!f)return LD("app_not_found",`Soul App is not installed: ${D.appId}`);if(f.status!=="enabled")return LD("app_disabled",`Soul App is not enabled: ${D.appId}`);let w=xh(D,f);if(w)return w;if(u==="engine")return LD("engine_owned_by_host","Soul Apps cannot create raw engine invocations; Host owns engine scheduling and audit.");if(u==="connector"&&!(D.enabledConnectorIds??[]).includes(A))return LD("connector_not_enabled",`Connector is not enabled for brokered access: ${A}`);if(!f.manifest.permissions.some((E)=>E.kind===u&&E.action===r&&mh(f,E,A)))return LD("permission_denied",`Soul App manifest does not declare ${u}:${A}:${r}.`);return{allowed:!0,code:"allowed",reason:"Permission is declared in the Soul App manifest and enforced by Host broker."}}function xh(D,u){if(!D.workerId&&!D.workspaceId&&!D.sessionId)return null;let r=D.workerId?PD(D.workerId):null;if(D.workerId&&!r)return LD("scope_not_found",`Worker scope was not found: ${D.workerId}`);if(r&&r.soulId!==u.appId)return LD("scope_mismatch",`Worker ${r.id} belongs to ${r.soulId}, not ${u.appId}.`);let A=D.workspaceId?Du(D.workspaceId):null;if(D.workspaceId&&!A)return LD("scope_not_found",`Workspace scope was not found: ${D.workspaceId}`);if(A&&D.workerId&&A.workerId!==D.workerId)return LD("scope_mismatch",`Workspace ${A.id} belongs to worker ${A.workerId}, not ${D.workerId}.`);if(A&&!D.workerId){let w=PD(A.workerId);if(!w)return LD("scope_not_found",`Workspace worker was not found: ${A.workerId}`);if(w.soulId!==u.appId)return LD("scope_mismatch",`Workspace ${A.id} belongs to ${w.soulId}, not ${u.appId}.`)}let f=D.sessionId?wu(D.sessionId):null;if(D.sessionId&&!f)return LD("scope_not_found",`Session scope was not found: ${D.sessionId}`);if(f&&D.workerId&&f.workerId!==D.workerId)return LD("scope_mismatch",`Session ${f.id} belongs to worker ${f.workerId}, not ${D.workerId}.`);if(f&&D.workspaceId&&f.workspaceId!==D.workspaceId)return LD("scope_mismatch",`Session ${f.id} belongs to workspace ${f.workspaceId}, not ${D.workspaceId}.`);if(f&&!D.workerId){let w=PD(f.workerId);if(!w)return LD("scope_not_found",`Session worker was not found: ${f.workerId}`);if(w.soulId!==u.appId)return LD("scope_mismatch",`Session ${f.id} belongs to ${w.soulId}, not ${u.appId}.`)}return null}function mh(D,u,r){if(u.target===r)return!0;if(u.kind==="review"&&u.action==="create")return!0;if(u.kind==="artifact"&&D.manifest.artifactTypes.some((A)=>A.id===r))return!0;if(u.kind==="memory"&&r===D.manifest.memory.namespace)return!0;return!1}function Yr(D,u,r,A,f,w){HE({action:A,appId:D.appId,decision:u.allowed?"allowed":"denied",operatorId:D.operatorId??null,reason:u.reason,requestJson:w,sessionId:D.sessionId??null,target:f,targetKind:r,workerId:D.workerId??null,workspaceId:D.workspaceId??null,at:D.now?.()})}function K$(D){return Ou(D.appId)}function LD(D,u){return{allowed:!1,code:D,reason:u}}function Mr(D){return{decision:D.allowed?LD("permission_denied","Broker request was denied."):D}}var nB=W(()=>{nr();i1();_B();V$()});var h$=W(()=>{bE();zE();FB();nB();S$();i1();V$();C$();H$();P$()});function q$(D){if(D===null||typeof D!=="object")return!1;let u=Object.getPrototypeOf(D);if(u!==null&&u!==Object.prototype&&Object.getPrototypeOf(u)!==null)return!1;if(Symbol.iterator in D)return!1;if(Symbol.toStringTag in D)return Object.prototype.toString.call(D)==="[object Module]";return!0}function j$(D,u,r=".",A){if(!q$(u))return j$(D,{},r,A);let f=Object.assign({},u);for(let w in D){if(w==="__proto__"||w==="constructor")continue;let F=D[w];if(F===null||F===void 0)continue;if(A&&A(f,w,F,r))continue;if(Array.isArray(F)&&Array.isArray(f[w]))f[w]=[...F,...f[w]];else if(q$(F)&&q$(f[w]))f[w]=j$(F,f[w],(r?`${r}.`:"")+w.toString(),A);else f[w]=F}return f}function SN(D){return(...u)=>u.reduce((r,A)=>j$(r,A,"",D),{})}function RN(D){return Object.prototype.toString.call(D)==="[object Object]"}function nN(D){if(!RN(D))return!1;if(!D.message&&!D.args)return!1;if(D.stack)return!1;return!0}class ZD{options;_lastLog;_mockFn;constructor(D={}){let u=D.types||z$;this.options=_N({...D,defaults:{...D.defaults},level:s$(D.level,u),reporters:[...D.reporters||[]]},{types:z$,throttle:1000,throttleMin:5,formatOptions:{date:!0,colors:!1,compact:!0}});for(let r in u){let A={type:r,...this.options.defaults,...u[r]};this[r]=this._wrapLogFn(A),this[r].raw=this._wrapLogFn(A,!0)}if(this.options.mockFn)this.mockTypes();this._lastLog={}}get level(){return this.options.level}set level(D){this.options.level=s$(D,this.options.types,this.options.level)}prompt(D,u){if(!this.options.prompt)throw Error("prompt is not supported!");return this.options.prompt(D,u)}create(D){let u=new ZD({...this.options,...D});if(this._mockFn)u.mockTypes(this._mockFn);return u}withDefaults(D){return this.create({...this.options,defaults:{...this.options.defaults,...D}})}withTag(D){return this.withDefaults({tag:this.options.defaults.tag?this.options.defaults.tag+":"+D:D})}addReporter(D){return this.options.reporters.push(D),this}removeReporter(D){if(D){let u=this.options.reporters.indexOf(D);if(u!==-1)return this.options.reporters.splice(u,1)}else this.options.reporters.splice(0);return this}setReporters(D){return this.options.reporters=Array.isArray(D)?D:[D],this}wrapAll(){this.wrapConsole(),this.wrapStd()}restoreAll(){this.restoreConsole(),this.restoreStd()}wrapConsole(){for(let D in this.options.types){if(!console["__"+D])console["__"+D]=console[D];console[D]=this[D].raw}}restoreConsole(){for(let D in this.options.types)if(console["__"+D])console[D]=console["__"+D],delete console["__"+D]}wrapStd(){this._wrapStream(this.options.stdout,"log"),this._wrapStream(this.options.stderr,"log")}_wrapStream(D,u){if(!D)return;if(!D.__write)D.__write=D.write;D.write=(r)=>{this[u].raw(String(r).trim())}}restoreStd(){this._restoreStream(this.options.stdout),this._restoreStream(this.options.stderr)}_restoreStream(D){if(!D)return;if(D.__write)D.write=D.__write,delete D.__write}pauseLogs(){b$=!0}resumeLogs(){b$=!1;let D=iB.splice(0);for(let u of D)u[0]._logFn(u[1],u[2])}mockTypes(D){let u=D||this.options.mockFn;if(this._mockFn=u,typeof u!=="function")return;for(let r in this.options.types)this[r]=u(r,this.options.types[r])||this[r],this[r].raw=this[r]}_wrapLogFn(D,u){return(...r)=>{if(b$){iB.push([this,D,r,u]);return}return this._logFn(D,r,u)}}_logFn(D,u,r){if((D.level||0)>this.level)return!1;let A={date:new Date,args:[],...D,level:s$(D.level,this.options.types)};if(!r&&u.length===1&&nN(u[0]))Object.assign(A,u[0]);else A.args=[...u];if(A.message)A.args.unshift(A.message),delete A.message;if(A.additional){if(!Array.isArray(A.additional))A.additional=A.additional.split(`
1515
1515
  `);A.args.push(`
1516
1516
  `+A.additional.join(`
1517
- `)),delete A.additional}A.type=typeof A.type==="string"?A.type.toLowerCase():"log",A.tag=typeof A.tag==="string"?A.tag:"";let f=(F=!1)=>{let E=(this._lastLog.count||0)-this.options.throttleMin;if(this._lastLog.object&&E>0){let $=[...this._lastLog.object.args];if(E>1)$.push(`(repeated ${E} times)`);this._log({...this._lastLog.object,args:$}),this._lastLog.count=1}if(F)this._lastLog.object=A,this._log(A)};clearTimeout(this._lastLog.timeout);let w=this._lastLog.time&&A.date?A.date.getTime()-this._lastLog.time.getTime():0;if(this._lastLog.time=A.date,w<this.options.throttle)try{let F=JSON.stringify([A.type,A.tag,A.args]),E=this._lastLog.serialized===F;if(this._lastLog.serialized=F,E){if(this._lastLog.count=(this._lastLog.count||0)+1,this._lastLog.count>this.options.throttleMin){this._lastLog.timeout=setTimeout(f,this.options.throttle);return}}}catch{}f(!0)}_log(D){for(let u of this.options.reporters)u.log(D,{options:this.options})}}function U$(D,u={},r=3){if(D===void 0)return r;if(typeof D==="number")return D;if(u[D]&&u[D].level!==void 0)return u[D].level;return r}function uJ(D={}){return new vD(D)}var yD,X$,Lh,n$=!1,DJ;var M$=W(()=>{yD={silent:Number.NEGATIVE_INFINITY,fatal:0,error:0,warn:1,log:2,info:3,success:3,fail:3,ready:3,start:3,box:3,debug:4,trace:5,verbose:Number.POSITIVE_INFINITY},X$={silent:{level:-1},fatal:{level:yD.fatal},error:{level:yD.error},warn:{level:yD.warn},log:{level:yD.log},info:{level:yD.info},success:{level:yD.success},fail:{level:yD.fail},ready:{level:yD.info},start:{level:yD.info},box:{level:yD.info},debug:{level:yD.debug},trace:{level:yD.trace},verbose:{level:yD.verbose}};Lh=Qh();DJ=[];vD.prototype.add=vD.prototype.addReporter;vD.prototype.remove=vD.prototype.removeReporter;vD.prototype.clear=vD.prototype.removeReporter;vD.prototype.withScope=vD.prototype.withTag;vD.prototype.mock=vD.prototype.mockTypes;vD.prototype.pause=vD.prototype.pauseLogs;vD.prototype.resume=vD.prototype.resumeLogs});import{formatWithOptions as rJ}from"util";import{sep as zh}from"path";function P$(D,u){let r=process.cwd()+zh;return D.split(`
1517
+ `)),delete A.additional}A.type=typeof A.type==="string"?A.type.toLowerCase():"log",A.tag=typeof A.tag==="string"?A.tag:"";let f=(F=!1)=>{let E=(this._lastLog.count||0)-this.options.throttleMin;if(this._lastLog.object&&E>0){let $=[...this._lastLog.object.args];if(E>1)$.push(`(repeated ${E} times)`);this._log({...this._lastLog.object,args:$}),this._lastLog.count=1}if(F)this._lastLog.object=A,this._log(A)};clearTimeout(this._lastLog.timeout);let w=this._lastLog.time&&A.date?A.date.getTime()-this._lastLog.time.getTime():0;if(this._lastLog.time=A.date,w<this.options.throttle)try{let F=JSON.stringify([A.type,A.tag,A.args]),E=this._lastLog.serialized===F;if(this._lastLog.serialized=F,E){if(this._lastLog.count=(this._lastLog.count||0)+1,this._lastLog.count>this.options.throttleMin){this._lastLog.timeout=setTimeout(f,this.options.throttle);return}}}catch{}f(!0)}_log(D){for(let u of this.options.reporters)u.log(D,{options:this.options})}}function s$(D,u={},r=3){if(D===void 0)return r;if(typeof D==="number")return D;if(u[D]&&u[D].level!==void 0)return u[D].level;return r}function UB(D={}){return new ZD(D)}var yD,z$,_N,b$=!1,iB;var T$=W(()=>{yD={silent:Number.NEGATIVE_INFINITY,fatal:0,error:0,warn:1,log:2,info:3,success:3,fail:3,ready:3,start:3,box:3,debug:4,trace:5,verbose:Number.POSITIVE_INFINITY},z$={silent:{level:-1},fatal:{level:yD.fatal},error:{level:yD.error},warn:{level:yD.warn},log:{level:yD.log},info:{level:yD.info},success:{level:yD.success},fail:{level:yD.fail},ready:{level:yD.info},start:{level:yD.info},box:{level:yD.info},debug:{level:yD.debug},trace:{level:yD.trace},verbose:{level:yD.verbose}};_N=SN();iB=[];ZD.prototype.add=ZD.prototype.addReporter;ZD.prototype.remove=ZD.prototype.removeReporter;ZD.prototype.clear=ZD.prototype.removeReporter;ZD.prototype.withScope=ZD.prototype.withTag;ZD.prototype.mock=ZD.prototype.mockTypes;ZD.prototype.pause=ZD.prototype.pauseLogs;ZD.prototype.resume=ZD.prototype.resumeLogs});import{formatWithOptions as YB}from"util";import{sep as BN}from"path";function Z$(D,u){let r=process.cwd()+BN;return D.split(`
1518
1518
  `).splice(u.split(`
1519
- `).length).map((f)=>f.trim().replace("file://","").replace(r,""))}function jh(D,u){return(u.__write||u.write).call(u,D)}class yf{formatStack(D,u,r){let A=" ".repeat((r?.errorLevel||0)+1);return A+P$(D,u).join(`
1520
- ${A}`)}formatError(D,u){let r=D.message??rJ(u,D),A=D.stack?this.formatStack(D.stack,r,u):"",f=u?.errorLevel||0,w=f>0?`${" ".repeat(f)}[cause]: `:"",F=D.cause?`
1519
+ `).length).map((f)=>f.trim().replace("file://","").replace(r,""))}function WN(D,u){return(u.__write||u.write).call(u,D)}class mf{formatStack(D,u,r){let A=" ".repeat((r?.errorLevel||0)+1);return A+Z$(D,u).join(`
1520
+ ${A}`)}formatError(D,u){let r=D.message??YB(u,D),A=D.stack?this.formatStack(D.stack,r,u):"",f=u?.errorLevel||0,w=f>0?`${" ".repeat(f)}[cause]: `:"",F=D.cause?`
1521
1521
 
1522
1522
  `+this.formatError(D.cause,{...u,errorLevel:f+1}):"";return w+r+`
1523
- `+A+F}formatArgs(D,u){let r=D.map((A)=>{if(A&&typeof A.stack==="string")return this.formatError(A,u);return A});return rJ(u,...r)}formatDate(D,u){return u.date?D.toLocaleTimeString():""}filterAndJoin(D){return D.filter(Boolean).join(" ")}formatLogObj(D,u){let r=this.formatArgs(D.args,u);if(D.type==="box")return`
1524
- `+[O$(D.tag),D.title&&D.title,...r.split(`
1523
+ `+A+F}formatArgs(D,u){let r=D.map((A)=>{if(A&&typeof A.stack==="string")return this.formatError(A,u);return A});return YB(u,...r)}formatDate(D,u){return u.date?D.toLocaleTimeString():""}filterAndJoin(D){return D.filter(Boolean).join(" ")}formatLogObj(D,u){let r=this.formatArgs(D.args,u);if(D.type==="box")return`
1524
+ `+[v$(D.tag),D.title&&D.title,...r.split(`
1525
1525
  `)].filter(Boolean).map((A)=>" > "+A).join(`
1526
1526
  `)+`
1527
- `;return this.filterAndJoin([O$(D.type),O$(D.tag),r])}log(D,u){let r=this.formatLogObj(D,{columns:u.options.stdout.columns||0,...u.options.formatOptions});return jh(r+`
1528
- `,D.level<2?u.options.stderr||process.stderr:u.options.stdout||process.stdout)}}var O$=(D)=>D?`[${D}]`:"";var AJ=()=>{};import*as lf from"tty";function EJ(D,u,r,A,f=u.slice(0,Math.max(0,D))+A,w=u.slice(Math.max(0,D+r.length)),F=w.indexOf(r)){return f+(F<0?w:EJ(F,w,r,A))}function lh(D,u,r,A,f){return D<0?r+u+A:r+EJ(D,u,A,f)+A}function ch(D,u,r=D,A=D.length+1){return(f)=>f||!(f===""||f===void 0)?lh((""+f).indexOf(u,A),f,D,u,r):""}function m(D,u,r){return ch(`\x1B[${D}m`,`\x1B[${u}m`,r)}function th(D=yh){return D?fJ:Object.fromEntries(Object.keys(fJ).map((u)=>[u,String]))}function xh(D,u="reset"){return Du[D]||Du[u]}function C0(D){return D.replace(new RegExp(mh,"g"),"")}function gJ(D,u={}){let r={...u,style:{...ph,...u.style}},A=D.split(`
1529
- `),f=[],w=xh(r.style.borderColor),F={...typeof r.style.borderStyle==="string"?FJ[r.style.borderStyle]||FJ.solid:r.style.borderStyle};if(w)for(let J in F)F[J]=w(F[J]);let E=r.style.padding%2===0?r.style.padding:r.style.padding+1,$=A.length+E,g=Math.max(...A.map((J)=>C0(J).length),r.title?C0(r.title).length:0)+E,R=g+E,S=r.style.marginLeft>0?" ".repeat(r.style.marginLeft):"";if(r.style.marginTop>0)f.push("".repeat(r.style.marginTop));if(r.title){let J=w?w(r.title):r.title,H=F.h.repeat(Math.floor((g-C0(r.title).length)/2)),G=F.h.repeat(g-C0(r.title).length-C0(H).length+E);f.push(`${S}${F.tl}${H}${J}${G}${F.tr}`)}else f.push(`${S}${F.tl}${F.h.repeat(R)}${F.tr}`);let B=r.style.valign==="center"?Math.floor(($-A.length)/2):r.style.valign==="top"?$-A.length-E:$-A.length;for(let J=0;J<$;J++)if(J<B||J>=B+A.length)f.push(`${S}${F.v}${" ".repeat(R)}${F.v}`);else{let H=A[J-B],G=" ".repeat(E),U=" ".repeat(g-C0(H).length);f.push(`${S}${F.v}${G}${H}${U}${F.v}`)}if(f.push(`${S}${F.bl}${F.h.repeat(R)}${F.br}`),r.style.marginBottom>0)f.push("".repeat(r.style.marginBottom));return f.join(`
1530
- `)}var H0,wJ,Th,vh,sh,Zh,$J,oh,dh,yh,fJ,Du,mh,FJ,ph;var _J=W(()=>{({env:H0={},argv:wJ=[],platform:Th=""}=typeof process>"u"?{}:process),vh="NO_COLOR"in H0||wJ.includes("--no-color"),sh="FORCE_COLOR"in H0||wJ.includes("--color"),Zh=Th==="win32",$J=H0.TERM==="dumb",oh=lf&&lf.isatty&&lf.isatty(1)&&H0.TERM&&!$J,dh="CI"in H0&&(("GITHUB_ACTIONS"in H0)||("GITLAB_CI"in H0)||("CIRCLECI"in H0)),yh=!vh&&(sh||Zh&&!$J||oh||dh);fJ={reset:m(0,0),bold:m(1,22,"\x1B[22m\x1B[1m"),dim:m(2,22,"\x1B[22m\x1B[2m"),italic:m(3,23),underline:m(4,24),inverse:m(7,27),hidden:m(8,28),strikethrough:m(9,29),black:m(30,39),red:m(31,39),green:m(32,39),yellow:m(33,39),blue:m(34,39),magenta:m(35,39),cyan:m(36,39),white:m(37,39),gray:m(90,39),bgBlack:m(40,49),bgRed:m(41,49),bgGreen:m(42,49),bgYellow:m(43,49),bgBlue:m(44,49),bgMagenta:m(45,49),bgCyan:m(46,49),bgWhite:m(47,49),blackBright:m(90,39),redBright:m(91,39),greenBright:m(92,39),yellowBright:m(93,39),blueBright:m(94,39),magentaBright:m(95,39),cyanBright:m(96,39),whiteBright:m(97,39),bgBlackBright:m(100,49),bgRedBright:m(101,49),bgGreenBright:m(102,49),bgYellowBright:m(103,49),bgBlueBright:m(104,49),bgMagentaBright:m(105,49),bgCyanBright:m(106,49),bgWhiteBright:m(107,49)};Du=th();mh=[String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`,String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`].join("|");FJ={solid:{tl:"\u250C",tr:"\u2510",bl:"\u2514",br:"\u2518",h:"\u2500",v:"\u2502"},double:{tl:"\u2554",tr:"\u2557",bl:"\u255A",br:"\u255D",h:"\u2550",v:"\u2551"},doubleSingle:{tl:"\u2553",tr:"\u2556",bl:"\u2559",br:"\u255C",h:"\u2500",v:"\u2551"},doubleSingleRounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2551"},singleThick:{tl:"\u250F",tr:"\u2513",bl:"\u2517",br:"\u251B",h:"\u2501",v:"\u2503"},singleDouble:{tl:"\u2552",tr:"\u2555",bl:"\u2558",br:"\u255B",h:"\u2550",v:"\u2502"},singleDoubleRounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2550",v:"\u2502"},rounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502"}},ph={borderColor:"white",borderStyle:"rounded",valign:"center",padding:2,marginLeft:1,marginTop:1,marginBottom:1}});var qJ={};dA(qJ,{prompt:()=>LJ,kCancel:()=>QJ});import tu,{stdin as ah,stdout as eh}from"process";import RJ from"readline";import{WriteStream as DN}from"tty";function uN(D){return D&&D.__esModule&&Object.prototype.hasOwnProperty.call(D,"default")?D.default:D}function rN(){if(SJ)return i$;SJ=1;let D="\x1B",u=`${D}[`,r="\x07",A={to(F,E){if(!E)return`${u}${F+1}G`;return`${u}${E+1};${F+1}H`},move(F,E){let $="";if(F<0)$+=`${u}${-F}D`;else if(F>0)$+=`${u}${F}C`;if(E<0)$+=`${u}${-E}A`;else if(E>0)$+=`${u}${E}B`;return $},up:(F=1)=>`${u}${F}A`,down:(F=1)=>`${u}${F}B`,forward:(F=1)=>`${u}${F}C`,backward:(F=1)=>`${u}${F}D`,nextLine:(F=1)=>`${u}E`.repeat(F),prevLine:(F=1)=>`${u}F`.repeat(F),left:`${u}G`,hide:`${u}?25l`,show:`${u}?25h`,save:`${D}7`,restore:`${D}8`},f={up:(F=1)=>`${u}S`.repeat(F),down:(F=1)=>`${u}T`.repeat(F)},w={screen:`${u}2J`,up:(F=1)=>`${u}1J`.repeat(F),down:(F=1)=>`${u}J`.repeat(F),line:`${u}2K`,lineEnd:`${u}K`,lineStart:`${u}1K`,lines(F){let E="";for(let $=0;$<F;$++)E+=this.line+($<F-1?A.up():"");if(F)E+=A.left;return E}};return i$={cursor:A,scroll:f,erase:w,beep:r},i$}function AN(){if(BJ)return cf.exports;BJ=1;let D=process||{},u=D.argv||[],r=D.env||{},A=!(!!r.NO_COLOR||u.includes("--no-color"))&&(!!r.FORCE_COLOR||u.includes("--color")||D.platform==="win32"||(D.stdout||{}).isTTY&&r.TERM!=="dumb"||!!r.CI),f=(E,$,g=E)=>(R)=>{let S=""+R,B=S.indexOf($,E.length);return~B?E+w(S,$,g,B)+$:E+S+$},w=(E,$,g,R)=>{let S="",B=0;do S+=E.substring(B,R)+g,B=R+$.length,R=E.indexOf($,B);while(~R);return S+E.substring(B)},F=(E=A)=>{let $=E?f:()=>String;return{isColorSupported:E,reset:$("\x1B[0m","\x1B[0m"),bold:$("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:$("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:$("\x1B[3m","\x1B[23m"),underline:$("\x1B[4m","\x1B[24m"),inverse:$("\x1B[7m","\x1B[27m"),hidden:$("\x1B[8m","\x1B[28m"),strikethrough:$("\x1B[9m","\x1B[29m"),black:$("\x1B[30m","\x1B[39m"),red:$("\x1B[31m","\x1B[39m"),green:$("\x1B[32m","\x1B[39m"),yellow:$("\x1B[33m","\x1B[39m"),blue:$("\x1B[34m","\x1B[39m"),magenta:$("\x1B[35m","\x1B[39m"),cyan:$("\x1B[36m","\x1B[39m"),white:$("\x1B[37m","\x1B[39m"),gray:$("\x1B[90m","\x1B[39m"),bgBlack:$("\x1B[40m","\x1B[49m"),bgRed:$("\x1B[41m","\x1B[49m"),bgGreen:$("\x1B[42m","\x1B[49m"),bgYellow:$("\x1B[43m","\x1B[49m"),bgBlue:$("\x1B[44m","\x1B[49m"),bgMagenta:$("\x1B[45m","\x1B[49m"),bgCyan:$("\x1B[46m","\x1B[49m"),bgWhite:$("\x1B[47m","\x1B[49m"),blackBright:$("\x1B[90m","\x1B[39m"),redBright:$("\x1B[91m","\x1B[39m"),greenBright:$("\x1B[92m","\x1B[39m"),yellowBright:$("\x1B[93m","\x1B[39m"),blueBright:$("\x1B[94m","\x1B[39m"),magentaBright:$("\x1B[95m","\x1B[39m"),cyanBright:$("\x1B[96m","\x1B[39m"),whiteBright:$("\x1B[97m","\x1B[39m"),bgBlackBright:$("\x1B[100m","\x1B[49m"),bgRedBright:$("\x1B[101m","\x1B[49m"),bgGreenBright:$("\x1B[102m","\x1B[49m"),bgYellowBright:$("\x1B[103m","\x1B[49m"),bgBlueBright:$("\x1B[104m","\x1B[49m"),bgMagentaBright:$("\x1B[105m","\x1B[49m"),bgCyanBright:$("\x1B[106m","\x1B[49m"),bgWhiteBright:$("\x1B[107m","\x1B[49m")}};return cf.exports=F(),cf.exports.createColors=F,cf.exports}function FN({onlyFirst:D=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,D?void 0:"g")}function OJ(D){if(typeof D!="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(wN,"")}function PJ(D){return D&&D.__esModule&&Object.prototype.hasOwnProperty.call(D,"default")?D.default:D}function YA(D,u={}){if(typeof D!="string"||D.length===0||(u={ambiguousIsNarrow:!0,...u},D=OJ(D),D.length===0))return 0;D=D.replace(_N()," ");let r=u.ambiguousIsNarrow?1:2,A=0;for(let f of D){let w=f.codePointAt(0);if(w<=31||w>=127&&w<=159||w>=768&&w<=879)continue;switch(EN.eastAsianWidth(f)){case"F":case"W":A+=2;break;case"A":A+=r;break;default:A+=1}}return A}function BN(){let D=new Map;for(let[u,r]of Object.entries(HD)){for(let[A,f]of Object.entries(r))HD[A]={open:`\x1B[${f[0]}m`,close:`\x1B[${f[1]}m`},r[A]=HD[A],D.set(f[0],f[1]);Object.defineProperty(HD,u,{value:r,enumerable:!1})}return Object.defineProperty(HD,"codes",{value:D,enumerable:!1}),HD.color.close="\x1B[39m",HD.bgColor.close="\x1B[49m",HD.color.ansi=JJ(),HD.color.ansi256=WJ(),HD.color.ansi16m=GJ(),HD.bgColor.ansi=JJ(k$),HD.bgColor.ansi256=WJ(k$),HD.bgColor.ansi16m=GJ(k$),Object.defineProperties(HD,{rgbToAnsi256:{value:(u,r,A)=>u===r&&r===A?u<8?16:u>248?231:Math.round((u-8)/247*24)+232:16+36*Math.round(u/255*5)+6*Math.round(r/255*5)+Math.round(A/255*5),enumerable:!1},hexToRgb:{value:(u)=>{let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));if(!r)return[0,0,0];let[A]=r;A.length===3&&(A=[...A].map((w)=>w+w).join(""));let f=Number.parseInt(A,16);return[f>>16&255,f>>8&255,f&255]},enumerable:!1},hexToAnsi256:{value:(u)=>HD.rgbToAnsi256(...HD.hexToRgb(u)),enumerable:!1},ansi256ToAnsi:{value:(u)=>{if(u<8)return 30+u;if(u<16)return 90+(u-8);let r,A,f;if(u>=232)r=((u-232)*10+8)/255,A=r,f=r;else{u-=16;let E=u%36;r=Math.floor(u/36)/5,A=Math.floor(E/6)/5,f=E%6/5}let w=Math.max(r,A,f)*2;if(w===0)return 30;let F=30+(Math.round(f)<<2|Math.round(A)<<1|Math.round(r));return w===2&&(F+=60),F},enumerable:!1},rgbToAnsi:{value:(u,r,A)=>HD.ansi256ToAnsi(HD.rgbToAnsi256(u,r,A)),enumerable:!1},hexToAnsi:{value:(u)=>HD.ansi256ToAnsi(HD.hexToAnsi256(u)),enumerable:!1}}),HD}function nJ(D,u,r){return String(D).normalize().replace(/\r\n/g,`
1527
+ `;return this.filterAndJoin([v$(D.type),v$(D.tag),r])}log(D,u){let r=this.formatLogObj(D,{columns:u.options.stdout.columns||0,...u.options.formatOptions});return WN(r+`
1528
+ `,D.level<2?u.options.stderr||process.stderr:u.options.stdout||process.stdout)}}var v$=(D)=>D?`[${D}]`:"";var MB=()=>{};import*as af from"tty";function VB(D,u,r,A,f=u.slice(0,Math.max(0,D))+A,w=u.slice(Math.max(0,D+r.length)),F=w.indexOf(r)){return f+(F<0?w:VB(F,w,r,A))}function YN(D,u,r,A,f){return D<0?r+u+A:r+VB(D,u,A,f)+A}function MN(D,u,r=D,A=D.length+1){return(f)=>f||!(f===""||f===void 0)?YN((""+f).indexOf(u,A),f,D,u,r):""}function x(D,u,r){return MN(`\x1B[${D}m`,`\x1B[${u}m`,r)}function ON(D=UN){return D?OB:Object.fromEntries(Object.keys(OB).map((u)=>[u,String]))}function PN(D,u="reset"){return ru[D]||ru[u]}function G0(D){return D.replace(new RegExp(kN,"g"),"")}function KB(D,u={}){let r={...u,style:{...IN,...u.style}},A=D.split(`
1529
+ `),f=[],w=PN(r.style.borderColor),F={...typeof r.style.borderStyle==="string"?PB[r.style.borderStyle]||PB.solid:r.style.borderStyle};if(w)for(let B in F)F[B]=w(F[B]);let E=r.style.padding%2===0?r.style.padding:r.style.padding+1,$=A.length+E,g=Math.max(...A.map((B)=>G0(B).length),r.title?G0(r.title).length:0)+E,_=g+E,R=r.style.marginLeft>0?" ".repeat(r.style.marginLeft):"";if(r.style.marginTop>0)f.push("".repeat(r.style.marginTop));if(r.title){let B=w?w(r.title):r.title,C=F.h.repeat(Math.floor((g-G0(r.title).length)/2)),J=F.h.repeat(g-G0(r.title).length-G0(C).length+E);f.push(`${R}${F.tl}${C}${B}${J}${F.tr}`)}else f.push(`${R}${F.tl}${F.h.repeat(_)}${F.tr}`);let n=r.style.valign==="center"?Math.floor(($-A.length)/2):r.style.valign==="top"?$-A.length-E:$-A.length;for(let B=0;B<$;B++)if(B<n||B>=n+A.length)f.push(`${R}${F.v}${" ".repeat(_)}${F.v}`);else{let C=A[B-n],J=" ".repeat(E),X=" ".repeat(g-G0(C).length);f.push(`${R}${F.v}${J}${C}${X}${F.v}`)}if(f.push(`${R}${F.bl}${F.h.repeat(_)}${F.br}`),r.style.marginBottom>0)f.push("".repeat(r.style.marginBottom));return f.join(`
1530
+ `)}var C0,kB,JN,GN,CN,HN,IB,XN,iN,UN,OB,ru,kN,PB,IN;var hB=W(()=>{({env:C0={},argv:kB=[],platform:JN=""}=typeof process>"u"?{}:process),GN="NO_COLOR"in C0||kB.includes("--no-color"),CN="FORCE_COLOR"in C0||kB.includes("--color"),HN=JN==="win32",IB=C0.TERM==="dumb",XN=af&&af.isatty&&af.isatty(1)&&C0.TERM&&!IB,iN="CI"in C0&&(("GITHUB_ACTIONS"in C0)||("GITLAB_CI"in C0)||("CIRCLECI"in C0)),UN=!GN&&(CN||HN&&!IB||XN||iN);OB={reset:x(0,0),bold:x(1,22,"\x1B[22m\x1B[1m"),dim:x(2,22,"\x1B[22m\x1B[2m"),italic:x(3,23),underline:x(4,24),inverse:x(7,27),hidden:x(8,28),strikethrough:x(9,29),black:x(30,39),red:x(31,39),green:x(32,39),yellow:x(33,39),blue:x(34,39),magenta:x(35,39),cyan:x(36,39),white:x(37,39),gray:x(90,39),bgBlack:x(40,49),bgRed:x(41,49),bgGreen:x(42,49),bgYellow:x(43,49),bgBlue:x(44,49),bgMagenta:x(45,49),bgCyan:x(46,49),bgWhite:x(47,49),blackBright:x(90,39),redBright:x(91,39),greenBright:x(92,39),yellowBright:x(93,39),blueBright:x(94,39),magentaBright:x(95,39),cyanBright:x(96,39),whiteBright:x(97,39),bgBlackBright:x(100,49),bgRedBright:x(101,49),bgGreenBright:x(102,49),bgYellowBright:x(103,49),bgBlueBright:x(104,49),bgMagentaBright:x(105,49),bgCyanBright:x(106,49),bgWhiteBright:x(107,49)};ru=ON();kN=[String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`,String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`].join("|");PB={solid:{tl:"\u250C",tr:"\u2510",bl:"\u2514",br:"\u2518",h:"\u2500",v:"\u2502"},double:{tl:"\u2554",tr:"\u2557",bl:"\u255A",br:"\u255D",h:"\u2550",v:"\u2551"},doubleSingle:{tl:"\u2553",tr:"\u2556",bl:"\u2559",br:"\u255C",h:"\u2500",v:"\u2551"},doubleSingleRounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2551"},singleThick:{tl:"\u250F",tr:"\u2513",bl:"\u2517",br:"\u251B",h:"\u2501",v:"\u2503"},singleDouble:{tl:"\u2552",tr:"\u2555",bl:"\u2558",br:"\u255B",h:"\u2550",v:"\u2502"},singleDoubleRounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2550",v:"\u2502"},rounded:{tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502"}},IN={borderColor:"white",borderStyle:"rounded",valign:"center",padding:2,marginLeft:1,marginTop:1,marginBottom:1}});var rW={};t1(rW,{prompt:()=>uW,kCancel:()=>DW});import xu,{stdin as VN,stdout as KN}from"process";import NB from"readline";import{WriteStream as hN}from"tty";function NN(D){return D&&D.__esModule&&Object.prototype.hasOwnProperty.call(D,"default")?D.default:D}function QN(){if(QB)return o$;QB=1;let D="\x1B",u=`${D}[`,r="\x07",A={to(F,E){if(!E)return`${u}${F+1}G`;return`${u}${E+1};${F+1}H`},move(F,E){let $="";if(F<0)$+=`${u}${-F}D`;else if(F>0)$+=`${u}${F}C`;if(E<0)$+=`${u}${-E}A`;else if(E>0)$+=`${u}${E}B`;return $},up:(F=1)=>`${u}${F}A`,down:(F=1)=>`${u}${F}B`,forward:(F=1)=>`${u}${F}C`,backward:(F=1)=>`${u}${F}D`,nextLine:(F=1)=>`${u}E`.repeat(F),prevLine:(F=1)=>`${u}F`.repeat(F),left:`${u}G`,hide:`${u}?25l`,show:`${u}?25h`,save:`${D}7`,restore:`${D}8`},f={up:(F=1)=>`${u}S`.repeat(F),down:(F=1)=>`${u}T`.repeat(F)},w={screen:`${u}2J`,up:(F=1)=>`${u}1J`.repeat(F),down:(F=1)=>`${u}J`.repeat(F),line:`${u}2K`,lineEnd:`${u}K`,lineStart:`${u}1K`,lines(F){let E="";for(let $=0;$<F;$++)E+=this.line+($<F-1?A.up():"");if(F)E+=A.left;return E}};return o$={cursor:A,scroll:f,erase:w,beep:r},o$}function LN(){if(LB)return ef.exports;LB=1;let D=process||{},u=D.argv||[],r=D.env||{},A=!(!!r.NO_COLOR||u.includes("--no-color"))&&(!!r.FORCE_COLOR||u.includes("--color")||D.platform==="win32"||(D.stdout||{}).isTTY&&r.TERM!=="dumb"||!!r.CI),f=(E,$,g=E)=>(_)=>{let R=""+_,n=R.indexOf($,E.length);return~n?E+w(R,$,g,n)+$:E+R+$},w=(E,$,g,_)=>{let R="",n=0;do R+=E.substring(n,_)+g,n=_+$.length,_=E.indexOf($,n);while(~_);return R+E.substring(n)},F=(E=A)=>{let $=E?f:()=>String;return{isColorSupported:E,reset:$("\x1B[0m","\x1B[0m"),bold:$("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:$("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:$("\x1B[3m","\x1B[23m"),underline:$("\x1B[4m","\x1B[24m"),inverse:$("\x1B[7m","\x1B[27m"),hidden:$("\x1B[8m","\x1B[28m"),strikethrough:$("\x1B[9m","\x1B[29m"),black:$("\x1B[30m","\x1B[39m"),red:$("\x1B[31m","\x1B[39m"),green:$("\x1B[32m","\x1B[39m"),yellow:$("\x1B[33m","\x1B[39m"),blue:$("\x1B[34m","\x1B[39m"),magenta:$("\x1B[35m","\x1B[39m"),cyan:$("\x1B[36m","\x1B[39m"),white:$("\x1B[37m","\x1B[39m"),gray:$("\x1B[90m","\x1B[39m"),bgBlack:$("\x1B[40m","\x1B[49m"),bgRed:$("\x1B[41m","\x1B[49m"),bgGreen:$("\x1B[42m","\x1B[49m"),bgYellow:$("\x1B[43m","\x1B[49m"),bgBlue:$("\x1B[44m","\x1B[49m"),bgMagenta:$("\x1B[45m","\x1B[49m"),bgCyan:$("\x1B[46m","\x1B[49m"),bgWhite:$("\x1B[47m","\x1B[49m"),blackBright:$("\x1B[90m","\x1B[39m"),redBright:$("\x1B[91m","\x1B[39m"),greenBright:$("\x1B[92m","\x1B[39m"),yellowBright:$("\x1B[93m","\x1B[39m"),blueBright:$("\x1B[94m","\x1B[39m"),magentaBright:$("\x1B[95m","\x1B[39m"),cyanBright:$("\x1B[96m","\x1B[39m"),whiteBright:$("\x1B[97m","\x1B[39m"),bgBlackBright:$("\x1B[100m","\x1B[49m"),bgRedBright:$("\x1B[101m","\x1B[49m"),bgGreenBright:$("\x1B[102m","\x1B[49m"),bgYellowBright:$("\x1B[103m","\x1B[49m"),bgBlueBright:$("\x1B[104m","\x1B[49m"),bgMagentaBright:$("\x1B[105m","\x1B[49m"),bgCyanBright:$("\x1B[106m","\x1B[49m"),bgWhiteBright:$("\x1B[107m","\x1B[49m")}};return ef.exports=F(),ef.exports.createColors=F,ef.exports}function bN({onlyFirst:D=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,D?void 0:"g")}function lB(D){if(typeof D!="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(sN,"")}function yB(D){return D&&D.__esModule&&Object.prototype.hasOwnProperty.call(D,"default")?D.default:D}function O1(D,u={}){if(typeof D!="string"||D.length===0||(u={ambiguousIsNarrow:!0,...u},D=lB(D),D.length===0))return 0;D=D.replace(vN()," ");let r=u.ambiguousIsNarrow?1:2,A=0;for(let f of D){let w=f.codePointAt(0);if(w<=31||w>=127&&w<=159||w>=768&&w<=879)continue;switch(jN.eastAsianWidth(f)){case"F":case"W":A+=2;break;case"A":A+=r;break;default:A+=1}}return A}function dN(){let D=new Map;for(let[u,r]of Object.entries(CD)){for(let[A,f]of Object.entries(r))CD[A]={open:`\x1B[${f[0]}m`,close:`\x1B[${f[1]}m`},r[A]=CD[A],D.set(f[0],f[1]);Object.defineProperty(CD,u,{value:r,enumerable:!1})}return Object.defineProperty(CD,"codes",{value:D,enumerable:!1}),CD.color.close="\x1B[39m",CD.bgColor.close="\x1B[49m",CD.color.ansi=qB(),CD.color.ansi256=bB(),CD.color.ansi16m=sB(),CD.bgColor.ansi=qB(d$),CD.bgColor.ansi256=bB(d$),CD.bgColor.ansi16m=sB(d$),Object.defineProperties(CD,{rgbToAnsi256:{value:(u,r,A)=>u===r&&r===A?u<8?16:u>248?231:Math.round((u-8)/247*24)+232:16+36*Math.round(u/255*5)+6*Math.round(r/255*5)+Math.round(A/255*5),enumerable:!1},hexToRgb:{value:(u)=>{let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));if(!r)return[0,0,0];let[A]=r;A.length===3&&(A=[...A].map((w)=>w+w).join(""));let f=Number.parseInt(A,16);return[f>>16&255,f>>8&255,f&255]},enumerable:!1},hexToAnsi256:{value:(u)=>CD.rgbToAnsi256(...CD.hexToRgb(u)),enumerable:!1},ansi256ToAnsi:{value:(u)=>{if(u<8)return 30+u;if(u<16)return 90+(u-8);let r,A,f;if(u>=232)r=((u-232)*10+8)/255,A=r,f=r;else{u-=16;let E=u%36;r=Math.floor(u/36)/5,A=Math.floor(E/6)/5,f=E%6/5}let w=Math.max(r,A,f)*2;if(w===0)return 30;let F=30+(Math.round(f)<<2|Math.round(A)<<1|Math.round(r));return w===2&&(F+=60),F},enumerable:!1},rgbToAnsi:{value:(u,r,A)=>CD.ansi256ToAnsi(CD.rgbToAnsi256(u,r,A)),enumerable:!1},hexToAnsi:{value:(u)=>CD.ansi256ToAnsi(CD.hexToAnsi256(u)),enumerable:!1}}),CD}function TB(D,u,r){return String(D).normalize().replace(/\r\n/g,`
1531
1531
  `).split(`
1532
- `).map((A)=>nN(A,u,r)).join(`
1533
- `)}function VJ(D,u){if(typeof D=="string")return xf.aliases.get(D)===u;for(let r of D)if(r!==void 0&&VJ(r,u))return!0;return!1}function XN(D,u){if(D===u)return;let r=D.split(`
1532
+ `).map((A)=>xN(A,u,r)).join(`
1533
+ `)}function xB(D,u){if(typeof D=="string")return u3.aliases.get(D)===u;for(let r of D)if(r!==void 0&&xB(r,u))return!0;return!1}function aN(D,u){if(D===u)return;let r=D.split(`
1534
1534
  `),A=u.split(`
1535
- `),f=[];for(let w=0;w<Math.max(r.length,A.length);w++)r[w]!==A[w]&&f.push(w);return f}function tf(D,u){let r=D;r.isTTY&&r.setRawMode(u)}class MA{constructor(D,u=!0){Wu(this,"input"),Wu(this,"output"),Wu(this,"_abortSignal"),Wu(this,"rl"),Wu(this,"opts"),Wu(this,"_render"),Wu(this,"_track",!1),Wu(this,"_prevFrame",""),Wu(this,"_subscribers",new Map),Wu(this,"_cursor",0),Wu(this,"state","initial"),Wu(this,"error",""),Wu(this,"value");let{input:r=ah,output:A=eh,render:f,signal:w,...F}=D;this.opts=F,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=f.bind(this),this._track=u,this._abortSignal=w,this.input=r,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(D,u){let r=this._subscribers.get(D)??[];r.push(u),this._subscribers.set(D,r)}on(D,u){this.setSubscriber(D,{cb:u})}once(D,u){this.setSubscriber(D,{cb:u,once:!0})}emit(D,...u){let r=this._subscribers.get(D)??[],A=[];for(let f of r)f.cb(...u),f.once&&A.push(()=>r.splice(r.indexOf(f),1));for(let f of A)f()}prompt(){return new Promise((D,u)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),D(UJ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}let r=new DN(0);r._write=(A,f,w)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),w()},this.input.pipe(r),this.rl=RJ.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50}),RJ.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),tf(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xu.cursor.show),this.output.off("resize",this.render),tf(this.input,!1),D(this.value)}),this.once("cancel",()=>{this.output.write(xu.cursor.show),this.output.off("resize",this.render),tf(this.input,!1),D(UJ)})})}onKeypress(D,u){if(this.state==="error"&&(this.state="active"),u?.name&&(!this._track&&xf.aliases.has(u.name)&&this.emit("cursor",xf.aliases.get(u.name)),xf.actions.has(u.name)&&this.emit("cursor",u.name)),D&&(D.toLowerCase()==="y"||D.toLowerCase()==="n")&&this.emit("confirm",D.toLowerCase()==="y"),D==="\t"&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),D&&this.emit("key",D.toLowerCase()),u?.name==="return"){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}VJ([D,u?.name,u?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
1536
- `),tf(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let D=nJ(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
1537
- `).length-1;this.output.write(xu.cursor.move(-999,D*-1))}render(){let D=nJ(this._render(this)??"",process.stdout.columns,{hard:!0});if(D!==this._prevFrame){if(this.state==="initial")this.output.write(xu.cursor.hide);else{let u=XN(this._prevFrame,D);if(this.restoreCursor(),u&&u?.length===1){let r=u[0];this.output.write(xu.cursor.move(0,r)),this.output.write(xu.erase.lines(1));let A=D.split(`
1538
- `);this.output.write(A[r]),this._prevFrame=D,this.output.write(xu.cursor.move(0,A.length-r-1));return}if(u&&u?.length>1){let r=u[0];this.output.write(xu.cursor.move(0,r)),this.output.write(xu.erase.down());let A=D.split(`
1535
+ `),f=[];for(let w=0;w<Math.max(r.length,A.length);w++)r[w]!==A[w]&&f.push(w);return f}function D3(D,u){let r=D;r.isTTY&&r.setRawMode(u)}class P1{constructor(D,u=!0){Ju(this,"input"),Ju(this,"output"),Ju(this,"_abortSignal"),Ju(this,"rl"),Ju(this,"opts"),Ju(this,"_render"),Ju(this,"_track",!1),Ju(this,"_prevFrame",""),Ju(this,"_subscribers",new Map),Ju(this,"_cursor",0),Ju(this,"state","initial"),Ju(this,"error",""),Ju(this,"value");let{input:r=VN,output:A=KN,render:f,signal:w,...F}=D;this.opts=F,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=f.bind(this),this._track=u,this._abortSignal=w,this.input=r,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(D,u){let r=this._subscribers.get(D)??[];r.push(u),this._subscribers.set(D,r)}on(D,u){this.setSubscriber(D,{cb:u})}once(D,u){this.setSubscriber(D,{cb:u,once:!0})}emit(D,...u){let r=this._subscribers.get(D)??[],A=[];for(let f of r)f.cb(...u),f.once&&A.push(()=>r.splice(r.indexOf(f),1));for(let f of A)f()}prompt(){return new Promise((D,u)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),D(vB);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}let r=new hN(0);r._write=(A,f,w)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),w()},this.input.pipe(r),this.rl=NB.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50}),NB.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),D3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(mu.cursor.show),this.output.off("resize",this.render),D3(this.input,!1),D(this.value)}),this.once("cancel",()=>{this.output.write(mu.cursor.show),this.output.off("resize",this.render),D3(this.input,!1),D(vB)})})}onKeypress(D,u){if(this.state==="error"&&(this.state="active"),u?.name&&(!this._track&&u3.aliases.has(u.name)&&this.emit("cursor",u3.aliases.get(u.name)),u3.actions.has(u.name)&&this.emit("cursor",u.name)),D&&(D.toLowerCase()==="y"||D.toLowerCase()==="n")&&this.emit("confirm",D.toLowerCase()==="y"),D==="\t"&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),D&&this.emit("key",D.toLowerCase()),u?.name==="return"){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}xB([D,u?.name,u?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
1536
+ `),D3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let D=TB(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
1537
+ `).length-1;this.output.write(mu.cursor.move(-999,D*-1))}render(){let D=TB(this._render(this)??"",process.stdout.columns,{hard:!0});if(D!==this._prevFrame){if(this.state==="initial")this.output.write(mu.cursor.hide);else{let u=aN(this._prevFrame,D);if(this.restoreCursor(),u&&u?.length===1){let r=u[0];this.output.write(mu.cursor.move(0,r)),this.output.write(mu.erase.lines(1));let A=D.split(`
1538
+ `);this.output.write(A[r]),this._prevFrame=D,this.output.write(mu.cursor.move(0,A.length-r-1));return}if(u&&u?.length>1){let r=u[0];this.output.write(mu.cursor.move(0,r)),this.output.write(mu.erase.down());let A=D.split(`
1539
1539
  `).slice(r);this.output.write(A.join(`
1540
- `)),this._prevFrame=D;return}this.output.write(xu.erase.down())}this.output.write(D),this.state==="initial"&&(this.state="active"),this._prevFrame=D}}}function VN(){return tu.platform!=="win32"?tu.env.TERM!=="linux":!!tu.env.CI||!!tu.env.WT_SESSION||!!tu.env.TERMINUS_SUBLIME||tu.env.ConEmuTask==="{cmd::Cmder}"||tu.env.TERM_PROGRAM==="Terminus-Sublime"||tu.env.TERM_PROGRAM==="vscode"||tu.env.TERM==="xterm-256color"||tu.env.TERM==="alacritty"||tu.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}async function LJ(D,u={}){let r=(A)=>{if(typeof A!=="symbol"||A.toString()!=="Symbol(clack:cancel)")return A;switch(u.cancel){case"reject":{let f=Error("Prompt cancelled.");if(f.name="ConsolaPromptCancelledError",Error.captureStackTrace)Error.captureStackTrace(f,LJ);throw f}case"undefined":return;case"null":return null;case"symbol":return QJ;default:case"default":return u.default??u.initial}};if(!u.type||u.type==="text")return await zN({message:D,defaultValue:u.default,placeholder:u.placeholder,initialValue:u.initial}).then(r);if(u.type==="confirm")return await jN({message:D,initialValue:u.initial}).then(r);if(u.type==="select")return await TN({message:D,options:u.options.map((A)=>typeof A==="string"?{value:A,label:A}:A),initialValue:u.initial}).then(r);if(u.type==="multiselect")return await vN({message:D,options:u.options.map((A)=>typeof A==="string"?{value:A,label:A}:A),required:u.required,initialValues:u.initial}).then(r);throw Error(`Unknown prompt type: ${u.type}`)}var i$,SJ,xu,cf,BJ,fN,I,wN,iJ,$N,EN,gN=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\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])|\uD83C[\uDF3E\uDF73\uDF7C\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\uDF7C\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\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\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\uDF7C\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\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\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\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\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-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*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\u26A7\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-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\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[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},_N,k$=10,JJ=(D=0)=>(u)=>`\x1B[${u+D}m`,WJ=(D=0)=>(u)=>`\x1B[${38+D};5;${u}m`,GJ=(D=0)=>(u,r,A)=>`\x1B[${38+D};2;${u};${r};${A}m`,HD,RN,SN,JN,mf,WN=39,N$="\x07",kJ="[",GN="]",IJ="m",Q$,CJ=(D)=>`${mf.values().next().value}${kJ}${D}${IJ}`,HJ=(D)=>`${mf.values().next().value}${Q$}${D}${N$}`,CN=(D)=>D.split(" ").map((u)=>YA(u)),I$=(D,u,r)=>{let A=[...u],f=!1,w=!1,F=YA(OJ(D[D.length-1]));for(let[E,$]of A.entries()){let g=YA($);if(F+g<=r?D[D.length-1]+=$:(D.push($),F=0),mf.has($)&&(f=!0,w=A.slice(E+1).join("").startsWith(Q$)),f){w?$===N$&&(f=!1,w=!1):$===IJ&&(f=!1);continue}F+=g,F===r&&E<A.length-1&&(D.push(""),F=0)}!F&&D[D.length-1].length>0&&D.length>1&&(D[D.length-2]+=D.pop())},HN=(D)=>{let u=D.split(" "),r=u.length;for(;r>0&&!(YA(u[r-1])>0);)r--;return r===u.length?D:u.slice(0,r).join(" ")+u.slice(r).join("")},nN=(D,u,r={})=>{if(r.trim!==!1&&D.trim()==="")return"";let A="",f,w,F=CN(D),E=[""];for(let[g,R]of D.split(" ").entries()){r.trim!==!1&&(E[E.length-1]=E[E.length-1].trimStart());let S=YA(E[E.length-1]);if(g!==0&&(S>=u&&(r.wordWrap===!1||r.trim===!1)&&(E.push(""),S=0),(S>0||r.trim===!1)&&(E[E.length-1]+=" ",S++)),r.hard&&F[g]>u){let B=u-S,J=1+Math.floor((F[g]-B-1)/u);Math.floor((F[g]-1)/u)<J&&E.push(""),I$(E,R,u);continue}if(S+F[g]>u&&S>0&&F[g]>0){if(r.wordWrap===!1&&S<u){I$(E,R,u);continue}E.push("")}if(S+F[g]>u&&r.wordWrap===!1){I$(E,R,u);continue}E[E.length-1]+=R}r.trim!==!1&&(E=E.map((g)=>HN(g)));let $=[...E.join(`
1541
- `)];for(let[g,R]of $.entries()){if(A+=R,mf.has(R)){let{groups:B}=new RegExp(`(?:\\${kJ}(?<code>\\d+)m|\\${Q$}(?<uri>.*)${N$})`).exec($.slice(g).join(""))||{groups:{}};if(B.code!==void 0){let J=Number.parseFloat(B.code);f=J===WN?void 0:J}else B.uri!==void 0&&(w=B.uri.length===0?void 0:B.uri)}let S=JN.codes.get(Number(f));$[g+1]===`
1542
- `?(w&&(A+=HJ("")),f&&S&&(A+=CJ(S))):R===`
1543
- `&&(f&&S&&(A+=CJ(f)),w&&(A+=HJ(w)))}return A},UN,xf,UJ,YN,MN=(D,u,r)=>(u in D)?YN(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,Wu=(D,u,r)=>(MN(D,typeof u!="symbol"?u+"":u,r),r),KJ,ON,PN=(D,u,r)=>(u in D)?ON(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,XJ=(D,u,r)=>(PN(D,typeof u!="symbol"?u+"":u,r),r),iN,kN,IN=(D,u,r)=>(u in D)?kN(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,YJ=(D,u,r)=>(IN(D,typeof u!="symbol"?u+"":u,r),r),hJ,NJ,KN,mu=(D,u)=>KN?D:u,hN,NN,QN,LN,SD,s2,V$,K$,qN,MJ,bN,pf=(D)=>{switch(D){case"initial":case"active":return I.cyan(hN);case"cancel":return I.red(NN);case"error":return I.yellow(QN);case"submit":return I.green(LN)}},h$=(D)=>{let{cursor:u,options:r,style:A}=D,f=D.maxItems??Number.POSITIVE_INFINITY,w=Math.max(process.stdout.rows-4,0),F=Math.min(w,Math.max(f,5)),E=0;u>=E+F-3?E=Math.max(Math.min(u-F+3,r.length-F),0):u<E+2&&(E=Math.max(u-2,0));let $=F<r.length&&E>0,g=F<r.length&&E+F<r.length;return r.slice(E,E+F).map((R,S,B)=>{let J=S===0&&$,H=S===B.length-1&&g;return J||H?I.dim("..."):A(R,S+E===u)})},zN=(D)=>new NJ({validate:D.validate,placeholder:D.placeholder,defaultValue:D.defaultValue,initialValue:D.initialValue,render(){let u=`${I.gray(SD)}
1544
- ${pf(this.state)} ${D.message}
1540
+ `)),this._prevFrame=D;return}this.output.write(mu.erase.down())}this.output.write(D),this.state==="initial"&&(this.state="active"),this._prevFrame=D}}}function wQ(){return xu.platform!=="win32"?xu.env.TERM!=="linux":!!xu.env.CI||!!xu.env.WT_SESSION||!!xu.env.TERMINUS_SUBLIME||xu.env.ConEmuTask==="{cmd::Cmder}"||xu.env.TERM_PROGRAM==="Terminus-Sublime"||xu.env.TERM_PROGRAM==="vscode"||xu.env.TERM==="xterm-256color"||xu.env.TERM==="alacritty"||xu.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}async function uW(D,u={}){let r=(A)=>{if(typeof A!=="symbol"||A.toString()!=="Symbol(clack:cancel)")return A;switch(u.cancel){case"reject":{let f=Error("Prompt cancelled.");if(f.name="ConsolaPromptCancelledError",Error.captureStackTrace)Error.captureStackTrace(f,uW);throw f}case"undefined":return;case"null":return null;case"symbol":return DW;default:case"default":return u.default??u.initial}};if(!u.type||u.type==="text")return await BQ({message:D,defaultValue:u.default,placeholder:u.placeholder,initialValue:u.initial}).then(r);if(u.type==="confirm")return await WQ({message:D,initialValue:u.initial}).then(r);if(u.type==="select")return await JQ({message:D,options:u.options.map((A)=>typeof A==="string"?{value:A,label:A}:A),initialValue:u.initial}).then(r);if(u.type==="multiselect")return await GQ({message:D,options:u.options.map((A)=>typeof A==="string"?{value:A,label:A}:A),required:u.required,initialValues:u.initial}).then(r);throw Error(`Unknown prompt type: ${u.type}`)}var o$,QB,mu,ef,LB,qN,I,sN,cB,zN,jN,TN=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\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])|\uD83C[\uDF3E\uDF73\uDF7C\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\uDF7C\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\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\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\uDF7C\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\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\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\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\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-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*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\u26A7\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-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\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[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},vN,d$=10,qB=(D=0)=>(u)=>`\x1B[${u+D}m`,bB=(D=0)=>(u)=>`\x1B[${38+D};5;${u}m`,sB=(D=0)=>(u,r,A)=>`\x1B[${38+D};2;${u};${r};${A}m`,CD,ZN,oN,lN,r3,yN=39,p$="\x07",tB="[",cN="]",pB="m",x$,zB=(D)=>`${r3.values().next().value}${tB}${D}${pB}`,jB=(D)=>`${r3.values().next().value}${x$}${D}${p$}`,tN=(D)=>D.split(" ").map((u)=>O1(u)),l$=(D,u,r)=>{let A=[...u],f=!1,w=!1,F=O1(lB(D[D.length-1]));for(let[E,$]of A.entries()){let g=O1($);if(F+g<=r?D[D.length-1]+=$:(D.push($),F=0),r3.has($)&&(f=!0,w=A.slice(E+1).join("").startsWith(x$)),f){w?$===p$&&(f=!1,w=!1):$===pB&&(f=!1);continue}F+=g,F===r&&E<A.length-1&&(D.push(""),F=0)}!F&&D[D.length-1].length>0&&D.length>1&&(D[D.length-2]+=D.pop())},pN=(D)=>{let u=D.split(" "),r=u.length;for(;r>0&&!(O1(u[r-1])>0);)r--;return r===u.length?D:u.slice(0,r).join(" ")+u.slice(r).join("")},xN=(D,u,r={})=>{if(r.trim!==!1&&D.trim()==="")return"";let A="",f,w,F=tN(D),E=[""];for(let[g,_]of D.split(" ").entries()){r.trim!==!1&&(E[E.length-1]=E[E.length-1].trimStart());let R=O1(E[E.length-1]);if(g!==0&&(R>=u&&(r.wordWrap===!1||r.trim===!1)&&(E.push(""),R=0),(R>0||r.trim===!1)&&(E[E.length-1]+=" ",R++)),r.hard&&F[g]>u){let n=u-R,B=1+Math.floor((F[g]-n-1)/u);Math.floor((F[g]-1)/u)<B&&E.push(""),l$(E,_,u);continue}if(R+F[g]>u&&R>0&&F[g]>0){if(r.wordWrap===!1&&R<u){l$(E,_,u);continue}E.push("")}if(R+F[g]>u&&r.wordWrap===!1){l$(E,_,u);continue}E[E.length-1]+=_}r.trim!==!1&&(E=E.map((g)=>pN(g)));let $=[...E.join(`
1541
+ `)];for(let[g,_]of $.entries()){if(A+=_,r3.has(_)){let{groups:n}=new RegExp(`(?:\\${tB}(?<code>\\d+)m|\\${x$}(?<uri>.*)${p$})`).exec($.slice(g).join(""))||{groups:{}};if(n.code!==void 0){let B=Number.parseFloat(n.code);f=B===yN?void 0:B}else n.uri!==void 0&&(w=n.uri.length===0?void 0:n.uri)}let R=lN.codes.get(Number(f));$[g+1]===`
1542
+ `?(w&&(A+=jB("")),f&&R&&(A+=zB(R))):_===`
1543
+ `&&(f&&R&&(A+=zB(f)),w&&(A+=jB(w)))}return A},mN,u3,vB,eN,DQ=(D,u,r)=>(u in D)?eN(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,Ju=(D,u,r)=>(DQ(D,typeof u!="symbol"?u+"":u,r),r),mB,uQ,rQ=(D,u,r)=>(u in D)?uQ(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,ZB=(D,u,r)=>(rQ(D,typeof u!="symbol"?u+"":u,r),r),AQ,fQ,FQ=(D,u,r)=>(u in D)?fQ(D,u,{enumerable:!0,configurable:!0,writable:!0,value:r}):D[u]=r,oB=(D,u,r)=>(FQ(D,typeof u!="symbol"?u+"":u,r),r),aB,eB,$Q,au=(D,u)=>$Q?D:u,EQ,gQ,SQ,_Q,RD,v2,y$,c$,RQ,dB,nQ,A3=(D)=>{switch(D){case"initial":case"active":return I.cyan(EQ);case"cancel":return I.red(gQ);case"error":return I.yellow(SQ);case"submit":return I.green(_Q)}},t$=(D)=>{let{cursor:u,options:r,style:A}=D,f=D.maxItems??Number.POSITIVE_INFINITY,w=Math.max(process.stdout.rows-4,0),F=Math.min(w,Math.max(f,5)),E=0;u>=E+F-3?E=Math.max(Math.min(u-F+3,r.length-F),0):u<E+2&&(E=Math.max(u-2,0));let $=F<r.length&&E>0,g=F<r.length&&E+F<r.length;return r.slice(E,E+F).map((_,R,n)=>{let B=R===0&&$,C=R===n.length-1&&g;return B||C?I.dim("..."):A(_,R+E===u)})},BQ=(D)=>new eB({validate:D.validate,placeholder:D.placeholder,defaultValue:D.defaultValue,initialValue:D.initialValue,render(){let u=`${I.gray(RD)}
1544
+ ${A3(this.state)} ${D.message}
1545
1545
  `,r=D.placeholder?I.inverse(D.placeholder[0])+I.dim(D.placeholder.slice(1)):I.inverse(I.hidden("_")),A=this.value?this.valueWithCursor:r;switch(this.state){case"error":return`${u.trim()}
1546
- ${I.yellow(SD)} ${A}
1547
- ${I.yellow(s2)} ${I.yellow(this.error)}
1548
- `;case"submit":return`${u}${I.gray(SD)} ${I.dim(this.value||D.placeholder)}`;case"cancel":return`${u}${I.gray(SD)} ${I.strikethrough(I.dim(this.value??""))}${this.value?.trim()?`
1549
- ${I.gray(SD)}`:""}`;default:return`${u}${I.cyan(SD)} ${A}
1550
- ${I.cyan(s2)}
1551
- `}}}).prompt(),jN=(D)=>{let u=D.active??"Yes",r=D.inactive??"No";return new KJ({active:u,inactive:r,initialValue:D.initialValue??!0,render(){let A=`${I.gray(SD)}
1552
- ${pf(this.state)} ${D.message}
1553
- `,f=this.value?u:r;switch(this.state){case"submit":return`${A}${I.gray(SD)} ${I.dim(f)}`;case"cancel":return`${A}${I.gray(SD)} ${I.strikethrough(I.dim(f))}
1554
- ${I.gray(SD)}`;default:return`${A}${I.cyan(SD)} ${this.value?`${I.green(V$)} ${u}`:`${I.dim(K$)} ${I.dim(u)}`} ${I.dim("/")} ${this.value?`${I.dim(K$)} ${I.dim(r)}`:`${I.green(V$)} ${r}`}
1555
- ${I.cyan(s2)}
1556
- `}}}).prompt()},TN=(D)=>{let u=(r,A)=>{let f=r.label??String(r.value);switch(A){case"selected":return`${I.dim(f)}`;case"active":return`${I.green(V$)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`;case"cancelled":return`${I.strikethrough(I.dim(f))}`;default:return`${I.dim(K$)} ${I.dim(f)}`}};return new hJ({options:D.options,initialValue:D.initialValue,render(){let r=`${I.gray(SD)}
1557
- ${pf(this.state)} ${D.message}
1558
- `;switch(this.state){case"submit":return`${r}${I.gray(SD)} ${u(this.options[this.cursor],"selected")}`;case"cancel":return`${r}${I.gray(SD)} ${u(this.options[this.cursor],"cancelled")}
1559
- ${I.gray(SD)}`;default:return`${r}${I.cyan(SD)} ${h$({cursor:this.cursor,options:this.options,maxItems:D.maxItems,style:(A,f)=>u(A,f?"active":"inactive")}).join(`
1560
- ${I.cyan(SD)} `)}
1561
- ${I.cyan(s2)}
1562
- `}}}).prompt()},vN=(D)=>{let u=(r,A)=>{let f=r.label??String(r.value);return A==="active"?`${I.cyan(qN)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`:A==="selected"?`${I.green(MJ)} ${I.dim(f)}`:A==="cancelled"?`${I.strikethrough(I.dim(f))}`:A==="active-selected"?`${I.green(MJ)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`:A==="submitted"?`${I.dim(f)}`:`${I.dim(bN)} ${I.dim(f)}`};return new iN({options:D.options,initialValues:D.initialValues,required:D.required??!0,cursorAt:D.cursorAt,validate(r){if(this.required&&r.length===0)return`Please select at least one option.
1563
- ${I.reset(I.dim(`Press ${I.gray(I.bgWhite(I.inverse(" space ")))} to select, ${I.gray(I.bgWhite(I.inverse(" enter ")))} to submit`))}`},render(){let r=`${I.gray(SD)}
1564
- ${pf(this.state)} ${D.message}
1565
- `,A=(f,w)=>{let F=this.value.includes(f.value);return w&&F?u(f,"active-selected"):F?u(f,"selected"):u(f,w?"active":"inactive")};switch(this.state){case"submit":return`${r}${I.gray(SD)} ${this.options.filter(({value:f})=>this.value.includes(f)).map((f)=>u(f,"submitted")).join(I.dim(", "))||I.dim("none")}`;case"cancel":{let f=this.options.filter(({value:w})=>this.value.includes(w)).map((w)=>u(w,"cancelled")).join(I.dim(", "));return`${r}${I.gray(SD)} ${f.trim()?`${f}
1566
- ${I.gray(SD)}`:""}`}case"error":{let f=this.error.split(`
1567
- `).map((w,F)=>F===0?`${I.yellow(s2)} ${I.yellow(w)}`:` ${w}`).join(`
1568
- `);return`${r+I.yellow(SD)} ${h$({options:this.options,cursor:this.cursor,maxItems:D.maxItems,style:A}).join(`
1569
- ${I.yellow(SD)} `)}
1546
+ ${I.yellow(RD)} ${A}
1547
+ ${I.yellow(v2)} ${I.yellow(this.error)}
1548
+ `;case"submit":return`${u}${I.gray(RD)} ${I.dim(this.value||D.placeholder)}`;case"cancel":return`${u}${I.gray(RD)} ${I.strikethrough(I.dim(this.value??""))}${this.value?.trim()?`
1549
+ ${I.gray(RD)}`:""}`;default:return`${u}${I.cyan(RD)} ${A}
1550
+ ${I.cyan(v2)}
1551
+ `}}}).prompt(),WQ=(D)=>{let u=D.active??"Yes",r=D.inactive??"No";return new mB({active:u,inactive:r,initialValue:D.initialValue??!0,render(){let A=`${I.gray(RD)}
1552
+ ${A3(this.state)} ${D.message}
1553
+ `,f=this.value?u:r;switch(this.state){case"submit":return`${A}${I.gray(RD)} ${I.dim(f)}`;case"cancel":return`${A}${I.gray(RD)} ${I.strikethrough(I.dim(f))}
1554
+ ${I.gray(RD)}`;default:return`${A}${I.cyan(RD)} ${this.value?`${I.green(y$)} ${u}`:`${I.dim(c$)} ${I.dim(u)}`} ${I.dim("/")} ${this.value?`${I.dim(c$)} ${I.dim(r)}`:`${I.green(y$)} ${r}`}
1555
+ ${I.cyan(v2)}
1556
+ `}}}).prompt()},JQ=(D)=>{let u=(r,A)=>{let f=r.label??String(r.value);switch(A){case"selected":return`${I.dim(f)}`;case"active":return`${I.green(y$)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`;case"cancelled":return`${I.strikethrough(I.dim(f))}`;default:return`${I.dim(c$)} ${I.dim(f)}`}};return new aB({options:D.options,initialValue:D.initialValue,render(){let r=`${I.gray(RD)}
1557
+ ${A3(this.state)} ${D.message}
1558
+ `;switch(this.state){case"submit":return`${r}${I.gray(RD)} ${u(this.options[this.cursor],"selected")}`;case"cancel":return`${r}${I.gray(RD)} ${u(this.options[this.cursor],"cancelled")}
1559
+ ${I.gray(RD)}`;default:return`${r}${I.cyan(RD)} ${t$({cursor:this.cursor,options:this.options,maxItems:D.maxItems,style:(A,f)=>u(A,f?"active":"inactive")}).join(`
1560
+ ${I.cyan(RD)} `)}
1561
+ ${I.cyan(v2)}
1562
+ `}}}).prompt()},GQ=(D)=>{let u=(r,A)=>{let f=r.label??String(r.value);return A==="active"?`${I.cyan(RQ)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`:A==="selected"?`${I.green(dB)} ${I.dim(f)}`:A==="cancelled"?`${I.strikethrough(I.dim(f))}`:A==="active-selected"?`${I.green(dB)} ${f} ${r.hint?I.dim(`(${r.hint})`):""}`:A==="submitted"?`${I.dim(f)}`:`${I.dim(nQ)} ${I.dim(f)}`};return new AQ({options:D.options,initialValues:D.initialValues,required:D.required??!0,cursorAt:D.cursorAt,validate(r){if(this.required&&r.length===0)return`Please select at least one option.
1563
+ ${I.reset(I.dim(`Press ${I.gray(I.bgWhite(I.inverse(" space ")))} to select, ${I.gray(I.bgWhite(I.inverse(" enter ")))} to submit`))}`},render(){let r=`${I.gray(RD)}
1564
+ ${A3(this.state)} ${D.message}
1565
+ `,A=(f,w)=>{let F=this.value.includes(f.value);return w&&F?u(f,"active-selected"):F?u(f,"selected"):u(f,w?"active":"inactive")};switch(this.state){case"submit":return`${r}${I.gray(RD)} ${this.options.filter(({value:f})=>this.value.includes(f)).map((f)=>u(f,"submitted")).join(I.dim(", "))||I.dim("none")}`;case"cancel":{let f=this.options.filter(({value:w})=>this.value.includes(w)).map((w)=>u(w,"cancelled")).join(I.dim(", "));return`${r}${I.gray(RD)} ${f.trim()?`${f}
1566
+ ${I.gray(RD)}`:""}`}case"error":{let f=this.error.split(`
1567
+ `).map((w,F)=>F===0?`${I.yellow(v2)} ${I.yellow(w)}`:` ${w}`).join(`
1568
+ `);return`${r+I.yellow(RD)} ${t$({options:this.options,cursor:this.cursor,maxItems:D.maxItems,style:A}).join(`
1569
+ ${I.yellow(RD)} `)}
1570
1570
  ${f}
1571
- `}default:return`${r}${I.cyan(SD)} ${h$({options:this.options,cursor:this.cursor,maxItems:D.maxItems,style:A}).join(`
1572
- ${I.cyan(SD)} `)}
1573
- ${I.cyan(s2)}
1574
- `}}}).prompt()},QJ;var bJ=W(()=>{xu=rN(),cf={exports:{}};fN=AN(),I=uN(fN);wN=FN();iJ={exports:{}};(function(D){var u={};D.exports=u,u.eastAsianWidth=function(A){var f=A.charCodeAt(0),w=A.length==2?A.charCodeAt(1):0,F=f;return 55296<=f&&f<=56319&&56320<=w&&w<=57343&&(f&=1023,w&=1023,F=f<<10|w,F+=65536),F==12288||65281<=F&&F<=65376||65504<=F&&F<=65510?"F":F==8361||65377<=F&&F<=65470||65474<=F&&F<=65479||65482<=F&&F<=65487||65490<=F&&F<=65495||65498<=F&&F<=65500||65512<=F&&F<=65518?"H":4352<=F&&F<=4447||4515<=F&&F<=4519||4602<=F&&F<=4607||9001<=F&&F<=9002||11904<=F&&F<=11929||11931<=F&&F<=12019||12032<=F&&F<=12245||12272<=F&&F<=12283||12289<=F&&F<=12350||12353<=F&&F<=12438||12441<=F&&F<=12543||12549<=F&&F<=12589||12593<=F&&F<=12686||12688<=F&&F<=12730||12736<=F&&F<=12771||12784<=F&&F<=12830||12832<=F&&F<=12871||12880<=F&&F<=13054||13056<=F&&F<=19903||19968<=F&&F<=42124||42128<=F&&F<=42182||43360<=F&&F<=43388||44032<=F&&F<=55203||55216<=F&&F<=55238||55243<=F&&F<=55291||63744<=F&&F<=64255||65040<=F&&F<=65049||65072<=F&&F<=65106||65108<=F&&F<=65126||65128<=F&&F<=65131||110592<=F&&F<=110593||127488<=F&&F<=127490||127504<=F&&F<=127546||127552<=F&&F<=127560||127568<=F&&F<=127569||131072<=F&&F<=194367||177984<=F&&F<=196605||196608<=F&&F<=262141?"W":32<=F&&F<=126||162<=F&&F<=163||165<=F&&F<=166||F==172||F==175||10214<=F&&F<=10221||10629<=F&&F<=10630?"Na":F==161||F==164||167<=F&&F<=168||F==170||173<=F&&F<=174||176<=F&&F<=180||182<=F&&F<=186||188<=F&&F<=191||F==198||F==208||215<=F&&F<=216||222<=F&&F<=225||F==230||232<=F&&F<=234||236<=F&&F<=237||F==240||242<=F&&F<=243||247<=F&&F<=250||F==252||F==254||F==257||F==273||F==275||F==283||294<=F&&F<=295||F==299||305<=F&&F<=307||F==312||319<=F&&F<=322||F==324||328<=F&&F<=331||F==333||338<=F&&F<=339||358<=F&&F<=359||F==363||F==462||F==464||F==466||F==468||F==470||F==472||F==474||F==476||F==593||F==609||F==708||F==711||713<=F&&F<=715||F==717||F==720||728<=F&&F<=731||F==733||F==735||768<=F&&F<=879||913<=F&&F<=929||931<=F&&F<=937||945<=F&&F<=961||963<=F&&F<=969||F==1025||1040<=F&&F<=1103||F==1105||F==8208||8211<=F&&F<=8214||8216<=F&&F<=8217||8220<=F&&F<=8221||8224<=F&&F<=8226||8228<=F&&F<=8231||F==8240||8242<=F&&F<=8243||F==8245||F==8251||F==8254||F==8308||F==8319||8321<=F&&F<=8324||F==8364||F==8451||F==8453||F==8457||F==8467||F==8470||8481<=F&&F<=8482||F==8486||F==8491||8531<=F&&F<=8532||8539<=F&&F<=8542||8544<=F&&F<=8555||8560<=F&&F<=8569||F==8585||8592<=F&&F<=8601||8632<=F&&F<=8633||F==8658||F==8660||F==8679||F==8704||8706<=F&&F<=8707||8711<=F&&F<=8712||F==8715||F==8719||F==8721||F==8725||F==8730||8733<=F&&F<=8736||F==8739||F==8741||8743<=F&&F<=8748||F==8750||8756<=F&&F<=8759||8764<=F&&F<=8765||F==8776||F==8780||F==8786||8800<=F&&F<=8801||8804<=F&&F<=8807||8810<=F&&F<=8811||8814<=F&&F<=8815||8834<=F&&F<=8835||8838<=F&&F<=8839||F==8853||F==8857||F==8869||F==8895||F==8978||9312<=F&&F<=9449||9451<=F&&F<=9547||9552<=F&&F<=9587||9600<=F&&F<=9615||9618<=F&&F<=9621||9632<=F&&F<=9633||9635<=F&&F<=9641||9650<=F&&F<=9651||9654<=F&&F<=9655||9660<=F&&F<=9661||9664<=F&&F<=9665||9670<=F&&F<=9672||F==9675||9678<=F&&F<=9681||9698<=F&&F<=9701||F==9711||9733<=F&&F<=9734||F==9737||9742<=F&&F<=9743||9748<=F&&F<=9749||F==9756||F==9758||F==9792||F==9794||9824<=F&&F<=9825||9827<=F&&F<=9829||9831<=F&&F<=9834||9836<=F&&F<=9837||F==9839||9886<=F&&F<=9887||9918<=F&&F<=9919||9924<=F&&F<=9933||9935<=F&&F<=9953||F==9955||9960<=F&&F<=9983||F==10045||F==10071||10102<=F&&F<=10111||11093<=F&&F<=11097||12872<=F&&F<=12879||57344<=F&&F<=63743||65024<=F&&F<=65039||F==65533||127232<=F&&F<=127242||127248<=F&&F<=127277||127280<=F&&F<=127337||127344<=F&&F<=127386||917760<=F&&F<=917999||983040<=F&&F<=1048573||1048576<=F&&F<=1114109?"A":"N"},u.characterLength=function(A){var f=this.eastAsianWidth(A);return f=="F"||f=="W"||f=="A"?2:1};function r(A){return A.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}u.length=function(A){for(var f=r(A),w=0,F=0;F<f.length;F++)w=w+this.characterLength(f[F]);return w},u.slice=function(A,f,w){textLen=u.length(A),f=f||0,w=w||1,f<0&&(f=textLen+f),w<0&&(w=textLen+w);for(var F="",E=0,$=r(A),g=0;g<$.length;g++){var R=$[g],S=u.length(R);if(E>=f-(S==2?1:0))if(E+S<=w)F+=R;else break;E+=S}return F}})(iJ);$N=iJ.exports,EN=PJ($N),_N=PJ(gN);HD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],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],gray:[90,39],grey:[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],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(HD.modifier);RN=Object.keys(HD.color),SN=Object.keys(HD.bgColor);[...RN,...SN];JN=BN(),mf=new Set(["\x1B","\x9B"]),Q$=`${GN}8;;`;UN=["up","down","left","right","space","enter","cancel"],xf={actions:new Set(UN),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]])};globalThis.process.platform.startsWith("win");UJ=Symbol("clack:cancel");YN=Object.defineProperty;KJ=class KJ extends MA{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(D){super(D,!1),this.value=!!D.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",(u)=>{this.output.write(xu.cursor.move(0,-1)),this.value=u,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};ON=Object.defineProperty,iN=class extends MA{constructor(D){super(D,!1),XJ(this,"options"),XJ(this,"cursor",0),this.options=D.options,this.value=[...D.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:u})=>u===D.cursorAt),0),this.on("key",(u)=>{u==="a"&&this.toggleAll()}),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){let D=this.value.length===this.options.length;this.value=D?[]:this.options.map((u)=>u.value)}toggleValue(){let D=this.value.includes(this._value);this.value=D?this.value.filter((u)=>u!==this._value):[...this.value,this._value]}},kN=Object.defineProperty;hJ=class hJ extends MA{constructor(D){super(D,!1),YJ(this,"options"),YJ(this,"cursor",0),this.options=D.options,this.cursor=this.options.findIndex(({value:u})=>u===D.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};NJ=class NJ extends MA{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let D=this.value.slice(0,this.cursor),[u,...r]=this.value.slice(this.cursor);return`${D}${I.inverse(u)}${r.join("")}`}get cursor(){return this._cursor}constructor(D){super(D),this.on("finalize",()=>{this.value||(this.value=D.defaultValue)})}};KN=VN(),hN=mu("\u276F",">"),NN=mu("\u25A0","x"),QN=mu("\u25B2","x"),LN=mu("\u2714","\u221A"),SD=mu(""),s2=mu(""),V$=mu("\u25CF",">"),K$=mu("\u25CB"," "),qN=mu("\u25FB","[\u2022]"),MJ=mu("\u25FC","[+]"),bN=mu("\u25FB","[ ]");`${I.gray(SD)} `;QJ=Symbol.for("cancel")});import zJ from"process";function oN(){if(globalThis.process?.env)for(let D of ZN){let u=D[1]||D[0];if(globalThis.process?.env[u])return{name:D[0].toLowerCase(),...D[2]}}return globalThis.process?.env?.SHELL==="/bin/jsh"&&globalThis.process?.versions?.webcontainer?{name:"stackblitz",ci:!1}:{name:"",ci:!1}}function Z0(D){return D?D!=="false":!1}function AQ(){let D=rQ.find((u)=>u[0]);if(D)return{name:D[1]}}function FQ({onlyFirst:D=!1}={}){let r=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(r,D?void 0:"g")}function $Q(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(wQ,"")}function EQ(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function gQ(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function _Q(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function RQ(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function SQ(D,{ambiguousAsWide:u=!1}={}){if(RQ(D),gQ(D)||_Q(D)||u&&EQ(D))return 2;return 1}function GQ(D,u={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:A=!1}=u;if(!A)D=$Q(D);if(D.length===0)return 0;let f=0,w={ambiguousAsWide:!r};for(let{segment:F}of JQ.segment(D)){let E=F.codePointAt(0);if(E<=31||E>=127&&E<=159)continue;if(E>=8203&&E<=8207||E===65279)continue;if(E>=768&&E<=879||E>=6832&&E<=6911||E>=7616&&E<=7679||E>=8400&&E<=8447||E>=65056&&E<=65071)continue;if(E>=55296&&E<=57343)continue;if(E>=65024&&E<=65039)continue;if(WQ.test(F))continue;if(BQ().test(F)){f+=2;continue}f+=SQ(E,w)}return f}function CQ(){let{env:D}=zJ,{TERM:u,TERM_PROGRAM:r}=D;if(zJ.platform!=="win32")return u!=="linux";return Boolean(D.WT_SESSION)||Boolean(D.TERMINUS_SUBLIME)||D.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||u==="xterm-256color"||u==="alacritty"||u==="rxvt-unicode"||u==="rxvt-unicode-256color"||D.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function vJ(D){if(typeof Intl!=="object"||!Intl.Segmenter)return C0(D).length;return GQ(D)}function af(D){return D.replace(/`([^`]+)`/gm,(u,r)=>Du.cyan(r)).replace(/\s+_([^_]+)_\s+/gm,(u,r)=>` ${Du.underline(r)} `)}function XQ(D="white"){return Du[D]||Du.white}function YQ(D="bgWhite"){return Du[`bg${D[0].toUpperCase()}${D.slice(1)}`]||Du.bgWhite}function MQ(D={}){let u=OQ();if(process.env.CONSOLA_LEVEL)u=Number.parseInt(process.env.CONSOLA_LEVEL)??u;return uJ({level:u,defaults:{level:u},stdout:process.stdout,stderr:process.stderr,prompt:(...A)=>Promise.resolve().then(() => (bJ(),qJ)).then((f)=>f.prompt(...A)),reporters:D.reporters||[D.fancy??!(L$||q$)?new oJ:new yf],...D})}function OQ(){if(yN)return yD.debug;if(q$)return yD.warn;return yD.info}var ef,OA=(D)=>globalThis.process?.env||import.meta.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(D?ef:globalThis),n0,sN,ZN,sJ,dN,L$,ZJ,yN,q$,lN,cN,tN,jJ,xN,mN,pN,aN,eN,DQ,uQ,rQ,fQ,wQ,BQ=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g},JQ,WQ,HQ,nQ,UQ,Or=(D,u)=>UQ?D:u,TJ,oJ,vr;var D3=W(()=>{M$();M$();AJ();_J();ef=Object.create(null),n0=new Proxy(ef,{get(D,u){return OA()[u]??ef[u]},has(D,u){let r=OA();return u in r||u in ef},set(D,u,r){let A=OA(!0);return A[u]=r,!0},deleteProperty(D,u){if(!u)return!1;let r=OA(!0);return delete r[u],!0},ownKeys(){let D=OA(!0);return Object.keys(D)}}),sN=typeof process<"u"&&process.env&&"development"||"",ZN=[["APPVEYOR"],["AWS_AMPLIFY","AWS_APP_ID",{ci:!0}],["AZURE_PIPELINES","SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"],["AZURE_STATIC","INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"],["APPCIRCLE","AC_APPCIRCLE"],["BAMBOO","bamboo_planKey"],["BITBUCKET","BITBUCKET_COMMIT"],["BITRISE","BITRISE_IO"],["BUDDY","BUDDY_WORKSPACE_ID"],["BUILDKITE"],["CIRCLE","CIRCLECI"],["CIRRUS","CIRRUS_CI"],["CLOUDFLARE_PAGES","CF_PAGES",{ci:!0}],["CODEBUILD","CODEBUILD_BUILD_ARN"],["CODEFRESH","CF_BUILD_ID"],["DRONE"],["DRONE","DRONE_BUILD_EVENT"],["DSARI"],["GITHUB_ACTIONS"],["GITLAB","GITLAB_CI"],["GITLAB","CI_MERGE_REQUEST_ID"],["GOCD","GO_PIPELINE_LABEL"],["LAYERCI"],["HUDSON","HUDSON_URL"],["JENKINS","JENKINS_URL"],["MAGNUM"],["NETLIFY"],["NETLIFY","NETLIFY_LOCAL",{ci:!1}],["NEVERCODE"],["RENDER"],["SAIL","SAILCI"],["SEMAPHORE"],["SCREWDRIVER"],["SHIPPABLE"],["SOLANO","TDDIUM"],["STRIDER"],["TEAMCITY","TEAMCITY_VERSION"],["TRAVIS"],["VERCEL","NOW_BUILDER"],["VERCEL","VERCEL",{ci:!1}],["VERCEL","VERCEL_ENV",{ci:!1}],["APPCENTER","APPCENTER_BUILD_ID"],["CODESANDBOX","CODESANDBOX_SSE",{ci:!1}],["CODESANDBOX","CODESANDBOX_HOST",{ci:!1}],["STACKBLITZ"],["STORMKIT"],["CLEAVR"],["ZEABUR"],["CODESPHERE","CODESPHERE_APP_ID",{ci:!0}],["RAILWAY","RAILWAY_PROJECT_ID"],["RAILWAY","RAILWAY_SERVICE_ID"],["DENO-DEPLOY","DENO_DEPLOYMENT_ID"],["FIREBASE_APP_HOSTING","FIREBASE_APP_HOSTING",{ci:!0}]];sJ=oN();sJ.name;dN=globalThis.process?.platform||"",L$=Z0(n0.CI)||sJ.ci!==!1,ZJ=Z0(globalThis.process?.stdout&&globalThis.process?.stdout.isTTY),yN=Z0(n0.DEBUG),q$=sN==="test"||Z0(n0.TEST);Z0(n0.MINIMAL);lN=/^win/i.test(dN);!Z0(n0.NO_COLOR)&&(Z0(n0.FORCE_COLOR)||(ZJ||lN)&&n0.TERM);cN=(globalThis.process?.versions?.node||"").replace(/^v/,"")||null;Number(cN?.split(".")[0]);tN=globalThis.process||Object.create(null),jJ={versions:{}};new Proxy(tN,{get(D,u){if(u==="env")return n0;if(u in D)return D[u];if(u in jJ)return jJ[u]}});xN=globalThis.process?.release?.name==="node",mN=!!globalThis.Bun||!!globalThis.process?.versions?.bun,pN=!!globalThis.Deno,aN=!!globalThis.fastly,eN=!!globalThis.Netlify,DQ=!!globalThis.EdgeRuntime,uQ=globalThis.navigator?.userAgent==="Cloudflare-Workers",rQ=[[eN,"netlify"],[DQ,"edge-light"],[uQ,"workerd"],[aN,"fastly"],[pN,"deno"],[mN,"bun"],[xN,"node"]];fQ=AQ();fQ?.name;wQ=FQ();JQ=globalThis.Intl?.Segmenter?new Intl.Segmenter:{segment:(D)=>D.split("")},WQ=/^\p{Default_Ignorable_Code_Point}$/u;HQ={info:"cyan",fail:"red",success:"green",ready:"green",start:"magenta"},nQ={0:"red",1:"yellow"},UQ=CQ(),TJ={error:Or("\u2716","\xD7"),fatal:Or("\u2716","\xD7"),ready:Or("\u2714","\u221A"),warn:Or("\u26A0","\u203C"),info:Or("\u2139","i"),success:Or("\u2714","\u221A"),debug:Or("\u2699","D"),trace:Or("\u2192","\u2192"),fail:Or("\u2716","\xD7"),start:Or("\u25D0","o"),log:""};oJ=class oJ extends yf{formatStack(D,u,r){let A=" ".repeat((r?.errorLevel||0)+1);return`
1575
- ${A}`+P$(D,u).map((f)=>" "+f.replace(/^at +/,(w)=>Du.gray(w)).replace(/\((.+)\)/,(w,F)=>`(${Du.cyan(F)})`)).join(`
1576
- ${A}`)}formatType(D,u,r){let A=HQ[D.type]||nQ[D.level]||"gray";if(u)return YQ(A)(Du.black(` ${D.type.toUpperCase()} `));let f=typeof TJ[D.type]==="string"?TJ[D.type]:D.icon||D.type;return f?XQ(A)(f):""}formatLogObj(D,u){let[r,...A]=this.formatArgs(D.args,u).split(`
1577
- `);if(D.type==="box")return gJ(af(r+(A.length>0?`
1571
+ `}default:return`${r}${I.cyan(RD)} ${t$({options:this.options,cursor:this.cursor,maxItems:D.maxItems,style:A}).join(`
1572
+ ${I.cyan(RD)} `)}
1573
+ ${I.cyan(v2)}
1574
+ `}}}).prompt()},DW;var AW=W(()=>{mu=QN(),ef={exports:{}};qN=LN(),I=NN(qN);sN=bN();cB={exports:{}};(function(D){var u={};D.exports=u,u.eastAsianWidth=function(A){var f=A.charCodeAt(0),w=A.length==2?A.charCodeAt(1):0,F=f;return 55296<=f&&f<=56319&&56320<=w&&w<=57343&&(f&=1023,w&=1023,F=f<<10|w,F+=65536),F==12288||65281<=F&&F<=65376||65504<=F&&F<=65510?"F":F==8361||65377<=F&&F<=65470||65474<=F&&F<=65479||65482<=F&&F<=65487||65490<=F&&F<=65495||65498<=F&&F<=65500||65512<=F&&F<=65518?"H":4352<=F&&F<=4447||4515<=F&&F<=4519||4602<=F&&F<=4607||9001<=F&&F<=9002||11904<=F&&F<=11929||11931<=F&&F<=12019||12032<=F&&F<=12245||12272<=F&&F<=12283||12289<=F&&F<=12350||12353<=F&&F<=12438||12441<=F&&F<=12543||12549<=F&&F<=12589||12593<=F&&F<=12686||12688<=F&&F<=12730||12736<=F&&F<=12771||12784<=F&&F<=12830||12832<=F&&F<=12871||12880<=F&&F<=13054||13056<=F&&F<=19903||19968<=F&&F<=42124||42128<=F&&F<=42182||43360<=F&&F<=43388||44032<=F&&F<=55203||55216<=F&&F<=55238||55243<=F&&F<=55291||63744<=F&&F<=64255||65040<=F&&F<=65049||65072<=F&&F<=65106||65108<=F&&F<=65126||65128<=F&&F<=65131||110592<=F&&F<=110593||127488<=F&&F<=127490||127504<=F&&F<=127546||127552<=F&&F<=127560||127568<=F&&F<=127569||131072<=F&&F<=194367||177984<=F&&F<=196605||196608<=F&&F<=262141?"W":32<=F&&F<=126||162<=F&&F<=163||165<=F&&F<=166||F==172||F==175||10214<=F&&F<=10221||10629<=F&&F<=10630?"Na":F==161||F==164||167<=F&&F<=168||F==170||173<=F&&F<=174||176<=F&&F<=180||182<=F&&F<=186||188<=F&&F<=191||F==198||F==208||215<=F&&F<=216||222<=F&&F<=225||F==230||232<=F&&F<=234||236<=F&&F<=237||F==240||242<=F&&F<=243||247<=F&&F<=250||F==252||F==254||F==257||F==273||F==275||F==283||294<=F&&F<=295||F==299||305<=F&&F<=307||F==312||319<=F&&F<=322||F==324||328<=F&&F<=331||F==333||338<=F&&F<=339||358<=F&&F<=359||F==363||F==462||F==464||F==466||F==468||F==470||F==472||F==474||F==476||F==593||F==609||F==708||F==711||713<=F&&F<=715||F==717||F==720||728<=F&&F<=731||F==733||F==735||768<=F&&F<=879||913<=F&&F<=929||931<=F&&F<=937||945<=F&&F<=961||963<=F&&F<=969||F==1025||1040<=F&&F<=1103||F==1105||F==8208||8211<=F&&F<=8214||8216<=F&&F<=8217||8220<=F&&F<=8221||8224<=F&&F<=8226||8228<=F&&F<=8231||F==8240||8242<=F&&F<=8243||F==8245||F==8251||F==8254||F==8308||F==8319||8321<=F&&F<=8324||F==8364||F==8451||F==8453||F==8457||F==8467||F==8470||8481<=F&&F<=8482||F==8486||F==8491||8531<=F&&F<=8532||8539<=F&&F<=8542||8544<=F&&F<=8555||8560<=F&&F<=8569||F==8585||8592<=F&&F<=8601||8632<=F&&F<=8633||F==8658||F==8660||F==8679||F==8704||8706<=F&&F<=8707||8711<=F&&F<=8712||F==8715||F==8719||F==8721||F==8725||F==8730||8733<=F&&F<=8736||F==8739||F==8741||8743<=F&&F<=8748||F==8750||8756<=F&&F<=8759||8764<=F&&F<=8765||F==8776||F==8780||F==8786||8800<=F&&F<=8801||8804<=F&&F<=8807||8810<=F&&F<=8811||8814<=F&&F<=8815||8834<=F&&F<=8835||8838<=F&&F<=8839||F==8853||F==8857||F==8869||F==8895||F==8978||9312<=F&&F<=9449||9451<=F&&F<=9547||9552<=F&&F<=9587||9600<=F&&F<=9615||9618<=F&&F<=9621||9632<=F&&F<=9633||9635<=F&&F<=9641||9650<=F&&F<=9651||9654<=F&&F<=9655||9660<=F&&F<=9661||9664<=F&&F<=9665||9670<=F&&F<=9672||F==9675||9678<=F&&F<=9681||9698<=F&&F<=9701||F==9711||9733<=F&&F<=9734||F==9737||9742<=F&&F<=9743||9748<=F&&F<=9749||F==9756||F==9758||F==9792||F==9794||9824<=F&&F<=9825||9827<=F&&F<=9829||9831<=F&&F<=9834||9836<=F&&F<=9837||F==9839||9886<=F&&F<=9887||9918<=F&&F<=9919||9924<=F&&F<=9933||9935<=F&&F<=9953||F==9955||9960<=F&&F<=9983||F==10045||F==10071||10102<=F&&F<=10111||11093<=F&&F<=11097||12872<=F&&F<=12879||57344<=F&&F<=63743||65024<=F&&F<=65039||F==65533||127232<=F&&F<=127242||127248<=F&&F<=127277||127280<=F&&F<=127337||127344<=F&&F<=127386||917760<=F&&F<=917999||983040<=F&&F<=1048573||1048576<=F&&F<=1114109?"A":"N"},u.characterLength=function(A){var f=this.eastAsianWidth(A);return f=="F"||f=="W"||f=="A"?2:1};function r(A){return A.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}u.length=function(A){for(var f=r(A),w=0,F=0;F<f.length;F++)w=w+this.characterLength(f[F]);return w},u.slice=function(A,f,w){textLen=u.length(A),f=f||0,w=w||1,f<0&&(f=textLen+f),w<0&&(w=textLen+w);for(var F="",E=0,$=r(A),g=0;g<$.length;g++){var _=$[g],R=u.length(_);if(E>=f-(R==2?1:0))if(E+R<=w)F+=_;else break;E+=R}return F}})(cB);zN=cB.exports,jN=yB(zN),vN=yB(TN);CD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],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],gray:[90,39],grey:[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],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(CD.modifier);ZN=Object.keys(CD.color),oN=Object.keys(CD.bgColor);[...ZN,...oN];lN=dN(),r3=new Set(["\x1B","\x9B"]),x$=`${cN}8;;`;mN=["up","down","left","right","space","enter","cancel"],u3={actions:new Set(mN),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]])};globalThis.process.platform.startsWith("win");vB=Symbol("clack:cancel");eN=Object.defineProperty;mB=class mB extends P1{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(D){super(D,!1),this.value=!!D.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",(u)=>{this.output.write(mu.cursor.move(0,-1)),this.value=u,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};uQ=Object.defineProperty,AQ=class extends P1{constructor(D){super(D,!1),ZB(this,"options"),ZB(this,"cursor",0),this.options=D.options,this.value=[...D.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:u})=>u===D.cursorAt),0),this.on("key",(u)=>{u==="a"&&this.toggleAll()}),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){let D=this.value.length===this.options.length;this.value=D?[]:this.options.map((u)=>u.value)}toggleValue(){let D=this.value.includes(this._value);this.value=D?this.value.filter((u)=>u!==this._value):[...this.value,this._value]}},fQ=Object.defineProperty;aB=class aB extends P1{constructor(D){super(D,!1),oB(this,"options"),oB(this,"cursor",0),this.options=D.options,this.cursor=this.options.findIndex(({value:u})=>u===D.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};eB=class eB extends P1{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let D=this.value.slice(0,this.cursor),[u,...r]=this.value.slice(this.cursor);return`${D}${I.inverse(u)}${r.join("")}`}get cursor(){return this._cursor}constructor(D){super(D),this.on("finalize",()=>{this.value||(this.value=D.defaultValue)})}};$Q=wQ(),EQ=au("\u276F",">"),gQ=au("\u25A0","x"),SQ=au("\u25B2","x"),_Q=au("\u2714","\u221A"),RD=au(""),v2=au(""),y$=au("\u25CF",">"),c$=au("\u25CB"," "),RQ=au("\u25FB","[\u2022]"),dB=au("\u25FC","[+]"),nQ=au("\u25FB","[ ]");`${I.gray(RD)} `;DW=Symbol.for("cancel")});import fW from"process";function XQ(){if(globalThis.process?.env)for(let D of HQ){let u=D[1]||D[0];if(globalThis.process?.env[u])return{name:D[0].toLowerCase(),...D[2]}}return globalThis.process?.env?.SHELL==="/bin/jsh"&&globalThis.process?.versions?.webcontainer?{name:"stackblitz",ci:!1}:{name:"",ci:!1}}function o0(D){return D?D!=="false":!1}function LQ(){let D=QQ.find((u)=>u[0]);if(D)return{name:D[1]}}function bQ({onlyFirst:D=!1}={}){let r=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(r,D?void 0:"g")}function zQ(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(sQ,"")}function jQ(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function TQ(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function vQ(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function ZQ(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function oQ(D,{ambiguousAsWide:u=!1}={}){if(ZQ(D),TQ(D)||vQ(D)||u&&jQ(D))return 2;return 1}function cQ(D,u={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:A=!1}=u;if(!A)D=zQ(D);if(D.length===0)return 0;let f=0,w={ambiguousAsWide:!r};for(let{segment:F}of lQ.segment(D)){let E=F.codePointAt(0);if(E<=31||E>=127&&E<=159)continue;if(E>=8203&&E<=8207||E===65279)continue;if(E>=768&&E<=879||E>=6832&&E<=6911||E>=7616&&E<=7679||E>=8400&&E<=8447||E>=65056&&E<=65071)continue;if(E>=55296&&E<=57343)continue;if(E>=65024&&E<=65039)continue;if(yQ.test(F))continue;if(dQ().test(F)){f+=2;continue}f+=oQ(E,w)}return f}function tQ(){let{env:D}=fW,{TERM:u,TERM_PROGRAM:r}=D;if(fW.platform!=="win32")return u!=="linux";return Boolean(D.WT_SESSION)||Boolean(D.TERMINUS_SUBLIME)||D.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||u==="xterm-256color"||u==="alacritty"||u==="rxvt-unicode"||u==="rxvt-unicode-256color"||D.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function $W(D){if(typeof Intl!=="object"||!Intl.Segmenter)return G0(D).length;return cQ(D)}function f3(D){return D.replace(/`([^`]+)`/gm,(u,r)=>ru.cyan(r)).replace(/\s+_([^_]+)_\s+/gm,(u,r)=>` ${ru.underline(r)} `)}function aQ(D="white"){return ru[D]||ru.white}function eQ(D="bgWhite"){return ru[`bg${D[0].toUpperCase()}${D.slice(1)}`]||ru.bgWhite}function DL(D={}){let u=uL();if(process.env.CONSOLA_LEVEL)u=Number.parseInt(process.env.CONSOLA_LEVEL)??u;return UB({level:u,defaults:{level:u},stdout:process.stdout,stderr:process.stderr,prompt:(...A)=>Promise.resolve().then(() => (AW(),rW)).then((f)=>f.prompt(...A)),reporters:D.reporters||[D.fancy??!(m$||a$)?new SW:new mf],...D})}function uL(){if(UQ)return yD.debug;if(a$)return yD.warn;return yD.info}var F3,k1=(D)=>globalThis.process?.env||import.meta.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(D?F3:globalThis),H0,CQ,HQ,EW,iQ,m$,gW,UQ,a$,YQ,MQ,OQ,FW,PQ,kQ,IQ,VQ,KQ,hQ,NQ,QQ,qQ,sQ,dQ=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g},lQ,yQ,pQ,xQ,mQ,Or=(D,u)=>mQ?D:u,wW,SW,vr;var w3=W(()=>{T$();T$();MB();hB();F3=Object.create(null),H0=new Proxy(F3,{get(D,u){return k1()[u]??F3[u]},has(D,u){let r=k1();return u in r||u in F3},set(D,u,r){let A=k1(!0);return A[u]=r,!0},deleteProperty(D,u){if(!u)return!1;let r=k1(!0);return delete r[u],!0},ownKeys(){let D=k1(!0);return Object.keys(D)}}),CQ=typeof process<"u"&&process.env&&"development"||"",HQ=[["APPVEYOR"],["AWS_AMPLIFY","AWS_APP_ID",{ci:!0}],["AZURE_PIPELINES","SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"],["AZURE_STATIC","INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"],["APPCIRCLE","AC_APPCIRCLE"],["BAMBOO","bamboo_planKey"],["BITBUCKET","BITBUCKET_COMMIT"],["BITRISE","BITRISE_IO"],["BUDDY","BUDDY_WORKSPACE_ID"],["BUILDKITE"],["CIRCLE","CIRCLECI"],["CIRRUS","CIRRUS_CI"],["CLOUDFLARE_PAGES","CF_PAGES",{ci:!0}],["CODEBUILD","CODEBUILD_BUILD_ARN"],["CODEFRESH","CF_BUILD_ID"],["DRONE"],["DRONE","DRONE_BUILD_EVENT"],["DSARI"],["GITHUB_ACTIONS"],["GITLAB","GITLAB_CI"],["GITLAB","CI_MERGE_REQUEST_ID"],["GOCD","GO_PIPELINE_LABEL"],["LAYERCI"],["HUDSON","HUDSON_URL"],["JENKINS","JENKINS_URL"],["MAGNUM"],["NETLIFY"],["NETLIFY","NETLIFY_LOCAL",{ci:!1}],["NEVERCODE"],["RENDER"],["SAIL","SAILCI"],["SEMAPHORE"],["SCREWDRIVER"],["SHIPPABLE"],["SOLANO","TDDIUM"],["STRIDER"],["TEAMCITY","TEAMCITY_VERSION"],["TRAVIS"],["VERCEL","NOW_BUILDER"],["VERCEL","VERCEL",{ci:!1}],["VERCEL","VERCEL_ENV",{ci:!1}],["APPCENTER","APPCENTER_BUILD_ID"],["CODESANDBOX","CODESANDBOX_SSE",{ci:!1}],["CODESANDBOX","CODESANDBOX_HOST",{ci:!1}],["STACKBLITZ"],["STORMKIT"],["CLEAVR"],["ZEABUR"],["CODESPHERE","CODESPHERE_APP_ID",{ci:!0}],["RAILWAY","RAILWAY_PROJECT_ID"],["RAILWAY","RAILWAY_SERVICE_ID"],["DENO-DEPLOY","DENO_DEPLOYMENT_ID"],["FIREBASE_APP_HOSTING","FIREBASE_APP_HOSTING",{ci:!0}]];EW=XQ();EW.name;iQ=globalThis.process?.platform||"",m$=o0(H0.CI)||EW.ci!==!1,gW=o0(globalThis.process?.stdout&&globalThis.process?.stdout.isTTY),UQ=o0(H0.DEBUG),a$=CQ==="test"||o0(H0.TEST);o0(H0.MINIMAL);YQ=/^win/i.test(iQ);!o0(H0.NO_COLOR)&&(o0(H0.FORCE_COLOR)||(gW||YQ)&&H0.TERM);MQ=(globalThis.process?.versions?.node||"").replace(/^v/,"")||null;Number(MQ?.split(".")[0]);OQ=globalThis.process||Object.create(null),FW={versions:{}};new Proxy(OQ,{get(D,u){if(u==="env")return H0;if(u in D)return D[u];if(u in FW)return FW[u]}});PQ=globalThis.process?.release?.name==="node",kQ=!!globalThis.Bun||!!globalThis.process?.versions?.bun,IQ=!!globalThis.Deno,VQ=!!globalThis.fastly,KQ=!!globalThis.Netlify,hQ=!!globalThis.EdgeRuntime,NQ=globalThis.navigator?.userAgent==="Cloudflare-Workers",QQ=[[KQ,"netlify"],[hQ,"edge-light"],[NQ,"workerd"],[VQ,"fastly"],[IQ,"deno"],[kQ,"bun"],[PQ,"node"]];qQ=LQ();qQ?.name;sQ=bQ();lQ=globalThis.Intl?.Segmenter?new Intl.Segmenter:{segment:(D)=>D.split("")},yQ=/^\p{Default_Ignorable_Code_Point}$/u;pQ={info:"cyan",fail:"red",success:"green",ready:"green",start:"magenta"},xQ={0:"red",1:"yellow"},mQ=tQ(),wW={error:Or("\u2716","\xD7"),fatal:Or("\u2716","\xD7"),ready:Or("\u2714","\u221A"),warn:Or("\u26A0","\u203C"),info:Or("\u2139","i"),success:Or("\u2714","\u221A"),debug:Or("\u2699","D"),trace:Or("\u2192","\u2192"),fail:Or("\u2716","\xD7"),start:Or("\u25D0","o"),log:""};SW=class SW extends mf{formatStack(D,u,r){let A=" ".repeat((r?.errorLevel||0)+1);return`
1575
+ ${A}`+Z$(D,u).map((f)=>" "+f.replace(/^at +/,(w)=>ru.gray(w)).replace(/\((.+)\)/,(w,F)=>`(${ru.cyan(F)})`)).join(`
1576
+ ${A}`)}formatType(D,u,r){let A=pQ[D.type]||xQ[D.level]||"gray";if(u)return eQ(A)(ru.black(` ${D.type.toUpperCase()} `));let f=typeof wW[D.type]==="string"?wW[D.type]:D.icon||D.type;return f?aQ(A)(f):""}formatLogObj(D,u){let[r,...A]=this.formatArgs(D.args,u).split(`
1577
+ `);if(D.type==="box")return KB(f3(r+(A.length>0?`
1578
1578
  `+A.join(`
1579
- `):"")),{title:D.title?af(D.title):void 0,style:D.style});let f=this.formatDate(D.date,u),w=f&&Du.gray(f),F=D.badge??D.level<2,E=this.formatType(D,F,u),$=D.tag?Du.gray(D.tag):"",g,R=this.filterAndJoin([E,af(r)]),S=this.filterAndJoin(u.columns?[$,w]:[$]),B=(u.columns||0)-vJ(R)-vJ(S)-2;if(g=B>0&&(u.columns||0)>=80?R+" ".repeat(B)+S:(S?`${Du.gray(`[${S}]`)} `:"")+R,g+=af(A.length>0?`
1579
+ `):"")),{title:D.title?f3(D.title):void 0,style:D.style});let f=this.formatDate(D.date,u),w=f&&ru.gray(f),F=D.badge??D.level<2,E=this.formatType(D,F,u),$=D.tag?ru.gray(D.tag):"",g,_=this.filterAndJoin([E,f3(r)]),R=this.filterAndJoin(u.columns?[$,w]:[$]),n=(u.columns||0)-$W(_)-$W(R)-2;if(g=n>0&&(u.columns||0)>=80?_+" ".repeat(n)+R:(R?`${ru.gray(`[${R}]`)} `:"")+_,g+=f3(A.length>0?`
1580
1580
  `+A.join(`
1581
- `):""),D.type==="trace"){let J=Error("Trace: "+D.message);g+=this.formatStack(J.stack||"",J.message)}return F?`
1581
+ `):""),D.type==="trace"){let B=Error("Trace: "+D.message);g+=this.formatStack(B.stack||"",B.message)}return F?`
1582
1582
  `+g+`
1583
- `:g}};vr=MQ()});function IA(D,u){var r={};for(var A in D)if(Object.prototype.hasOwnProperty.call(D,A)&&u.indexOf(A)<0)r[A]=D[A];if(D!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var f=0,A=Object.getOwnPropertySymbols(D);f<A.length;f++)if(u.indexOf(A[f])<0&&Object.prototype.propertyIsEnumerable.call(D,A[f]))r[A[f]]=D[A[f]]}return r}function p(D,u){var r;return((r=D===null||D===void 0?void 0:D._def)===null||r===void 0?void 0:r.typeName)===u}function qQ(D){return"_def"in D}function iA(D,u){let r=D.ZodType.prototype[u];D.ZodType.prototype[u]=function(...A){let f=r.apply(this,A);return f._def.openapi=this._def.openapi,f}}function aJ(D){if(typeof D.ZodType.prototype.openapi<"u")return;D.ZodType.prototype.openapi=function(f,w){var F,E,$,g,R,S;let B=typeof f==="string"?w:f,J=B!==null&&B!==void 0?B:{},{param:H}=J,G=IA(J,["param"]),U=Object.assign(Object.assign({},(F=this._def.openapi)===null||F===void 0?void 0:F._internal),typeof f==="string"?{refId:f}:void 0),O=Object.assign(Object.assign(Object.assign({},(E=this._def.openapi)===null||E===void 0?void 0:E.metadata),G),((g=($=this._def.openapi)===null||$===void 0?void 0:$.metadata)===null||g===void 0?void 0:g.param)||H?{param:Object.assign(Object.assign({},(S=(R=this._def.openapi)===null||R===void 0?void 0:R.metadata)===null||S===void 0?void 0:S.param),H)}:void 0),i=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(U).length>0?{_internal:U}:void 0),Object.keys(O).length>0?{metadata:O}:void 0)}));if(p(this,"ZodObject")){let k=this.extend;i.extend=function(...z){var q,M,s,h,rD,_D,WD;let e=k.apply(this,z);return e._def.openapi={_internal:{extendedFrom:((M=(q=this._def.openapi)===null||q===void 0?void 0:q._internal)===null||M===void 0?void 0:M.refId)?{refId:(h=(s=this._def.openapi)===null||s===void 0?void 0:s._internal)===null||h===void 0?void 0:h.refId,schema:this}:(_D=(rD=this._def.openapi)===null||rD===void 0?void 0:rD._internal)===null||_D===void 0?void 0:_D.extendedFrom},metadata:(WD=e._def.openapi)===null||WD===void 0?void 0:WD.metadata},e}}return i},iA(D,"optional"),iA(D,"nullable"),iA(D,"default"),iA(D,"transform"),iA(D,"refine");let u=D.ZodObject.prototype.deepPartial;D.ZodObject.prototype.deepPartial=function(){let f=this._def.shape(),w=u.apply(this),F=w._def.shape();return Object.entries(F).forEach(([E,$])=>{var g,R;$._def.openapi=(R=(g=f[E])===null||g===void 0?void 0:g._def)===null||R===void 0?void 0:R.openapi}),w._def.openapi=void 0,w};let r=D.ZodObject.prototype.pick;D.ZodObject.prototype.pick=function(...f){let w=r.apply(this,f);return w._def.openapi=void 0,w};let A=D.ZodObject.prototype.omit;D.ZodObject.prototype.omit=function(...f){let w=A.apply(this,f);return w._def.openapi=void 0,w}}function F3(D,u){if(D===null||D===void 0||u===null||u===void 0)return D===u;if(D===u||D.valueOf()===u.valueOf())return!0;if(Array.isArray(D)){if(!Array.isArray(u))return!1;if(D.length!==u.length)return!1}if(!(D instanceof Object)||!(u instanceof Object))return!1;let r=Object.keys(D);return Object.keys(u).every((A)=>r.indexOf(A)!==-1)&&r.every((A)=>F3(D[A],u[A]))}class eJ{constructor(){this.buckets=new Map}put(D){let u=this.hashCodeOf(D),r=this.buckets.get(u);if(!r){this.buckets.set(u,[D]);return}if(!r.some((f)=>F3(f,D)))r.push(D)}contains(D){let u=this.hashCodeOf(D),r=this.buckets.get(u);if(!r)return!1;return r.some((A)=>F3(A,D))}values(){return[...this.buckets.values()].flat()}stats(){let D=0,u=0,r=0;for(let f of this.buckets.values())if(D+=1,u+=f.length,f.length>1)r+=1;let A=D/u;return{totalBuckets:D,collisions:r,totalValues:u,hashEffectiveness:A}}hashCodeOf(D){let u=0;if(Array.isArray(D)){for(let r=0;r<D.length;r++)u^=this.hashCodeOf(D[r])*r;return u}if(typeof D==="string"){for(let r=0;r<D.length;r++)u^=D.charCodeAt(r)*r;return u}if(typeof D==="number")return D;if(typeof D==="object")for(let[r,A]of Object.entries(D))u^=this.hashCodeOf(r)+this.hashCodeOf(A!==null&&A!==void 0?A:"");return u}}function VA(D){return D===void 0}function KA(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{r[A]=u(f)}),r}function bQ(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{if(!u.some((w)=>w===A))r[A]=f}),r}function o2(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{if(!u(f,A))r[A]=f}),r}function pJ(D){return D.filter((u)=>!VA(u))}function zQ(D){let u=new eJ;return D.forEach((r)=>u.put(r)),[...u.values()]}function DW(D){return typeof D==="string"}class s${constructor(D){this.parents=D,this._definitions=[]}get definitions(){var D,u;return[...(u=(D=this.parents)===null||D===void 0?void 0:D.flatMap((A)=>A.definitions))!==null&&u!==void 0?u:[],...this._definitions]}register(D,u){let r=this.schemaWithRefId(D,u);return this._definitions.push({type:"schema",schema:r}),r}registerParameter(D,u){var r,A,f;let w=this.schemaWithRefId(D,u),F=(r=w._def.openapi)===null||r===void 0?void 0:r.metadata,E=w.openapi(Object.assign(Object.assign({},F),{param:Object.assign(Object.assign({},F===null||F===void 0?void 0:F.param),{name:(f=(A=F===null||F===void 0?void 0:F.param)===null||A===void 0?void 0:A.name)!==null&&f!==void 0?f:D})}));return this._definitions.push({type:"parameter",schema:E}),E}registerPath(D){this._definitions.push({type:"route",route:D})}registerWebhook(D){this._definitions.push({type:"webhook",webhook:D})}registerComponent(D,u,r){return this._definitions.push({type:"component",componentType:D,name:u,component:r}),{name:u,ref:{$ref:`#/components/${D}/${u}`}}}schemaWithRefId(D,u){return u.openapi(D)}}class NA{constructor(D){this.message=D}}function kA(D,u){try{return D()}catch(r){if(r instanceof hA)throw new hA(Object.assign(Object.assign({},r.data),u));throw r}}class JD{static getMetadata(D){var u;let r=this.unwrapChained(D),A=D._def.openapi?D._def.openapi:r._def.openapi,f=(u=D.description)!==null&&u!==void 0?u:r.description;return{_internal:A===null||A===void 0?void 0:A._internal,metadata:Object.assign({description:f},A===null||A===void 0?void 0:A.metadata)}}static getInternalMetadata(D){let u=this.unwrapChained(D),r=D._def.openapi?D._def.openapi:u._def.openapi;return r===null||r===void 0?void 0:r._internal}static getParamMetadata(D){var u,r;let A=this.unwrapChained(D),f=D._def.openapi?D._def.openapi:A._def.openapi,w=(u=D.description)!==null&&u!==void 0?u:A.description;return{_internal:f===null||f===void 0?void 0:f._internal,metadata:Object.assign(Object.assign({},f===null||f===void 0?void 0:f.metadata),{param:Object.assign({description:w},(r=f===null||f===void 0?void 0:f.metadata)===null||r===void 0?void 0:r.param)})}}static buildSchemaMetadata(D){return o2(bQ(D,["param"]),VA)}static buildParameterMetadata(D){return o2(D,VA)}static applySchemaMetadata(D,u){return o2(Object.assign(Object.assign({},D),this.buildSchemaMetadata(u)),VA)}static getRefId(D){var u;return(u=this.getInternalMetadata(D))===null||u===void 0?void 0:u.refId}static unwrapChained(D){return this.unwrapUntil(D)}static getDefaultValue(D){let u=this.unwrapUntil(D,"ZodDefault");return u===null||u===void 0?void 0:u._def.defaultValue()}static unwrapUntil(D,u){if(u&&p(D,u))return D;if(p(D,"ZodOptional")||p(D,"ZodNullable")||p(D,"ZodBranded"))return this.unwrapUntil(D.unwrap(),u);if(p(D,"ZodDefault")||p(D,"ZodReadonly"))return this.unwrapUntil(D._def.innerType,u);if(p(D,"ZodEffects"))return this.unwrapUntil(D._def.schema,u);if(p(D,"ZodPipeline"))return this.unwrapUntil(D._def.in,u);return u?void 0:D}static isOptionalSchema(D){return D.isOptional()}}class rW{transform(D,u,r){var A,f;let w=D._def.type;return Object.assign(Object.assign({},u("array")),{items:r(w),minItems:(A=D._def.minLength)===null||A===void 0?void 0:A.value,maxItems:(f=D._def.maxLength)===null||f===void 0?void 0:f.value})}}class AW{transform(D){return Object.assign(Object.assign({},D("string")),{pattern:"^d+$"})}}class fW{transform(D,u,r,A,f){let w=[...D.options.values()],F=w.map(A);if(u)return{oneOf:r(F,u)};return{oneOf:F,discriminator:this.mapDiscriminator(w,D.discriminator,f)}}mapDiscriminator(D,u,r){if(D.some((f)=>JD.getRefId(f)===void 0))return;let A={};return D.forEach((f)=>{var w;let F=JD.getRefId(f),E=(w=f.shape)===null||w===void 0?void 0:w[u];if(p(E,"ZodEnum")||p(E,"ZodNativeEnum")){Object.values(E.enum).filter(DW).forEach((R)=>{A[R]=r(F)});return}let $=E===null||E===void 0?void 0:E._def.value;if(typeof $!=="string")throw Error(`Discriminator ${u} could not be found in one of the values of a discriminated union`);A[$]=r(F)}),{propertyName:u,mapping:A}}}class FW{transform(D,u){return Object.assign(Object.assign({},u("string")),{enum:D._def.values})}}class wW{transform(D,u,r,A){let w={allOf:this.flattenIntersectionTypes(D).map(A)};if(u)return{anyOf:r([w],u)};return w}flattenIntersectionTypes(D){if(!p(D,"ZodIntersection"))return[D];let u=this.flattenIntersectionTypes(D._def.left),r=this.flattenIntersectionTypes(D._def.right);return[...u,...r]}}class $W{transform(D,u){return Object.assign(Object.assign({},u(typeof D._def.value)),{enum:[D._def.value]})}}function jQ(D){let r=Object.keys(D).filter((w)=>typeof D[D[w]]!=="number").map((w)=>D[w]),A=r.filter((w)=>typeof w==="number").length,f=A===0?"string":A===r.length?"numeric":"mixed";return{values:r,type:f}}class EW{transform(D,u){let{type:r,values:A}=jQ(D._def.values);if(r==="mixed")throw new NA("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},u(r==="numeric"?"integer":"string")),{enum:A})}}class gW{transform(D,u,r){return Object.assign(Object.assign({},u(D.isInt?"integer":"number")),r(D._def.checks))}}class _W{transform(D,u,r,A){var f;let w=(f=JD.getInternalMetadata(D))===null||f===void 0?void 0:f.extendedFrom,F=this.requiredKeysOf(D),E=KA(D._def.shape(),A);if(!w)return Object.assign(Object.assign(Object.assign(Object.assign({},r("object")),{properties:E,default:u}),F.length>0?{required:F}:{}),this.generateAdditionalProperties(D,A));let $=w.schema;A($);let g=this.requiredKeysOf($),R=KA($===null||$===void 0?void 0:$._def.shape(),A),S=Object.fromEntries(Object.entries(E).filter(([H,G])=>{return!v$(R[H],G)})),B=F.filter((H)=>!g.includes(H)),J=Object.assign(Object.assign(Object.assign(Object.assign({},r("object")),{default:u,properties:S}),B.length>0?{required:B}:{}),this.generateAdditionalProperties(D,A));return{allOf:[{$ref:`#/components/schemas/${w.refId}`},J]}}generateAdditionalProperties(D,u){let r=D._def.unknownKeys,A=D._def.catchall;if(p(A,"ZodNever")){if(r==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:u(A)}}requiredKeysOf(D){return Object.entries(D._def.shape()).filter(([u,r])=>!JD.isOptionalSchema(r)).map(([u,r])=>u)}}class RW{transform(D,u,r){let A=D._def.valueType,f=D._def.keyType,w=r(A);if(p(f,"ZodEnum")||p(f,"ZodNativeEnum")){let E=Object.values(f.enum).filter(DW).reduce(($,g)=>Object.assign(Object.assign({},$),{[g]:w}),{});return Object.assign(Object.assign({},u("object")),{properties:E})}return Object.assign(Object.assign({},u("object")),{additionalProperties:w})}}class SW{transform(D,u){var r,A,f;let w=this.getZodStringCheck(D,"regex"),F=(r=this.getZodStringCheck(D,"length"))===null||r===void 0?void 0:r.value,E=Number.isFinite(D.minLength)?(A=D.minLength)!==null&&A!==void 0?A:void 0:void 0,$=Number.isFinite(D.maxLength)?(f=D.maxLength)!==null&&f!==void 0?f:void 0:void 0;return Object.assign(Object.assign({},u("string")),{minLength:F!==null&&F!==void 0?F:E,maxLength:F!==null&&F!==void 0?F:$,format:this.mapStringFormat(D),pattern:w===null||w===void 0?void 0:w.regex.source})}mapStringFormat(D){if(D.isUUID)return"uuid";if(D.isEmail)return"email";if(D.isURL)return"uri";if(D.isDate)return"date";if(D.isDatetime)return"date-time";if(D.isCUID)return"cuid";if(D.isCUID2)return"cuid2";if(D.isULID)return"ulid";if(D.isIP)return"ip";if(D.isEmoji)return"emoji";return}getZodStringCheck(D,u){return D._def.checks.find((r)=>{return r.kind===u})}}class BW{constructor(D){this.versionSpecifics=D}transform(D,u,r){let{items:A}=D._def,f=A.map(r);return Object.assign(Object.assign({},u("array")),this.versionSpecifics.mapTupleItems(f))}}class JW{transform(D,u,r){let f=this.flattenUnionTypes(D).map((w)=>{let F=this.unwrapNullable(w);return r(F)});return{anyOf:u(f)}}flattenUnionTypes(D){if(!p(D,"ZodUnion"))return[D];return D._def.options.flatMap((r)=>this.flattenUnionTypes(r))}unwrapNullable(D){if(p(D,"ZodNullable"))return this.unwrapNullable(D.unwrap());return D}}class WW{constructor(D){this.versionSpecifics=D,this.objectTransformer=new _W,this.stringTransformer=new SW,this.numberTransformer=new gW,this.bigIntTransformer=new AW,this.literalTransformer=new $W,this.enumTransformer=new FW,this.nativeEnumTransformer=new EW,this.arrayTransformer=new rW,this.unionTransformer=new JW,this.discriminatedUnionTransformer=new fW,this.intersectionTransformer=new wW,this.recordTransformer=new RW,this.tupleTransformer=new BW(D)}transform(D,u,r,A,f){if(p(D,"ZodNull"))return this.versionSpecifics.nullType;if(p(D,"ZodUnknown")||p(D,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,u);if(p(D,"ZodObject"))return this.objectTransformer.transform(D,f,(F)=>this.versionSpecifics.mapNullableType(F,u),r);let w=this.transformSchemaWithoutDefault(D,u,r,A);return Object.assign(Object.assign({},w),{default:f})}transformSchemaWithoutDefault(D,u,r,A){if(p(D,"ZodUnknown")||p(D,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,u);if(p(D,"ZodString"))return this.stringTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(p(D,"ZodNumber"))return this.numberTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),(w)=>this.versionSpecifics.getNumberChecks(w));if(p(D,"ZodBigInt"))return this.bigIntTransformer.transform((w)=>this.versionSpecifics.mapNullableType(w,u));if(p(D,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",u);if(p(D,"ZodLiteral"))return this.literalTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(p(D,"ZodEnum"))return this.enumTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(p(D,"ZodNativeEnum"))return this.nativeEnumTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(p(D,"ZodArray"))return this.arrayTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(p(D,"ZodTuple"))return this.tupleTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(p(D,"ZodUnion"))return this.unionTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r);if(p(D,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform(D,u,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r,A);if(p(D,"ZodIntersection"))return this.intersectionTransformer.transform(D,u,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r);if(p(D,"ZodRecord"))return this.recordTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(p(D,"ZodDate"))return this.versionSpecifics.mapNullableType("string",u);let f=JD.getRefId(D);throw new uW({currentSchema:D._def,schemaName:f})}}class Z${constructor(D,u){this.definitions=D,this.versionSpecifics=u,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new WW(u),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach((D)=>this.generateSingle(D)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach((D)=>this.generateSingle(D)),{components:this.buildComponents()}}buildComponents(){var D,u;let r={};return this.rawComponents.forEach(({componentType:A,name:f,component:w})=>{var F;(F=r[A])!==null&&F!==void 0||(r[A]={}),r[A][f]=w}),Object.assign(Object.assign({},r),{schemas:Object.assign(Object.assign({},(D=r.schemas)!==null&&D!==void 0?D:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(u=r.parameters)!==null&&u!==void 0?u:{}),this.paramRefs)})}sortDefinitions(){let D=["schema","parameter","component","route"];this.definitions.sort((u,r)=>{if(!("type"in u)){if(!("type"in r))return 0;return-1}if(!("type"in r))return 1;let A=D.findIndex((w)=>w===u.type),f=D.findIndex((w)=>w===r.type);return A-f})}generateSingle(D){if(!("type"in D)){this.generateSchemaWithRef(D);return}switch(D.type){case"parameter":this.generateParameterDefinition(D.schema);return;case"schema":this.generateSchemaWithRef(D.schema);return;case"route":this.generateSingleRoute(D.route);return;case"component":this.rawComponents.push(D);return}}generateParameterDefinition(D){let u=JD.getRefId(D),r=this.generateParameter(D);if(u)this.paramRefs[u]=r;return r}getParameterRef(D,u){var r,A,f,w,F;let E=(r=D===null||D===void 0?void 0:D.metadata)===null||r===void 0?void 0:r.param,$=((A=D===null||D===void 0?void 0:D._internal)===null||A===void 0?void 0:A.refId)?this.paramRefs[(f=D._internal)===null||f===void 0?void 0:f.refId]:void 0;if(!((w=D===null||D===void 0?void 0:D._internal)===null||w===void 0?void 0:w.refId)||!$)return;if(E&&$.in!==E.in||(u===null||u===void 0?void 0:u.in)&&$.in!==u.in)throw new Z2(`Conflicting location for parameter ${$.name}`,{key:"in",values:pJ([$.in,u===null||u===void 0?void 0:u.in,E===null||E===void 0?void 0:E.in])});if(E&&$.name!==E.name||(u===null||u===void 0?void 0:u.name)&&$.name!==(u===null||u===void 0?void 0:u.name))throw new Z2("Conflicting names for parameter",{key:"name",values:pJ([$.name,u===null||u===void 0?void 0:u.name,E===null||E===void 0?void 0:E.name])});return{$ref:`#/components/parameters/${(F=D._internal)===null||F===void 0?void 0:F.refId}`}}generateInlineParameters(D,u){var r;let A=JD.getMetadata(D),f=(r=A===null||A===void 0?void 0:A.metadata)===null||r===void 0?void 0:r.param,w=this.getParameterRef(A,{in:u});if(w)return[w];if(p(D,"ZodObject")){let F=D._def.shape();return Object.entries(F).map(([$,g])=>{var R,S;let B=JD.getMetadata(g),J=this.getParameterRef(B,{in:u,name:$});if(J)return J;let H=(R=B===null||B===void 0?void 0:B.metadata)===null||R===void 0?void 0:R.param;if((H===null||H===void 0?void 0:H.name)&&H.name!==$)throw new Z2("Conflicting names for parameter",{key:"name",values:[$,H.name]});if((H===null||H===void 0?void 0:H.in)&&H.in!==u)throw new Z2(`Conflicting location for parameter ${(S=H.name)!==null&&S!==void 0?S:$}`,{key:"in",values:[u,H.in]});return this.generateParameter(g.openapi({param:{name:$,in:u}}))})}if((f===null||f===void 0?void 0:f.in)&&f.in!==u)throw new Z2(`Conflicting location for parameter ${f.name}`,{key:"in",values:[u,f.in]});return[this.generateParameter(D.openapi({param:{in:u}}))]}generateSimpleParameter(D){var u;let r=JD.getParamMetadata(D),A=(u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.param,f=!JD.isOptionalSchema(D)&&!D.isNullable(),w=this.generateSchemaWithRef(D);return Object.assign({schema:w,required:f},A?JD.buildParameterMetadata(A):{})}generateParameter(D){var u;let r=JD.getMetadata(D),A=(u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.param,f=A===null||A===void 0?void 0:A.name,w=A===null||A===void 0?void 0:A.in;if(!f)throw new hA({missingField:"name"});if(!w)throw new hA({missingField:"in",paramName:f});let F=this.generateSimpleParameter(D);return Object.assign(Object.assign({},F),{in:w,name:f})}generateSchemaWithMetadata(D){var u;let r=JD.unwrapChained(D),A=JD.getMetadata(D),f=JD.getDefaultValue(D),w=((u=A===null||A===void 0?void 0:A.metadata)===null||u===void 0?void 0:u.type)?{type:A===null||A===void 0?void 0:A.metadata.type}:this.toOpenAPISchema(r,D.isNullable(),f);return(A===null||A===void 0?void 0:A.metadata)?JD.applySchemaMetadata(w,A.metadata):o2(w,VA)}constructReferencedOpenAPISchema(D){var u;let r=JD.getMetadata(D),A=JD.unwrapChained(D),f=JD.getDefaultValue(D),w=D.isNullable();if((u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.type)return this.versionSpecifics.mapNullableType(r.metadata.type,w);return this.toOpenAPISchema(A,w,f)}generateSimpleSchema(D){var u;let r=JD.getMetadata(D),A=JD.getRefId(D);if(!A||!this.schemaRefs[A])return this.generateSchemaWithMetadata(D);let f=this.schemaRefs[A],w={$ref:this.generateSchemaRef(A)},F=o2(JD.buildSchemaMetadata((u=r===null||r===void 0?void 0:r.metadata)!==null&&u!==void 0?u:{}),(g,R)=>g===void 0||v$(g,f[R]));if(F.type)return{allOf:[w,F]};let E=o2(this.constructReferencedOpenAPISchema(D),(g,R)=>g===void 0||v$(g,f[R])),$=JD.applySchemaMetadata(E,F);if(Object.keys($).length>0)return{allOf:[w,$]};return w}generateSchemaWithRef(D){let u=JD.getRefId(D),r=this.generateSimpleSchema(D);if(u&&this.schemaRefs[u]===void 0)return this.schemaRefs[u]=r,{$ref:this.generateSchemaRef(u)};return r}generateSchemaRef(D){return`#/components/schemas/${D}`}getRequestBody(D){if(!D)return;let{content:u}=D,r=IA(D,["content"]),A=this.getBodyContent(u);return Object.assign(Object.assign({},r),{content:A})}getParameters(D){if(!D)return[];let{headers:u}=D,r=this.cleanParameter(D.query),A=this.cleanParameter(D.params),f=this.cleanParameter(D.cookies),w=kA(()=>r?this.generateInlineParameters(r,"query"):[],{location:"query"}),F=kA(()=>A?this.generateInlineParameters(A,"path"):[],{location:"path"}),E=kA(()=>f?this.generateInlineParameters(f,"cookie"):[],{location:"cookie"}),$=kA(()=>{if(Array.isArray(u))return u.flatMap((R)=>this.generateInlineParameters(R,"header"));let g=this.cleanParameter(u);return g?this.generateInlineParameters(g,"header"):[]},{location:"header"});return[...F,...w,...$,...E]}cleanParameter(D){if(!D)return;return p(D,"ZodEffects")?this.cleanParameter(D._def.schema):D}generatePath(D){let{method:u,path:r,request:A,responses:f}=D,w=IA(D,["method","path","request","responses"]),F=KA(f,(R)=>{return this.getResponse(R)}),E=kA(()=>this.getParameters(A),{route:`${u} ${r}`}),$=this.getRequestBody(A===null||A===void 0?void 0:A.body);return{[u]:Object.assign(Object.assign(Object.assign(Object.assign({},w),E.length>0?{parameters:[...w.parameters||[],...E]}:{}),$?{requestBody:$}:{}),{responses:F})}}generateSingleRoute(D){let u=this.generatePath(D);return this.pathRefs[D.path]=Object.assign(Object.assign({},this.pathRefs[D.path]),u),u}getResponse(D){if(this.isReferenceObject(D))return D;let{content:u,headers:r}=D,A=IA(D,["content","headers"]),f=u?{content:this.getBodyContent(u)}:{};if(!r)return Object.assign(Object.assign({},A),f);let w=p(r,"ZodObject")?this.getResponseHeaders(r):r;return Object.assign(Object.assign(Object.assign({},A),{headers:w}),f)}isReferenceObject(D){return"$ref"in D}getResponseHeaders(D){let u=D._def.shape();return KA(u,(A)=>this.generateSimpleParameter(A))}getBodyContent(D){return KA(D,(u)=>{if(!u||!qQ(u.schema))return u;let{schema:r}=u,A=IA(u,["schema"]),f=this.generateSchemaWithRef(r);return Object.assign({schema:f},A)})}toOpenAPISchema(D,u,r){return this.openApiTransformer.transform(D,u,(A)=>this.generateSchemaWithRef(A),(A)=>this.generateSchemaRef(A),r)}}class GW{get nullType(){return{nullable:!0}}mapNullableOfArray(D,u){if(u)return[...D,this.nullType];return D}mapNullableType(D,u){return Object.assign(Object.assign({},D?{type:D}:void 0),u?this.nullType:void 0)}mapTupleItems(D){let u=zQ(D);return{items:u.length===1?u[0]:{anyOf:u},minItems:D.length,maxItems:D.length}}getNumberChecks(D){return Object.assign({},...D.map((u)=>{switch(u.kind){case"min":return u.inclusive?{minimum:Number(u.value)}:{minimum:Number(u.value),exclusiveMinimum:!0};case"max":return u.inclusive?{maximum:Number(u.value)}:{maximum:Number(u.value),exclusiveMaximum:!0};default:return{}}}))}}class o${constructor(D){let u=new GW;this.generator=new Z$(D,u)}generateDocument(D){let u=this.generator.generateDocumentData();return Object.assign(Object.assign({},D),u)}generateComponents(){return this.generator.generateComponents()}}class CW{get nullType(){return{type:"null"}}mapNullableOfArray(D,u){if(u)return[...D,this.nullType];return D}mapNullableType(D,u){if(!D)return{};if(u)return{type:Array.isArray(D)?[...D,"null"]:[D,"null"]};return{type:D}}mapTupleItems(D){return{prefixItems:D}}getNumberChecks(D){return Object.assign({},...D.map((u)=>{switch(u.kind){case"min":return u.inclusive?{minimum:Number(u.value)}:{exclusiveMinimum:Number(u.value)};case"max":return u.inclusive?{maximum:Number(u.value)}:{exclusiveMaximum:Number(u.value)};default:return{}}}))}}function TQ(D){return"type"in D&&D.type==="webhook"}class d${constructor(D){this.definitions=D,this.webhookRefs={};let u=new CW;this.generator=new Z$(this.definitions,u)}generateDocument(D){let u=this.generator.generateDocumentData();return this.definitions.filter(TQ).forEach((r)=>this.generateSingleWebhook(r.webhook)),Object.assign(Object.assign(Object.assign({},D),u),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook(D){let u=this.generator.generatePath(D);return this.webhookRefs[D.path]=Object.assign(Object.assign({},this.webhookRefs[D.path]),u),u}}var v$,Z2,hA,uW;var HW=W(()=>{v$=F3;Z2=class Z2 extends NA{constructor(D,u){super(D);this.data=u}};hA=class hA extends NA{constructor(D){super(`Missing parameter data, please specify \`${D.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=D}};uW=class uW extends NA{constructor(D){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=D}}});var l$=(D)=>{let u=D.split("/");if(u[0]==="")u.shift();return u},nW=(D)=>{let{groups:u,path:r}=vQ(D),A=l$(r);return sQ(A,u)},vQ=(D)=>{let u=[];return D=D.replace(/\{[^}]+\}/g,(r,A)=>{let f=`@${A}`;return u.push([f,r]),f}),{groups:u,path:D}},sQ=(D,u)=>{for(let r=u.length-1;r>=0;r--){let[A]=u[r];for(let f=D.length-1;f>=0;f--)if(D[f].includes(A)){D[f]=D[f].replace(A,u[r][1]);break}}return D},w3,UW=(D,u)=>{if(D==="*")return"*";let r=D.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let A=`${D}#${u}`;if(!w3[A])if(r[2])w3[A]=u&&u[0]!==":"&&u[0]!=="*"?[A,r[1],new RegExp(`^${r[2]}(?=/${u})`)]:[D,r[1],new RegExp(`^${r[2]}$`)];else w3[A]=[D,r[1],!0];return w3[A]}return null},d2=(D,u)=>{try{return u(D)}catch{return D.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return u(r)}catch{return r}})}},ZQ=(D)=>d2(D,decodeURI),c$=(D)=>{let u=D.url,r=u.indexOf("/",u.indexOf(":")+4),A=r;for(;A<u.length;A++){let f=u.charCodeAt(A);if(f===37){let w=u.indexOf("?",A),F=u.indexOf("#",A),E=w===-1?F===-1?void 0:F:F===-1?w:Math.min(w,F),$=u.slice(r,E);return ZQ($.includes("%25")?$.replace(/%25/g,"%2525"):$)}else if(f===63||f===35)break}return u.slice(r,A)},XW=(D)=>{let u=c$(D);return u.length>1&&u.at(-1)==="/"?u.slice(0,-1):u},pu=(D,u,...r)=>{if(r.length)u=pu(u,...r);return`${D?.[0]==="/"?"":"/"}${D}${u==="/"?"":`${D?.at(-1)==="/"?"":"/"}${u?.[0]==="/"?u.slice(1):u}`}`},$3=(D)=>{if(D.charCodeAt(D.length-1)!==63||!D.includes(":"))return null;let u=D.split("/"),r=[],A="";return u.forEach((f)=>{if(f!==""&&!/\:/.test(f))A+="/"+f;else if(/\:/.test(f))if(/\?/.test(f)){if(r.length===0&&A==="")r.push("/");else r.push(A);let w=f.replace("?","");A+="/"+w,r.push(A)}else A+="/"+f}),r.filter((f,w,F)=>F.indexOf(f)===w)},y$=(D)=>{if(!/[%+]/.test(D))return D;if(D.indexOf("+")!==-1)D=D.replace(/\+/g," ");return D.indexOf("%")!==-1?d2(D,QA):D},YW=(D,u,r)=>{let A;if(!r&&u&&!/[%+]/.test(u)){let F=D.indexOf("?",8);if(F===-1)return;if(!D.startsWith(u,F+1))F=D.indexOf(`&${u}`,F+1);while(F!==-1){let E=D.charCodeAt(F+u.length+1);if(E===61){let $=F+u.length+2,g=D.indexOf("&",$);return y$(D.slice($,g===-1?void 0:g))}else if(E==38||isNaN(E))return"";F=D.indexOf(`&${u}`,F+1)}if(A=/[%+]/.test(D),!A)return}let f={};A??=/[%+]/.test(D);let w=D.indexOf("?",8);while(w!==-1){let F=D.indexOf("&",w+1),E=D.indexOf("=",w);if(E>F&&F!==-1)E=-1;let $=D.slice(w+1,E===-1?F===-1?void 0:F:E);if(A)$=y$($);if(w=F,$==="")continue;let g;if(E===-1)g="";else if(g=D.slice(E+1,F===-1?void 0:F),A)g=y$(g);if(r){if(!(f[$]&&Array.isArray(f[$])))f[$]=[];f[$].push(g)}else f[$]??=g}return u?f[u]:f},MW,OW=(D,u)=>{return YW(D,u,!0)},QA;var U0=W(()=>{w3={},MW=YW,QA=decodeURIComponent});var oQ,dQ,PW=(D)=>{let u=0,r=D.length;while(u<r){let A=D.charCodeAt(u);if(A!==32&&A!==9)break;u++}while(r>u){let A=D.charCodeAt(r-1);if(A!==32&&A!==9)break;r--}return u===0&&r===D.length?D:D.slice(u,r)},t$=(D,u)=>{if(u&&D.indexOf(u)===-1)return{};let r=D.split(";"),A={};for(let f of r){let w=f.indexOf("=");if(w===-1)continue;let F=PW(f.substring(0,w));if(u&&u!==F||!oQ.test(F))continue;let E=PW(f.substring(w+1));if(E.startsWith('"')&&E.endsWith('"'))E=E.slice(1,-1);if(dQ.test(E)){if(A[F]=E.indexOf("%")!==-1?d2(E,QA):E,u)break}}return A};var iW=W(()=>{U0();oQ=/^[\w!#$%&'*.^`|~+-]+$/,dQ=/^[ !#-:<-[\]-~]*$/});var kW=(D,u,r)=>{let A=D.req.raw.headers.get("Cookie");if(typeof u==="string"){if(!A)return;let w=u;if(r==="secure")w="__Secure-"+u;else if(r==="host")w="__Host-"+u;return t$(A,w)[w]}if(!A)return{};return t$(A)};var IW=W(()=>{iW()});var E3;var x$=W(()=>{E3=class extends Error{res;status;constructor(D=500,u){super(u?.message,{cause:u?.cause});this.res=u?.res,this.status=D}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var VW=()=>{};var KW=(D,u)=>{return new Response(D,{headers:{"Content-Type":u}}).formData()};var hW=W(()=>{VW()});var yQ,lQ,cQ,m$=(D,u)=>{return async(r,A)=>{let f={},w=r.req.header("Content-Type");switch(D){case"json":if(!w||!yQ.test(w))break;try{f=await r.req.json()}catch{throw new E3(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!w||!(lQ.test(w)||cQ.test(w)))break;let E;if(r.req.bodyCache.formData)E=await r.req.bodyCache.formData;else try{let g=await r.req.arrayBuffer();E=await KW(g,w),r.req.bodyCache.formData=E}catch(g){let R="Malformed FormData request.";throw R+=g instanceof Error?` ${g.message}`:` ${String(g)}`,new E3(400,{message:R})}let $=Object.create(null);E.forEach((g,R)=>{if(R.endsWith("[]"))($[R]??=[]).push(g);else if(Array.isArray($[R]))$[R].push(g);else if(Object.hasOwn($,R))$[R]=[$[R],g];else $[R]=g}),f=$;break}case"query":f=Object.fromEntries(Object.entries(r.req.queries()).map(([E,$])=>{return $.length===1?[E,$[0]]:[E,$]}));break;case"param":f=r.req.param();break;case"header":f=r.req.header();break;case"cookie":f=kW(r);break}let F=await u(f,r);if(F instanceof Response)return F;return r.req.addValidatedData(D,F),await A()}};var NW=W(()=>{IW();x$();hW();yQ=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,lQ=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,cQ=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var QW=W(()=>{NW()});function tQ(D,u,r,A){return m$(D,async(f,w)=>{let F=f;if(D==="header"&&"_def"in u||D==="header"&&"_zod"in u){let $=Object.keys("in"in u?u.in.shape:u.shape),g=Object.fromEntries($.map((R)=>[R.toLowerCase(),R]));F=Object.fromEntries(Object.entries(f).map(([R,S])=>[g[R]||R,S]))}let E=A&&A.validationFunction?await A.validationFunction(u,F):await u.safeParseAsync(F);if(r){let $=await r({data:F,...E,target:D},w);if($){if($ instanceof Response)return $;if("response"in $)return $.response}}if(!E.success)return w.json(E,400);return E.data})}var o0;var LW=W(()=>{QW();o0=tQ});var p$=(D,u,r)=>{return(A,f)=>{let w=-1;return F(0);async function F(E){if(E<=w)throw Error("next() called multiple times");w=E;let $,g=!1,R;if(D[E])R=D[E][0][0],A.req.routeIndex=E;else R=E===D.length&&f||void 0;if(R)try{$=await R(A,()=>F(E+1))}catch(S){if(S instanceof Error&&u)A.error=S,$=await u(S,A),g=!0;else throw S}else if(A.finalized===!1&&r)$=await r(A);if($&&(A.finalized===!1||g))A.res=$;return A}}};var qW=()=>{};var bW;var zW=W(()=>{bW=Symbol()});async function xQ(D,u){let r=await D.formData();if(r)return mQ(r,u);return{}}function mQ(D,u){let r=Object.create(null);if(D.forEach((A,f)=>{if(!(u.all||f.endsWith("[]")))r[f]=A;else pQ(r,f,A)}),u.dot)Object.entries(r).forEach(([A,f])=>{if(A.includes("."))aQ(r,A,f),delete r[A]});return r}var jW=async(D,u=Object.create(null))=>{let{all:r=!1,dot:A=!1}=u,w=(D instanceof g3?D.raw.headers:D.headers).get("Content-Type");if(w?.startsWith("multipart/form-data")||w?.startsWith("application/x-www-form-urlencoded"))return xQ(D,{all:r,dot:A});return{}},pQ=(D,u,r)=>{if(D[u]!==void 0)if(Array.isArray(D[u]))D[u].push(r);else D[u]=[D[u],r];else if(!u.endsWith("[]"))D[u]=r;else D[u]=[r]},aQ=(D,u,r)=>{if(/(?:^|\.)__proto__\./.test(u))return;let A=D,f=u.split(".");f.forEach((w,F)=>{if(F===f.length-1)A[w]=r;else{if(!A[w]||typeof A[w]!=="object"||Array.isArray(A[w])||A[w]instanceof File)A[w]=Object.create(null);A=A[w]}})};var TW=W(()=>{a$()});var vW=(D)=>d2(D,QA),g3;var a$=W(()=>{x$();zW();TW();U0();g3=class{raw;#D;#r;routeIndex=0;path;bodyCache={};constructor(D,u="/",r=[[]]){this.raw=D,this.path=u,this.#r=r,this.#D={}}param(D){return D?this.#A(D):this.#F()}#A(D){let u=this.#r[0][this.routeIndex][1][D],r=this.#u(u);return r&&/\%/.test(r)?vW(r):r}#F(){let D={},u=Object.keys(this.#r[0][this.routeIndex][1]);for(let r of u){let A=this.#u(this.#r[0][this.routeIndex][1][r]);if(A!==void 0)D[r]=/\%/.test(A)?vW(A):A}return D}#u(D){return this.#r[1]?this.#r[1][D]:D}query(D){return MW(this.url,D)}queries(D){return OW(this.url,D)}header(D){if(D)return this.raw.headers.get(D)??void 0;let u={};return this.raw.headers.forEach((r,A)=>{u[A]=r}),u}async parseBody(D){return jW(this,D)}#f=(D)=>{let{bodyCache:u,raw:r}=this,A=u[D];if(A)return A;let f=Object.keys(u)[0];if(f)return u[f].then((w)=>{if(f==="json")w=JSON.stringify(w);return new Response(w)[D]()});return u[D]=r[D]()};json(){return this.#f("text").then((D)=>JSON.parse(D))}text(){return this.#f("text")}arrayBuffer(){return this.#f("arrayBuffer")}blob(){return this.#f("blob")}formData(){return this.#f("formData")}addValidatedData(D,u){this.#D[D]=u}valid(D){return this.#D[D]}get url(){return this.raw.url}get method(){return this.raw.method}get[bW](){return this.#r}get matchedRoutes(){return this.#r[0].map(([[,D]])=>D)}get routePath(){return this.#r[0].map(([[,D]])=>D)[this.routeIndex].path}}});var sW,eQ=(D,u)=>{let r=new String(D);return r.isEscaped=!0,r.callbacks=u,r},e$=async(D,u,r,A,f)=>{if(typeof D==="object"&&!(D instanceof String)){if(!(D instanceof Promise))D=D.toString();if(D instanceof Promise)D=await D}let w=D.callbacks;if(!w?.length)return Promise.resolve(D);if(f)f[0]+=D;else f=[D];let F=Promise.all(w.map((E)=>E({phase:u,buffer:f,context:A}))).then((E)=>Promise.all(E.filter(Boolean).map(($)=>e$($,u,!1,A,f))).then(()=>f[0]));if(r)return eQ(await F,w);else return F};var ZW=W(()=>{sW={Stringify:1,BeforeStream:2,Stream:3}});var DL="text/plain; charset=UTF-8",D7=(D,u)=>{return{"Content-Type":D,...u}},LA=(D,u)=>new Response(D,u),oW=class{#D;#r;env={};#A;finalized=!1;error;#F;#u;#f;#_;#E;#g;#$;#R;#S;constructor(D,u){if(this.#D=D,u)this.#u=u.executionCtx,this.env=u.env,this.#g=u.notFoundHandler,this.#S=u.path,this.#R=u.matchResult}get req(){return this.#r??=new g3(this.#D,this.#S,this.#R),this.#r}get event(){if(this.#u&&"respondWith"in this.#u)return this.#u;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#u)return this.#u;else throw Error("This context has no ExecutionContext")}get res(){return this.#f||=LA(null,{headers:this.#$??=new Headers})}set res(D){if(this.#f&&D){D=LA(D.body,D);for(let[u,r]of this.#f.headers.entries()){if(u==="content-type")continue;if(u==="set-cookie"){let A=this.#f.headers.getSetCookie();D.headers.delete("set-cookie");for(let f of A)D.headers.append("set-cookie",f)}else D.headers.set(u,r)}}this.#f=D,this.finalized=!0}render=(...D)=>{return this.#E??=(u)=>this.html(u),this.#E(...D)};setLayout=(D)=>this.#_=D;getLayout=()=>this.#_;setRenderer=(D)=>{this.#E=D};header=(D,u,r)=>{if(this.finalized)this.#f=LA(this.#f.body,this.#f);let A=this.#f?this.#f.headers:this.#$??=new Headers;if(u===void 0)A.delete(D);else if(r?.append)A.append(D,u);else A.set(D,u)};status=(D)=>{this.#F=D};set=(D,u)=>{this.#A??=new Map,this.#A.set(D,u)};get=(D)=>{return this.#A?this.#A.get(D):void 0};get var(){if(!this.#A)return{};return Object.fromEntries(this.#A)}#w(D,u,r){let A=this.#f?new Headers(this.#f.headers):this.#$??new Headers;if(typeof u==="object"&&"headers"in u){let w=u.headers instanceof Headers?u.headers:new Headers(u.headers);for(let[F,E]of w)if(F.toLowerCase()==="set-cookie")A.append(F,E);else A.set(F,E)}if(r)for(let[w,F]of Object.entries(r))if(typeof F==="string")A.set(w,F);else{A.delete(w);for(let E of F)A.append(w,E)}let f=typeof u==="number"?u:u?.status??this.#F;return LA(D,{status:f,headers:A})}newResponse=(...D)=>this.#w(...D);body=(D,u,r)=>this.#w(D,u,r);text=(D,u,r)=>{return!this.#$&&!this.#F&&!u&&!r&&!this.finalized?new Response(D):this.#w(D,u,D7(DL,r))};json=(D,u,r)=>{return this.#w(JSON.stringify(D),u,D7("application/json",r))};html=(D,u,r)=>{let A=(f)=>this.#w(f,u,D7("text/html; charset=UTF-8",r));return typeof D==="object"?e$(D,sW.Stringify,!1,{}).then(A):A(D)};redirect=(D,u)=>{let r=String(D);return this.header("Location",!/[^\x00-\xFF]/.test(r)?r:encodeURI(r)),this.newResponse(null,u??302)};notFound=()=>{return this.#g??=()=>LA(),this.#g(this)}};var dW=W(()=>{a$();ZW()});var ED="ALL",yW="all",lW,_3="Can not add a route since the matcher is already built.",R3;var d0=W(()=>{lW=["get","post","put","delete","options","patch"],R3=class extends Error{}});var cW="__COMPOSED_HANDLER";var tW=()=>{};var uL=(D)=>{return D.text("404 Not Found",404)},xW=(D,u)=>{if("getResponse"in D){let r=D.getResponse();return u.newResponse(r.body,r)}return console.error(D),u.text("Internal Server Error",500)},mW=class D{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#D="/";routes=[];constructor(u={}){[...lW,yW].forEach((w)=>{this[w]=(F,...E)=>{if(typeof F==="string")this.#D=F;else this.#F(w,this.#D,F);return E.forEach(($)=>{this.#F(w,this.#D,$)}),this}}),this.on=(w,F,...E)=>{for(let $ of[F].flat()){this.#D=$;for(let g of[w].flat())E.map((R)=>{this.#F(g.toUpperCase(),this.#D,R)})}return this},this.use=(w,...F)=>{if(typeof w==="string")this.#D=w;else this.#D="*",F.unshift(w);return F.forEach((E)=>{this.#F(ED,this.#D,E)}),this};let{strict:A,...f}=u;Object.assign(this,f),this.getPath=A??!0?u.getPath??c$:XW}#r(){let u=new D({router:this.router,getPath:this.getPath});return u.errorHandler=this.errorHandler,u.#A=this.#A,u.routes=this.routes,u}#A=uL;errorHandler=xW;route(u,r){let A=this.basePath(u);return r.routes.map((f)=>{let w;if(r.errorHandler===xW)w=f.handler;else w=async(F,E)=>(await p$([],r.errorHandler)(F,()=>f.handler(F,E))).res,w[cW]=f.handler;A.#F(f.method,f.path,w)}),this}basePath(u){let r=this.#r();return r._basePath=pu(this._basePath,u),r}onError=(u)=>{return this.errorHandler=u,this};notFound=(u)=>{return this.#A=u,this};mount(u,r,A){let f,w;if(A)if(typeof A==="function")w=A;else if(w=A.optionHandler,A.replaceRequest===!1)f=($)=>$;else f=A.replaceRequest;let F=w?($)=>{let g=w($);return Array.isArray(g)?g:[g]}:($)=>{let g=void 0;try{g=$.executionCtx}catch{}return[$.env,g]};f||=(()=>{let $=pu(this._basePath,u),g=$==="/"?0:$.length;return(R)=>{let S=new URL(R.url);return S.pathname=S.pathname.slice(g)||"/",new Request(S,R)}})();let E=async($,g)=>{let R=await r(f($.req.raw),...F($));if(R)return R;await g()};return this.#F(ED,pu(u,"*"),E),this}#F(u,r,A){u=u.toUpperCase(),r=pu(this._basePath,r);let f={basePath:this._basePath,path:r,method:u,handler:A};this.router.add(u,r,[A,f]),this.routes.push(f)}#u(u,r){if(u instanceof Error)return this.errorHandler(u,r);throw u}#f(u,r,A,f){if(f==="HEAD")return(async()=>new Response(null,await this.#f(u,r,A,"GET")))();let w=this.getPath(u,{env:A}),F=this.router.match(f,w),E=new oW(u,{path:w,matchResult:F,env:A,executionCtx:r,notFoundHandler:this.#A});if(F[0].length===1){let g;try{g=F[0][0][0][0](E,async()=>{E.res=await this.#A(E)})}catch(R){return this.#u(R,E)}return g instanceof Promise?g.then((R)=>R||(E.finalized?E.res:this.#A(E))).catch((R)=>this.#u(R,E)):g??this.#A(E)}let $=p$(F[0],this.errorHandler,this.#A);return(async()=>{try{let g=await $(E);if(!g.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return g.res}catch(g){return this.#u(g,E)}})()}fetch=(u,...r)=>{return this.#f(u,r[1],r[0],u.method)};request=(u,r,A,f)=>{if(u instanceof Request)return this.fetch(r?new Request(u,r):u,A,f);return u=u.toString(),this.fetch(new Request(/^https?:\/\//.test(u)?u:`http://localhost${pu("/",u)}`,r),A,f)};fire=()=>{addEventListener("fetch",(u)=>{u.respondWith(this.#f(u.request,u,void 0,u.request.method))})}};var pW=W(()=>{qW();dW();d0();tW();U0()});function S3(D,u){let r=this.buildAllMatchers(),A=(f,w)=>{let F=r[f]||r[ED],E=F[2][w];if(E)return E;let $=w.match(F[0]);if(!$)return[[],qA];let g=$.indexOf("",1);return[F[1][g],$]};return this.match=A,A(D,u)}var qA;var u7=W(()=>{d0();qA=[]});function AL(D,u){if(D.length===1)return u.length===1?D<u?-1:1:-1;if(u.length===1)return 1;if(D===bA||D===zA)return 1;else if(u===bA||u===zA)return-1;if(D===B3)return 1;else if(u===B3)return-1;return D.length===u.length?D<u?-1:1:u.length-D.length}var B3="[^/]+",bA=".*",zA="(?:|/.*)",y0,rL,aW=class D{#D;#r;#A=Object.create(null);insert(u,r,A,f,w){if(u.length===0){if(this.#D!==void 0)throw y0;if(w)return;this.#D=r;return}let[F,...E]=u,$=F==="*"?E.length===0?["","",bA]:["","",B3]:F==="/*"?["","",zA]:F.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),g;if($){let R=$[1],S=$[2]||B3;if(R&&$[2]){if(S===".*")throw y0;if(S=S.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(S))throw y0}if(g=this.#A[S],!g){if(Object.keys(this.#A).some((B)=>B!==bA&&B!==zA))throw y0;if(w)return;if(g=this.#A[S]=new D,R!=="")g.#r=f.varIndex++}if(!w&&R!=="")A.push([R,g.#r])}else if(g=this.#A[F],!g){if(Object.keys(this.#A).some((R)=>R.length>1&&R!==bA&&R!==zA))throw y0;if(w)return;g=this.#A[F]=new D}g.insert(E,r,A,f,w)}buildRegExpStr(){let r=Object.keys(this.#A).sort(AL).map((A)=>{let f=this.#A[A];return(typeof f.#r==="number"?`(${A})@${f.#r}`:rL.has(A)?`\\${A}`:A)+f.buildRegExpStr()});if(typeof this.#D==="number")r.unshift(`#${this.#D}`);if(r.length===0)return"";if(r.length===1)return r[0];return"(?:"+r.join("|")+")"}};var r7=W(()=>{y0=Symbol(),rL=new Set(".\\+*[^]$()")});var eW=class{#D={varIndex:0};#r=new aW;insert(D,u,r){let A=[],f=[];for(let F=0;;){let E=!1;if(D=D.replace(/\{[^}]+\}/g,($)=>{let g=`@\\${F}`;return f[F]=[g,$],F++,E=!0,g}),!E)break}let w=D.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let F=f.length-1;F>=0;F--){let[E]=f[F];for(let $=w.length-1;$>=0;$--)if(w[$].indexOf(E)!==-1){w[$]=w[$].replace(E,f[F][1]);break}}return this.#r.insert(w,u,A,this.#D,r),A}buildRegExp(){let D=this.#r.buildRegExpStr();if(D==="")return[/^$/,[],[]];let u=0,r=[],A=[];return D=D.replace(/#(\d+)|@(\d+)|\.\*\$/g,(f,w,F)=>{if(w!==void 0)return r[++u]=Number(w),"$()";if(F!==void 0)return A[Number(F)]=++u,"";return""}),[new RegExp(`^${D}`),r,A]}};var DG=W(()=>{r7()});function rG(D){return uG[D]??=new RegExp(D==="*"?"":`^${D.replace(/\/\*$|([.\\+*[^\]$()])/g,(u,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function FL(){uG=Object.create(null)}function wL(D){let u=new eW,r=[];if(D.length===0)return fL;let A=D.map((g)=>[!/\*|\/:/.test(g[0]),...g]).sort(([g,R],[S,B])=>g?1:S?-1:R.length-B.length),f=Object.create(null);for(let g=0,R=-1,S=A.length;g<S;g++){let[B,J,H]=A[g];if(B)f[J]=[H.map(([U])=>[U,Object.create(null)]),qA];else R++;let G;try{G=u.insert(J,R,B)}catch(U){throw U===y0?new R3(J):U}if(B)continue;r[R]=H.map(([U,O])=>{let i=Object.create(null);O-=1;for(;O>=0;O--){let[k,z]=G[O];i[k]=z}return[U,i]})}let[w,F,E]=u.buildRegExp();for(let g=0,R=r.length;g<R;g++)for(let S=0,B=r[g].length;S<B;S++){let J=r[g][S]?.[1];if(!J)continue;let H=Object.keys(J);for(let G=0,U=H.length;G<U;G++)J[H[G]]=E[J[H[G]]]}let $=[];for(let g in F)$[g]=r[F[g]];return[w,$,f]}function y2(D,u){if(!D)return;for(let r of Object.keys(D).sort((A,f)=>f.length-A.length))if(rG(r).test(u))return[...D[r]];return}var fL,uG,J3=class{name="RegExpRouter";#D;#r;constructor(){this.#D={[ED]:Object.create(null)},this.#r={[ED]:Object.create(null)}}add(D,u,r){let A=this.#D,f=this.#r;if(!A||!f)throw Error(_3);if(!A[D])[A,f].forEach((E)=>{E[D]=Object.create(null),Object.keys(E[ED]).forEach(($)=>{E[D][$]=[...E[ED][$]]})});if(u==="/*")u="*";let w=(u.match(/\/:/g)||[]).length;if(/\*$/.test(u)){let E=rG(u);if(D===ED)Object.keys(A).forEach(($)=>{A[$][u]||=y2(A[$],u)||y2(A[ED],u)||[]});else A[D][u]||=y2(A[D],u)||y2(A[ED],u)||[];Object.keys(A).forEach(($)=>{if(D===ED||D===$)Object.keys(A[$]).forEach((g)=>{E.test(g)&&A[$][g].push([r,w])})}),Object.keys(f).forEach(($)=>{if(D===ED||D===$)Object.keys(f[$]).forEach((g)=>E.test(g)&&f[$][g].push([r,w]))});return}let F=$3(u)||[u];for(let E=0,$=F.length;E<$;E++){let g=F[E];Object.keys(f).forEach((R)=>{if(D===ED||D===R)f[R][g]||=[...y2(A[R],g)||y2(A[ED],g)||[]],f[R][g].push([r,w-$+E+1])})}}match=S3;buildAllMatchers(){let D=Object.create(null);return Object.keys(this.#r).concat(Object.keys(this.#D)).forEach((u)=>{D[u]||=this.#A(u)}),this.#D=this.#r=void 0,FL(),D}#A(D){let u=[],r=D===ED;if([this.#D,this.#r].forEach((A)=>{let f=A[D]?Object.keys(A[D]).map((w)=>[w,A[D][w]]):[];if(f.length!==0)r||=!0,u.push(...f);else if(D!==ED)u.push(...Object.keys(A[ED]).map((w)=>[w,A[ED][w]]))}),!r)return null;else return wL(u)}};var A7=W(()=>{d0();U0();u7();r7();DG();fL=[/^$/,[],Object.create(null)],uG=Object.create(null)});var $L=class{name="PreparedRegExpRouter";#D;#r;constructor(D,u){this.#D=D,this.#r=u}#A(D,u){let r=this.#D[D];r[1].forEach((A)=>A&&A.push(u)),Object.values(r[2]).forEach((A)=>A[0].push(u))}#F(D,u,r,A,f){let w=this.#D[D];if(!f)w[2][u][0].push([r,{}]);else A.forEach((F)=>{if(typeof F==="number")w[1][F].push([r,f]);else w[2][F||u][0].push([r,f])})}add(D,u,r){if(!this.#D[D]){let f=this.#D[ED],w={};for(let F in f[2])w[F]=[f[2][F][0].slice(),qA];this.#D[D]=[f[0],f[1].map((F)=>Array.isArray(F)?F.slice():0),w]}if(u==="/*"||u==="*"){let f=[r,{}];if(D===ED)for(let w in this.#D)this.#A(w,f);else this.#A(D,f);return}let A=this.#r[u];if(!A)throw Error(`Path ${u} is not registered`);for(let[f,w]of A)if(D===ED)for(let F in this.#D)this.#F(F,u,r,f,w);else this.#F(D,u,r,f,w)}buildAllMatchers(){return this.#D}match=S3};var AG=W(()=>{d0();u7();A7()});var fG=W(()=>{A7();AG()});var f7=class{name="SmartRouter";#D=[];#r=[];constructor(D){this.#D=D.routers}add(D,u,r){if(!this.#r)throw Error(_3);this.#r.push([D,u,r])}match(D,u){if(!this.#r)throw Error("Fatal error");let r=this.#D,A=this.#r,f=r.length,w=0,F;for(;w<f;w++){let E=r[w];try{for(let $=0,g=A.length;$<g;$++)E.add(...A[$]);F=E.match(D,u)}catch($){if($ instanceof R3)continue;throw $}this.match=E.match.bind(E),this.#D=[E],this.#r=void 0;break}if(w===f)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,F}get activeRouter(){if(this.#r||this.#D.length!==1)throw Error("No active router has been determined yet.");return this.#D[0]}};var FG=W(()=>{d0()});var wG=W(()=>{FG()});var jA,EL=(D)=>{for(let u in D)return!0;return!1},$G=class D{#D;#r;#A;#F=0;#u=jA;constructor(u,r,A){if(this.#r=A||Object.create(null),this.#D=[],u&&r){let f=Object.create(null);f[u]={handler:r,possibleKeys:[],score:0},this.#D=[f]}this.#A=[]}insert(u,r,A){this.#F=++this.#F;let f=this,w=nW(r),F=[];for(let E=0,$=w.length;E<$;E++){let g=w[E],R=w[E+1],S=UW(g,R),B=Array.isArray(S)?S[0]:g;if(B in f.#r){if(f=f.#r[B],S)F.push(S[1]);continue}if(f.#r[B]=new D,S)f.#A.push(S),F.push(S[1]);f=f.#r[B]}return f.#D.push({[u]:{handler:A,possibleKeys:F.filter((E,$,g)=>g.indexOf(E)===$),score:this.#F}}),f}#f(u,r,A,f,w){for(let F=0,E=r.#D.length;F<E;F++){let $=r.#D[F],g=$[A]||$[ED],R={};if(g!==void 0){if(g.params=Object.create(null),u.push(g),f!==jA||w&&w!==jA)for(let S=0,B=g.possibleKeys.length;S<B;S++){let J=g.possibleKeys[S],H=R[g.score];g.params[J]=w?.[J]&&!H?w[J]:f[J]??w?.[J],R[g.score]=!0}}}}search(u,r){let A=[];this.#u=jA;let w=[this],F=l$(r),E=[],$=F.length,g=null;for(let R=0;R<$;R++){let S=F[R],B=R===$-1,J=[];for(let G=0,U=w.length;G<U;G++){let O=w[G],i=O.#r[S];if(i)if(i.#u=O.#u,B){if(i.#r["*"])this.#f(A,i.#r["*"],u,O.#u);this.#f(A,i,u,O.#u)}else J.push(i);for(let k=0,z=O.#A.length;k<z;k++){let q=O.#A[k],M=O.#u===jA?{}:{...O.#u};if(q==="*"){let WD=O.#r["*"];if(WD)this.#f(A,WD,u,O.#u),WD.#u=M,J.push(WD);continue}let[s,h,rD]=q;if(!S&&!(rD instanceof RegExp))continue;let _D=O.#r[s];if(rD instanceof RegExp){if(g===null){g=Array($);let QD=r[0]==="/"?1:0;for(let rr=0;rr<$;rr++)g[rr]=QD,QD+=F[rr].length+1}let WD=r.substring(g[R]),e=rD.exec(WD);if(e){if(M[h]=e[0],this.#f(A,_D,u,O.#u,M),EL(_D.#r)){_D.#u=M;let QD=e[0].match(/\//)?.length??0;(E[QD]||=[]).push(_D)}continue}}if(rD===!0||rD.test(S))if(M[h]=S,B){if(this.#f(A,_D,u,M,O.#u),_D.#r["*"])this.#f(A,_D.#r["*"],u,M,O.#u)}else _D.#u=M,J.push(_D)}}let H=E.shift();w=H?J.concat(H):J}if(A.length>1)A.sort((R,S)=>{return R.score-S.score});return[A.map(({handler:R,params:S})=>[R,S])]}};var EG=W(()=>{d0();U0();jA=Object.create(null)});var F7=class{name="TrieRouter";#D;constructor(){this.#D=new $G}add(D,u,r){let A=$3(u);if(A){for(let f=0,w=A.length;f<w;f++)this.#D.insert(D,A[f],r);return}this.#D.insert(D,u,r)}match(D,u){return this.#D.search(D,u)}};var gG=W(()=>{U0();EG()});var _G=W(()=>{gG()});var w7;var RG=W(()=>{pW();fG();wG();_G();w7=class extends mW{constructor(D={}){super(D);this.router=D.router??new f7({routers:[new J3,new F7]})}}});var SG=W(()=>{RG()});function BG(D,u){let r={};return Object.keys(D.paths).forEach((A)=>{r[pu(u.replaceAll(/:([^\/]+)/g,"{$1}"),A)]=D.paths[A]}),{...D,paths:r}}function JG(D){return/^application\/([a-z-\.]+\+)?json/.test(D)}function WG(D){return D.startsWith("multipart/form-data")||D.startsWith("application/x-www-form-urlencoded")}var GG;var CG=W(()=>{HW();LW();SG();U0();YD();GG=class D extends w7{openAPIRegistry;defaultHook;constructor(u){super(u);this.openAPIRegistry=new s$,this.defaultHook=u?.defaultHook}openapi=({middleware:u,hide:r,...A},f,w=this.defaultHook)=>{if(!r)this.openAPIRegistry.registerPath(A);let F=[];if(A.request?.query){let g=o0("query",A.request.query,w);F.push(g)}if(A.request?.params){let g=o0("param",A.request.params,w);F.push(g)}if(A.request?.headers){let g=o0("header",A.request.headers,w);F.push(g)}if(A.request?.cookies){let g=o0("cookie",A.request.cookies,w);F.push(g)}let E=A.request?.body?.content;if(E)for(let g of Object.keys(E)){if(!E[g])continue;let R=E[g].schema;if(!(R instanceof x))continue;if(JG(g)){let S=o0("json",R,w);if(A.request?.body?.required)F.push(S);else{let B=async(J,H)=>{if(J.req.header("content-type")){if(JG(J.req.header("content-type")))return await S(J,H)}J.req.addValidatedData("json",{}),await H()};F.push(B)}}if(WG(g)){let S=o0("form",R,w);if(A.request?.body?.required)F.push(S);else{let B=async(J,H)=>{if(J.req.header("content-type")){if(WG(J.req.header("content-type")))return await S(J,H)}J.req.addValidatedData("form",{}),await H()};F.push(B)}}}let $=u?Array.isArray(u)?u:[u]:[];return this.on([A.method],A.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...$,...F,f),this};getOpenAPIDocument=(u)=>{let A=new o$(this.openAPIRegistry.definitions).generateDocument(u);return this._basePath?BG(A,this._basePath):A};getOpenAPI31Document=(u)=>{let A=new d$(this.openAPIRegistry.definitions).generateDocument(u);return this._basePath?BG(A,this._basePath):A};doc=(u,r)=>{return this.get(u,(A)=>{let f=typeof r==="function"?r(A):r;try{let w=this.getOpenAPIDocument(f);return A.json(w)}catch(w){return A.json(w,500)}})};doc31=(u,r)=>{return this.get(u,(A)=>{let f=typeof r==="function"?r(A):r;try{let w=this.getOpenAPI31Document(f);return A.json(w)}catch(w){return A.json(w,500)}})};route(u,r){let A=u.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(u,r),!(r instanceof D))return this;return r.openAPIRegistry.definitions.forEach((f)=>{switch(f.type){case"component":return this.openAPIRegistry.registerComponent(f.componentType,f.name,f.component);case"route":{this.openAPIRegistry.registerPath({...f.route,path:pu(A,r._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),f.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...f.webhook,path:pu(A,r._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),f.webhook.path)});return}case"schema":return this.openAPIRegistry.register(f.schema._def.openapi._internal.refId,f.schema);case"parameter":return this.openAPIRegistry.registerParameter(f.schema._def.openapi._internal.refId,f.schema);default:throw Error(`Unknown registry type: ${f}`)}}),this}basePath(u){return new D({...super.basePath(u),defaultHook:this.defaultHook})}};aJ(_)});function $7(D){if(!gL.some((r)=>D.includes(r)))return D;return console.warn("DEPRECATION WARNING: It looks like you're using legacy CSS variables in your custom CSS string. Please migrate them to use the updated prefixes. See https://github.com/scalar/scalar/blob/main/documentation/themes.md#theme-prefix-changes"),HG.reduce((r,[A,f])=>r.replaceAll(A,f),D)}var HG,gL;var E7=W(()=>{HG=[["--theme-","--scalar-"],["--sidebar-","--scalar-sidebar-"]],gL=HG.map(([D])=>D)});var _L,RL,SL,_7,BL,UG,nG="https://api.scalar.com/request-proxy",g7="https://proxy.scalar.com",XG,JL,YG=(D)=>{let u={...D};if(u.customCss)u.customCss=$7(u.customCss);if(u.proxy){if(console.warn("[DEPRECATED] You\u2019re using the deprecated 'proxy' attribute, rename it to 'proxyUrl' or update the package."),!u.proxyUrl)u.proxyUrl=u.proxy;delete u.proxy}if(u.proxyUrl===nG)console.warn(`[DEPRECATED] Warning: configuration.proxyUrl points to our old proxy (${nG}).`),console.warn(`[DEPRECATED] We are overwriting the value and use the new proxy URL (${g7}) instead.`),console.warn(`[DEPRECATED] Action Required: You should manually update your configuration to use the new URL (${g7}). Read more: https://github.com/scalar/scalar`),u.proxyUrl=g7;return u},R7,WL;var MG=W(()=>{YD();E7();_L=_.enum(["alternate","default","moon","purple","solarized","bluePlanet","deepSpace","saturn","kepler","elysiajs","fastify","mars","none"]),RL=_.enum(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]),SL=_.enum(["adonisjs","docusaurus","dotnet","elysiajs","express","fastapi","fastify","go","hono","html","laravel","litestar","nestjs","nextjs","nitro","nuxt","platformatic","react","rust","vue"]).nullable(),_7=_.object({url:_.string().optional(),content:_.union([_.string(),_.record(_.any()),_.function().returns(_.record(_.any())),_.null()]).optional(),title:_.string().optional(),slug:_.string().optional()}),BL=_.object({basePath:_.string()}),UG=_.object({authentication:_.any().optional(),baseServerURL:_.string().optional(),hideClientButton:_.boolean().optional().default(!1).catch(!1),proxyUrl:_.string().optional(),searchHotKey:RL.optional(),servers:_.array(_.any()).optional(),showSidebar:_.boolean().optional().default(!0).catch(!0),spec:_7.optional(),theme:_L.optional().default("default").catch("default"),_integration:SL.optional()}),XG=UG.merge(_.object({layout:_.enum(["modern","classic"]).optional().default("modern").catch("modern"),proxy:_.string().optional(),isEditable:_.boolean().optional().default(!1).catch(!1),hideModels:_.boolean().optional().default(!1).catch(!1),hideDownloadButton:_.boolean().optional().default(!1).catch(!1),hideTestRequestButton:_.boolean().optional().default(!1).catch(!1),hideSearch:_.boolean().optional().default(!1).catch(!1),darkMode:_.boolean().optional(),forceDarkModeState:_.enum(["dark","light"]).optional(),hideDarkModeToggle:_.boolean().optional().default(!1).catch(!1),metaData:_.any().optional(),favicon:_.string().optional(),hiddenClients:_.union([_.record(_.union([_.boolean(),_.array(_.string())])),_.array(_.string()),_.literal(!0)]).optional(),defaultHttpClient:_.object({targetKey:_.custom(),clientKey:_.string()}).optional(),customCss:_.string().optional(),onSpecUpdate:_.function().args(_.string()).returns(_.void()).optional(),onServerChange:_.function().args(_.string()).returns(_.void()).optional(),pathRouting:BL.optional(),generateHeadingSlug:_.function().args(_.object({slug:_.string().default("headingSlug")})).returns(_.string()).optional(),generateModelSlug:_.function().args(_.object({name:_.string().default("modelName")})).returns(_.string()).optional(),generateTagSlug:_.function().args(_.object({name:_.string().default("tagName")})).returns(_.string()).optional(),generateOperationSlug:_.function().args(_.object({path:_.string(),operationId:_.string().optional(),method:_.string(),summary:_.string().optional()})).returns(_.string()).optional(),generateWebhookSlug:_.function().args(_.object({name:_.string(),method:_.string().optional()})).returns(_.string()).optional(),onLoaded:_.function().returns(_.void()).optional(),redirect:_.function().args(_.string()).returns(_.string().nullable().optional()).optional(),withDefaultFonts:_.boolean().optional().default(!0).catch(!0),defaultOpenAllTags:_.boolean().optional(),tagsSorter:_.union([_.literal("alpha"),_.function().args(_.any(),_.any()).returns(_.number())]).optional(),operationsSorter:_.union([_.literal("alpha"),_.literal("method"),_.function().args(_.any(),_.any()).returns(_.number())]).optional()})),JL=XG.merge(_.object({spec:_.object({sources:_.array(_7)})})),R7=XG.transform(YG),WL=JL.transform(YG)});var S7;var OG=W(()=>{YD();S7=_.object({cdn:_.string().optional().default("https://cdn.jsdelivr.net/npm/@scalar/api-reference"),pageTitle:_.string().optional().default("Scalar API Reference")})});var PG=W(()=>{MG();OG();E7()});function GL(D,u){return`
1583
+ `:g}};vr=DL()});function h1(D,u){var r={};for(var A in D)if(Object.prototype.hasOwnProperty.call(D,A)&&u.indexOf(A)<0)r[A]=D[A];if(D!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var f=0,A=Object.getOwnPropertySymbols(D);f<A.length;f++)if(u.indexOf(A[f])<0&&Object.prototype.propertyIsEnumerable.call(D,A[f]))r[A[f]]=D[A[f]]}return r}function m(D,u){var r;return((r=D===null||D===void 0?void 0:D._def)===null||r===void 0?void 0:r.typeName)===u}function RL(D){return"_def"in D}function V1(D,u){let r=D.ZodType.prototype[u];D.ZodType.prototype[u]=function(...A){let f=r.apply(this,A);return f._def.openapi=this._def.openapi,f}}function HW(D){if(typeof D.ZodType.prototype.openapi<"u")return;D.ZodType.prototype.openapi=function(f,w){var F,E,$,g,_,R;let n=typeof f==="string"?w:f,B=n!==null&&n!==void 0?n:{},{param:C}=B,J=h1(B,["param"]),X=Object.assign(Object.assign({},(F=this._def.openapi)===null||F===void 0?void 0:F._internal),typeof f==="string"?{refId:f}:void 0),M=Object.assign(Object.assign(Object.assign({},(E=this._def.openapi)===null||E===void 0?void 0:E.metadata),J),((g=($=this._def.openapi)===null||$===void 0?void 0:$.metadata)===null||g===void 0?void 0:g.param)||C?{param:Object.assign(Object.assign({},(R=(_=this._def.openapi)===null||_===void 0?void 0:_.metadata)===null||R===void 0?void 0:R.param),C)}:void 0),P=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(X).length>0?{_internal:X}:void 0),Object.keys(M).length>0?{metadata:M}:void 0)}));if(m(this,"ZodObject")){let k=this.extend;P.extend=function(...s){var q,Y,v,N,rD,_D,WD;let e=k.apply(this,s);return e._def.openapi={_internal:{extendedFrom:((Y=(q=this._def.openapi)===null||q===void 0?void 0:q._internal)===null||Y===void 0?void 0:Y.refId)?{refId:(N=(v=this._def.openapi)===null||v===void 0?void 0:v._internal)===null||N===void 0?void 0:N.refId,schema:this}:(_D=(rD=this._def.openapi)===null||rD===void 0?void 0:rD._internal)===null||_D===void 0?void 0:_D.extendedFrom},metadata:(WD=e._def.openapi)===null||WD===void 0?void 0:WD.metadata},e}}return P},V1(D,"optional"),V1(D,"nullable"),V1(D,"default"),V1(D,"transform"),V1(D,"refine");let u=D.ZodObject.prototype.deepPartial;D.ZodObject.prototype.deepPartial=function(){let f=this._def.shape(),w=u.apply(this),F=w._def.shape();return Object.entries(F).forEach(([E,$])=>{var g,_;$._def.openapi=(_=(g=f[E])===null||g===void 0?void 0:g._def)===null||_===void 0?void 0:_.openapi}),w._def.openapi=void 0,w};let r=D.ZodObject.prototype.pick;D.ZodObject.prototype.pick=function(...f){let w=r.apply(this,f);return w._def.openapi=void 0,w};let A=D.ZodObject.prototype.omit;D.ZodObject.prototype.omit=function(...f){let w=A.apply(this,f);return w._def.openapi=void 0,w}}function _3(D,u){if(D===null||D===void 0||u===null||u===void 0)return D===u;if(D===u||D.valueOf()===u.valueOf())return!0;if(Array.isArray(D)){if(!Array.isArray(u))return!1;if(D.length!==u.length)return!1}if(!(D instanceof Object)||!(u instanceof Object))return!1;let r=Object.keys(D);return Object.keys(u).every((A)=>r.indexOf(A)!==-1)&&r.every((A)=>_3(D[A],u[A]))}class XW{constructor(){this.buckets=new Map}put(D){let u=this.hashCodeOf(D),r=this.buckets.get(u);if(!r){this.buckets.set(u,[D]);return}if(!r.some((f)=>_3(f,D)))r.push(D)}contains(D){let u=this.hashCodeOf(D),r=this.buckets.get(u);if(!r)return!1;return r.some((A)=>_3(A,D))}values(){return[...this.buckets.values()].flat()}stats(){let D=0,u=0,r=0;for(let f of this.buckets.values())if(D+=1,u+=f.length,f.length>1)r+=1;let A=D/u;return{totalBuckets:D,collisions:r,totalValues:u,hashEffectiveness:A}}hashCodeOf(D){let u=0;if(Array.isArray(D)){for(let r=0;r<D.length;r++)u^=this.hashCodeOf(D[r])*r;return u}if(typeof D==="string"){for(let r=0;r<D.length;r++)u^=D.charCodeAt(r)*r;return u}if(typeof D==="number")return D;if(typeof D==="object")for(let[r,A]of Object.entries(D))u^=this.hashCodeOf(r)+this.hashCodeOf(A!==null&&A!==void 0?A:"");return u}}function N1(D){return D===void 0}function Q1(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{r[A]=u(f)}),r}function nL(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{if(!u.some((w)=>w===A))r[A]=f}),r}function o2(D,u){let r={};return Object.entries(D).forEach(([A,f])=>{if(!u(f,A))r[A]=f}),r}function CW(D){return D.filter((u)=>!N1(u))}function BL(D){let u=new XW;return D.forEach((r)=>u.put(r)),[...u.values()]}function iW(D){return typeof D==="string"}class f7{constructor(D){this.parents=D,this._definitions=[]}get definitions(){var D,u;return[...(u=(D=this.parents)===null||D===void 0?void 0:D.flatMap((A)=>A.definitions))!==null&&u!==void 0?u:[],...this._definitions]}register(D,u){let r=this.schemaWithRefId(D,u);return this._definitions.push({type:"schema",schema:r}),r}registerParameter(D,u){var r,A,f;let w=this.schemaWithRefId(D,u),F=(r=w._def.openapi)===null||r===void 0?void 0:r.metadata,E=w.openapi(Object.assign(Object.assign({},F),{param:Object.assign(Object.assign({},F===null||F===void 0?void 0:F.param),{name:(f=(A=F===null||F===void 0?void 0:F.param)===null||A===void 0?void 0:A.name)!==null&&f!==void 0?f:D})}));return this._definitions.push({type:"parameter",schema:E}),E}registerPath(D){this._definitions.push({type:"route",route:D})}registerWebhook(D){this._definitions.push({type:"webhook",webhook:D})}registerComponent(D,u,r){return this._definitions.push({type:"component",componentType:D,name:u,component:r}),{name:u,ref:{$ref:`#/components/${D}/${u}`}}}schemaWithRefId(D,u){return u.openapi(D)}}class q1{constructor(D){this.message=D}}function K1(D,u){try{return D()}catch(r){if(r instanceof L1)throw new L1(Object.assign(Object.assign({},r.data),u));throw r}}class BD{static getMetadata(D){var u;let r=this.unwrapChained(D),A=D._def.openapi?D._def.openapi:r._def.openapi,f=(u=D.description)!==null&&u!==void 0?u:r.description;return{_internal:A===null||A===void 0?void 0:A._internal,metadata:Object.assign({description:f},A===null||A===void 0?void 0:A.metadata)}}static getInternalMetadata(D){let u=this.unwrapChained(D),r=D._def.openapi?D._def.openapi:u._def.openapi;return r===null||r===void 0?void 0:r._internal}static getParamMetadata(D){var u,r;let A=this.unwrapChained(D),f=D._def.openapi?D._def.openapi:A._def.openapi,w=(u=D.description)!==null&&u!==void 0?u:A.description;return{_internal:f===null||f===void 0?void 0:f._internal,metadata:Object.assign(Object.assign({},f===null||f===void 0?void 0:f.metadata),{param:Object.assign({description:w},(r=f===null||f===void 0?void 0:f.metadata)===null||r===void 0?void 0:r.param)})}}static buildSchemaMetadata(D){return o2(nL(D,["param"]),N1)}static buildParameterMetadata(D){return o2(D,N1)}static applySchemaMetadata(D,u){return o2(Object.assign(Object.assign({},D),this.buildSchemaMetadata(u)),N1)}static getRefId(D){var u;return(u=this.getInternalMetadata(D))===null||u===void 0?void 0:u.refId}static unwrapChained(D){return this.unwrapUntil(D)}static getDefaultValue(D){let u=this.unwrapUntil(D,"ZodDefault");return u===null||u===void 0?void 0:u._def.defaultValue()}static unwrapUntil(D,u){if(u&&m(D,u))return D;if(m(D,"ZodOptional")||m(D,"ZodNullable")||m(D,"ZodBranded"))return this.unwrapUntil(D.unwrap(),u);if(m(D,"ZodDefault")||m(D,"ZodReadonly"))return this.unwrapUntil(D._def.innerType,u);if(m(D,"ZodEffects"))return this.unwrapUntil(D._def.schema,u);if(m(D,"ZodPipeline"))return this.unwrapUntil(D._def.in,u);return u?void 0:D}static isOptionalSchema(D){return D.isOptional()}}class YW{transform(D,u,r){var A,f;let w=D._def.type;return Object.assign(Object.assign({},u("array")),{items:r(w),minItems:(A=D._def.minLength)===null||A===void 0?void 0:A.value,maxItems:(f=D._def.maxLength)===null||f===void 0?void 0:f.value})}}class MW{transform(D){return Object.assign(Object.assign({},D("string")),{pattern:"^d+$"})}}class OW{transform(D,u,r,A,f){let w=[...D.options.values()],F=w.map(A);if(u)return{oneOf:r(F,u)};return{oneOf:F,discriminator:this.mapDiscriminator(w,D.discriminator,f)}}mapDiscriminator(D,u,r){if(D.some((f)=>BD.getRefId(f)===void 0))return;let A={};return D.forEach((f)=>{var w;let F=BD.getRefId(f),E=(w=f.shape)===null||w===void 0?void 0:w[u];if(m(E,"ZodEnum")||m(E,"ZodNativeEnum")){Object.values(E.enum).filter(iW).forEach((_)=>{A[_]=r(F)});return}let $=E===null||E===void 0?void 0:E._def.value;if(typeof $!=="string")throw Error(`Discriminator ${u} could not be found in one of the values of a discriminated union`);A[$]=r(F)}),{propertyName:u,mapping:A}}}class PW{transform(D,u){return Object.assign(Object.assign({},u("string")),{enum:D._def.values})}}class kW{transform(D,u,r,A){let w={allOf:this.flattenIntersectionTypes(D).map(A)};if(u)return{anyOf:r([w],u)};return w}flattenIntersectionTypes(D){if(!m(D,"ZodIntersection"))return[D];let u=this.flattenIntersectionTypes(D._def.left),r=this.flattenIntersectionTypes(D._def.right);return[...u,...r]}}class IW{transform(D,u){return Object.assign(Object.assign({},u(typeof D._def.value)),{enum:[D._def.value]})}}function WL(D){let r=Object.keys(D).filter((w)=>typeof D[D[w]]!=="number").map((w)=>D[w]),A=r.filter((w)=>typeof w==="number").length,f=A===0?"string":A===r.length?"numeric":"mixed";return{values:r,type:f}}class VW{transform(D,u){let{type:r,values:A}=WL(D._def.values);if(r==="mixed")throw new q1("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},u(r==="numeric"?"integer":"string")),{enum:A})}}class KW{transform(D,u,r){return Object.assign(Object.assign({},u(D.isInt?"integer":"number")),r(D._def.checks))}}class hW{transform(D,u,r,A){var f;let w=(f=BD.getInternalMetadata(D))===null||f===void 0?void 0:f.extendedFrom,F=this.requiredKeysOf(D),E=Q1(D._def.shape(),A);if(!w)return Object.assign(Object.assign(Object.assign(Object.assign({},r("object")),{properties:E,default:u}),F.length>0?{required:F}:{}),this.generateAdditionalProperties(D,A));let $=w.schema;A($);let g=this.requiredKeysOf($),_=Q1($===null||$===void 0?void 0:$._def.shape(),A),R=Object.fromEntries(Object.entries(E).filter(([C,J])=>{return!A7(_[C],J)})),n=F.filter((C)=>!g.includes(C)),B=Object.assign(Object.assign(Object.assign(Object.assign({},r("object")),{default:u,properties:R}),n.length>0?{required:n}:{}),this.generateAdditionalProperties(D,A));return{allOf:[{$ref:`#/components/schemas/${w.refId}`},B]}}generateAdditionalProperties(D,u){let r=D._def.unknownKeys,A=D._def.catchall;if(m(A,"ZodNever")){if(r==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:u(A)}}requiredKeysOf(D){return Object.entries(D._def.shape()).filter(([u,r])=>!BD.isOptionalSchema(r)).map(([u,r])=>u)}}class NW{transform(D,u,r){let A=D._def.valueType,f=D._def.keyType,w=r(A);if(m(f,"ZodEnum")||m(f,"ZodNativeEnum")){let E=Object.values(f.enum).filter(iW).reduce(($,g)=>Object.assign(Object.assign({},$),{[g]:w}),{});return Object.assign(Object.assign({},u("object")),{properties:E})}return Object.assign(Object.assign({},u("object")),{additionalProperties:w})}}class QW{transform(D,u){var r,A,f;let w=this.getZodStringCheck(D,"regex"),F=(r=this.getZodStringCheck(D,"length"))===null||r===void 0?void 0:r.value,E=Number.isFinite(D.minLength)?(A=D.minLength)!==null&&A!==void 0?A:void 0:void 0,$=Number.isFinite(D.maxLength)?(f=D.maxLength)!==null&&f!==void 0?f:void 0:void 0;return Object.assign(Object.assign({},u("string")),{minLength:F!==null&&F!==void 0?F:E,maxLength:F!==null&&F!==void 0?F:$,format:this.mapStringFormat(D),pattern:w===null||w===void 0?void 0:w.regex.source})}mapStringFormat(D){if(D.isUUID)return"uuid";if(D.isEmail)return"email";if(D.isURL)return"uri";if(D.isDate)return"date";if(D.isDatetime)return"date-time";if(D.isCUID)return"cuid";if(D.isCUID2)return"cuid2";if(D.isULID)return"ulid";if(D.isIP)return"ip";if(D.isEmoji)return"emoji";return}getZodStringCheck(D,u){return D._def.checks.find((r)=>{return r.kind===u})}}class LW{constructor(D){this.versionSpecifics=D}transform(D,u,r){let{items:A}=D._def,f=A.map(r);return Object.assign(Object.assign({},u("array")),this.versionSpecifics.mapTupleItems(f))}}class qW{transform(D,u,r){let f=this.flattenUnionTypes(D).map((w)=>{let F=this.unwrapNullable(w);return r(F)});return{anyOf:u(f)}}flattenUnionTypes(D){if(!m(D,"ZodUnion"))return[D];return D._def.options.flatMap((r)=>this.flattenUnionTypes(r))}unwrapNullable(D){if(m(D,"ZodNullable"))return this.unwrapNullable(D.unwrap());return D}}class bW{constructor(D){this.versionSpecifics=D,this.objectTransformer=new hW,this.stringTransformer=new QW,this.numberTransformer=new KW,this.bigIntTransformer=new MW,this.literalTransformer=new IW,this.enumTransformer=new PW,this.nativeEnumTransformer=new VW,this.arrayTransformer=new YW,this.unionTransformer=new qW,this.discriminatedUnionTransformer=new OW,this.intersectionTransformer=new kW,this.recordTransformer=new NW,this.tupleTransformer=new LW(D)}transform(D,u,r,A,f){if(m(D,"ZodNull"))return this.versionSpecifics.nullType;if(m(D,"ZodUnknown")||m(D,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,u);if(m(D,"ZodObject"))return this.objectTransformer.transform(D,f,(F)=>this.versionSpecifics.mapNullableType(F,u),r);let w=this.transformSchemaWithoutDefault(D,u,r,A);return Object.assign(Object.assign({},w),{default:f})}transformSchemaWithoutDefault(D,u,r,A){if(m(D,"ZodUnknown")||m(D,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,u);if(m(D,"ZodString"))return this.stringTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(m(D,"ZodNumber"))return this.numberTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),(w)=>this.versionSpecifics.getNumberChecks(w));if(m(D,"ZodBigInt"))return this.bigIntTransformer.transform((w)=>this.versionSpecifics.mapNullableType(w,u));if(m(D,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",u);if(m(D,"ZodLiteral"))return this.literalTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(m(D,"ZodEnum"))return this.enumTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(m(D,"ZodNativeEnum"))return this.nativeEnumTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u));if(m(D,"ZodArray"))return this.arrayTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(m(D,"ZodTuple"))return this.tupleTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(m(D,"ZodUnion"))return this.unionTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r);if(m(D,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform(D,u,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r,A);if(m(D,"ZodIntersection"))return this.intersectionTransformer.transform(D,u,(w)=>this.versionSpecifics.mapNullableOfArray(w,u),r);if(m(D,"ZodRecord"))return this.recordTransformer.transform(D,(w)=>this.versionSpecifics.mapNullableType(w,u),r);if(m(D,"ZodDate"))return this.versionSpecifics.mapNullableType("string",u);let f=BD.getRefId(D);throw new UW({currentSchema:D._def,schemaName:f})}}class F7{constructor(D,u){this.definitions=D,this.versionSpecifics=u,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new bW(u),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach((D)=>this.generateSingle(D)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach((D)=>this.generateSingle(D)),{components:this.buildComponents()}}buildComponents(){var D,u;let r={};return this.rawComponents.forEach(({componentType:A,name:f,component:w})=>{var F;(F=r[A])!==null&&F!==void 0||(r[A]={}),r[A][f]=w}),Object.assign(Object.assign({},r),{schemas:Object.assign(Object.assign({},(D=r.schemas)!==null&&D!==void 0?D:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(u=r.parameters)!==null&&u!==void 0?u:{}),this.paramRefs)})}sortDefinitions(){let D=["schema","parameter","component","route"];this.definitions.sort((u,r)=>{if(!("type"in u)){if(!("type"in r))return 0;return-1}if(!("type"in r))return 1;let A=D.findIndex((w)=>w===u.type),f=D.findIndex((w)=>w===r.type);return A-f})}generateSingle(D){if(!("type"in D)){this.generateSchemaWithRef(D);return}switch(D.type){case"parameter":this.generateParameterDefinition(D.schema);return;case"schema":this.generateSchemaWithRef(D.schema);return;case"route":this.generateSingleRoute(D.route);return;case"component":this.rawComponents.push(D);return}}generateParameterDefinition(D){let u=BD.getRefId(D),r=this.generateParameter(D);if(u)this.paramRefs[u]=r;return r}getParameterRef(D,u){var r,A,f,w,F;let E=(r=D===null||D===void 0?void 0:D.metadata)===null||r===void 0?void 0:r.param,$=((A=D===null||D===void 0?void 0:D._internal)===null||A===void 0?void 0:A.refId)?this.paramRefs[(f=D._internal)===null||f===void 0?void 0:f.refId]:void 0;if(!((w=D===null||D===void 0?void 0:D._internal)===null||w===void 0?void 0:w.refId)||!$)return;if(E&&$.in!==E.in||(u===null||u===void 0?void 0:u.in)&&$.in!==u.in)throw new Z2(`Conflicting location for parameter ${$.name}`,{key:"in",values:CW([$.in,u===null||u===void 0?void 0:u.in,E===null||E===void 0?void 0:E.in])});if(E&&$.name!==E.name||(u===null||u===void 0?void 0:u.name)&&$.name!==(u===null||u===void 0?void 0:u.name))throw new Z2("Conflicting names for parameter",{key:"name",values:CW([$.name,u===null||u===void 0?void 0:u.name,E===null||E===void 0?void 0:E.name])});return{$ref:`#/components/parameters/${(F=D._internal)===null||F===void 0?void 0:F.refId}`}}generateInlineParameters(D,u){var r;let A=BD.getMetadata(D),f=(r=A===null||A===void 0?void 0:A.metadata)===null||r===void 0?void 0:r.param,w=this.getParameterRef(A,{in:u});if(w)return[w];if(m(D,"ZodObject")){let F=D._def.shape();return Object.entries(F).map(([$,g])=>{var _,R;let n=BD.getMetadata(g),B=this.getParameterRef(n,{in:u,name:$});if(B)return B;let C=(_=n===null||n===void 0?void 0:n.metadata)===null||_===void 0?void 0:_.param;if((C===null||C===void 0?void 0:C.name)&&C.name!==$)throw new Z2("Conflicting names for parameter",{key:"name",values:[$,C.name]});if((C===null||C===void 0?void 0:C.in)&&C.in!==u)throw new Z2(`Conflicting location for parameter ${(R=C.name)!==null&&R!==void 0?R:$}`,{key:"in",values:[u,C.in]});return this.generateParameter(g.openapi({param:{name:$,in:u}}))})}if((f===null||f===void 0?void 0:f.in)&&f.in!==u)throw new Z2(`Conflicting location for parameter ${f.name}`,{key:"in",values:[u,f.in]});return[this.generateParameter(D.openapi({param:{in:u}}))]}generateSimpleParameter(D){var u;let r=BD.getParamMetadata(D),A=(u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.param,f=!BD.isOptionalSchema(D)&&!D.isNullable(),w=this.generateSchemaWithRef(D);return Object.assign({schema:w,required:f},A?BD.buildParameterMetadata(A):{})}generateParameter(D){var u;let r=BD.getMetadata(D),A=(u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.param,f=A===null||A===void 0?void 0:A.name,w=A===null||A===void 0?void 0:A.in;if(!f)throw new L1({missingField:"name"});if(!w)throw new L1({missingField:"in",paramName:f});let F=this.generateSimpleParameter(D);return Object.assign(Object.assign({},F),{in:w,name:f})}generateSchemaWithMetadata(D){var u;let r=BD.unwrapChained(D),A=BD.getMetadata(D),f=BD.getDefaultValue(D),w=((u=A===null||A===void 0?void 0:A.metadata)===null||u===void 0?void 0:u.type)?{type:A===null||A===void 0?void 0:A.metadata.type}:this.toOpenAPISchema(r,D.isNullable(),f);return(A===null||A===void 0?void 0:A.metadata)?BD.applySchemaMetadata(w,A.metadata):o2(w,N1)}constructReferencedOpenAPISchema(D){var u;let r=BD.getMetadata(D),A=BD.unwrapChained(D),f=BD.getDefaultValue(D),w=D.isNullable();if((u=r===null||r===void 0?void 0:r.metadata)===null||u===void 0?void 0:u.type)return this.versionSpecifics.mapNullableType(r.metadata.type,w);return this.toOpenAPISchema(A,w,f)}generateSimpleSchema(D){var u;let r=BD.getMetadata(D),A=BD.getRefId(D);if(!A||!this.schemaRefs[A])return this.generateSchemaWithMetadata(D);let f=this.schemaRefs[A],w={$ref:this.generateSchemaRef(A)},F=o2(BD.buildSchemaMetadata((u=r===null||r===void 0?void 0:r.metadata)!==null&&u!==void 0?u:{}),(g,_)=>g===void 0||A7(g,f[_]));if(F.type)return{allOf:[w,F]};let E=o2(this.constructReferencedOpenAPISchema(D),(g,_)=>g===void 0||A7(g,f[_])),$=BD.applySchemaMetadata(E,F);if(Object.keys($).length>0)return{allOf:[w,$]};return w}generateSchemaWithRef(D){let u=BD.getRefId(D),r=this.generateSimpleSchema(D);if(u&&this.schemaRefs[u]===void 0)return this.schemaRefs[u]=r,{$ref:this.generateSchemaRef(u)};return r}generateSchemaRef(D){return`#/components/schemas/${D}`}getRequestBody(D){if(!D)return;let{content:u}=D,r=h1(D,["content"]),A=this.getBodyContent(u);return Object.assign(Object.assign({},r),{content:A})}getParameters(D){if(!D)return[];let{headers:u}=D,r=this.cleanParameter(D.query),A=this.cleanParameter(D.params),f=this.cleanParameter(D.cookies),w=K1(()=>r?this.generateInlineParameters(r,"query"):[],{location:"query"}),F=K1(()=>A?this.generateInlineParameters(A,"path"):[],{location:"path"}),E=K1(()=>f?this.generateInlineParameters(f,"cookie"):[],{location:"cookie"}),$=K1(()=>{if(Array.isArray(u))return u.flatMap((_)=>this.generateInlineParameters(_,"header"));let g=this.cleanParameter(u);return g?this.generateInlineParameters(g,"header"):[]},{location:"header"});return[...F,...w,...$,...E]}cleanParameter(D){if(!D)return;return m(D,"ZodEffects")?this.cleanParameter(D._def.schema):D}generatePath(D){let{method:u,path:r,request:A,responses:f}=D,w=h1(D,["method","path","request","responses"]),F=Q1(f,(_)=>{return this.getResponse(_)}),E=K1(()=>this.getParameters(A),{route:`${u} ${r}`}),$=this.getRequestBody(A===null||A===void 0?void 0:A.body);return{[u]:Object.assign(Object.assign(Object.assign(Object.assign({},w),E.length>0?{parameters:[...w.parameters||[],...E]}:{}),$?{requestBody:$}:{}),{responses:F})}}generateSingleRoute(D){let u=this.generatePath(D);return this.pathRefs[D.path]=Object.assign(Object.assign({},this.pathRefs[D.path]),u),u}getResponse(D){if(this.isReferenceObject(D))return D;let{content:u,headers:r}=D,A=h1(D,["content","headers"]),f=u?{content:this.getBodyContent(u)}:{};if(!r)return Object.assign(Object.assign({},A),f);let w=m(r,"ZodObject")?this.getResponseHeaders(r):r;return Object.assign(Object.assign(Object.assign({},A),{headers:w}),f)}isReferenceObject(D){return"$ref"in D}getResponseHeaders(D){let u=D._def.shape();return Q1(u,(A)=>this.generateSimpleParameter(A))}getBodyContent(D){return Q1(D,(u)=>{if(!u||!RL(u.schema))return u;let{schema:r}=u,A=h1(u,["schema"]),f=this.generateSchemaWithRef(r);return Object.assign({schema:f},A)})}toOpenAPISchema(D,u,r){return this.openApiTransformer.transform(D,u,(A)=>this.generateSchemaWithRef(A),(A)=>this.generateSchemaRef(A),r)}}class sW{get nullType(){return{nullable:!0}}mapNullableOfArray(D,u){if(u)return[...D,this.nullType];return D}mapNullableType(D,u){return Object.assign(Object.assign({},D?{type:D}:void 0),u?this.nullType:void 0)}mapTupleItems(D){let u=BL(D);return{items:u.length===1?u[0]:{anyOf:u},minItems:D.length,maxItems:D.length}}getNumberChecks(D){return Object.assign({},...D.map((u)=>{switch(u.kind){case"min":return u.inclusive?{minimum:Number(u.value)}:{minimum:Number(u.value),exclusiveMinimum:!0};case"max":return u.inclusive?{maximum:Number(u.value)}:{maximum:Number(u.value),exclusiveMaximum:!0};default:return{}}}))}}class w7{constructor(D){let u=new sW;this.generator=new F7(D,u)}generateDocument(D){let u=this.generator.generateDocumentData();return Object.assign(Object.assign({},D),u)}generateComponents(){return this.generator.generateComponents()}}class zW{get nullType(){return{type:"null"}}mapNullableOfArray(D,u){if(u)return[...D,this.nullType];return D}mapNullableType(D,u){if(!D)return{};if(u)return{type:Array.isArray(D)?[...D,"null"]:[D,"null"]};return{type:D}}mapTupleItems(D){return{prefixItems:D}}getNumberChecks(D){return Object.assign({},...D.map((u)=>{switch(u.kind){case"min":return u.inclusive?{minimum:Number(u.value)}:{exclusiveMinimum:Number(u.value)};case"max":return u.inclusive?{maximum:Number(u.value)}:{exclusiveMaximum:Number(u.value)};default:return{}}}))}}function JL(D){return"type"in D&&D.type==="webhook"}class $7{constructor(D){this.definitions=D,this.webhookRefs={};let u=new zW;this.generator=new F7(this.definitions,u)}generateDocument(D){let u=this.generator.generateDocumentData();return this.definitions.filter(JL).forEach((r)=>this.generateSingleWebhook(r.webhook)),Object.assign(Object.assign(Object.assign({},D),u),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook(D){let u=this.generator.generatePath(D);return this.webhookRefs[D.path]=Object.assign(Object.assign({},this.webhookRefs[D.path]),u),u}}var A7,Z2,L1,UW;var jW=W(()=>{A7=_3;Z2=class Z2 extends q1{constructor(D,u){super(D);this.data=u}};L1=class L1 extends q1{constructor(D){super(`Missing parameter data, please specify \`${D.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=D}};UW=class UW extends q1{constructor(D){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=D}}});var g7=(D)=>{let u=D.split("/");if(u[0]==="")u.shift();return u},TW=(D)=>{let{groups:u,path:r}=GL(D),A=g7(r);return CL(A,u)},GL=(D)=>{let u=[];return D=D.replace(/\{[^}]+\}/g,(r,A)=>{let f=`@${A}`;return u.push([f,r]),f}),{groups:u,path:D}},CL=(D,u)=>{for(let r=u.length-1;r>=0;r--){let[A]=u[r];for(let f=D.length-1;f>=0;f--)if(D[f].includes(A)){D[f]=D[f].replace(A,u[r][1]);break}}return D},R3,vW=(D,u)=>{if(D==="*")return"*";let r=D.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let A=`${D}#${u}`;if(!R3[A])if(r[2])R3[A]=u&&u[0]!==":"&&u[0]!=="*"?[A,r[1],new RegExp(`^${r[2]}(?=/${u})`)]:[D,r[1],new RegExp(`^${r[2]}$`)];else R3[A]=[D,r[1],!0];return R3[A]}return null},d2=(D,u)=>{try{return u(D)}catch{return D.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return u(r)}catch{return r}})}},HL=(D)=>d2(D,decodeURI),S7=(D)=>{let u=D.url,r=u.indexOf("/",u.indexOf(":")+4),A=r;for(;A<u.length;A++){let f=u.charCodeAt(A);if(f===37){let w=u.indexOf("?",A),F=u.indexOf("#",A),E=w===-1?F===-1?void 0:F:F===-1?w:Math.min(w,F),$=u.slice(r,E);return HL($.includes("%25")?$.replace(/%25/g,"%2525"):$)}else if(f===63||f===35)break}return u.slice(r,A)},ZW=(D)=>{let u=S7(D);return u.length>1&&u.at(-1)==="/"?u.slice(0,-1):u},eu=(D,u,...r)=>{if(r.length)u=eu(u,...r);return`${D?.[0]==="/"?"":"/"}${D}${u==="/"?"":`${D?.at(-1)==="/"?"":"/"}${u?.[0]==="/"?u.slice(1):u}`}`},n3=(D)=>{if(D.charCodeAt(D.length-1)!==63||!D.includes(":"))return null;let u=D.split("/"),r=[],A="";return u.forEach((f)=>{if(f!==""&&!/\:/.test(f))A+="/"+f;else if(/\:/.test(f))if(/\?/.test(f)){if(r.length===0&&A==="")r.push("/");else r.push(A);let w=f.replace("?","");A+="/"+w,r.push(A)}else A+="/"+f}),r.filter((f,w,F)=>F.indexOf(f)===w)},E7=(D)=>{if(!/[%+]/.test(D))return D;if(D.indexOf("+")!==-1)D=D.replace(/\+/g," ");return D.indexOf("%")!==-1?d2(D,b1):D},oW=(D,u,r)=>{let A;if(!r&&u&&!/[%+]/.test(u)){let F=D.indexOf("?",8);if(F===-1)return;if(!D.startsWith(u,F+1))F=D.indexOf(`&${u}`,F+1);while(F!==-1){let E=D.charCodeAt(F+u.length+1);if(E===61){let $=F+u.length+2,g=D.indexOf("&",$);return E7(D.slice($,g===-1?void 0:g))}else if(E==38||isNaN(E))return"";F=D.indexOf(`&${u}`,F+1)}if(A=/[%+]/.test(D),!A)return}let f={};A??=/[%+]/.test(D);let w=D.indexOf("?",8);while(w!==-1){let F=D.indexOf("&",w+1),E=D.indexOf("=",w);if(E>F&&F!==-1)E=-1;let $=D.slice(w+1,E===-1?F===-1?void 0:F:E);if(A)$=E7($);if(w=F,$==="")continue;let g;if(E===-1)g="";else if(g=D.slice(E+1,F===-1?void 0:F),A)g=E7(g);if(r){if(!(f[$]&&Array.isArray(f[$])))f[$]=[];f[$].push(g)}else f[$]??=g}return u?f[u]:f},dW,lW=(D,u)=>{return oW(D,u,!0)},b1;var X0=W(()=>{R3={},dW=oW,b1=decodeURIComponent});var XL,iL,yW=(D)=>{let u=0,r=D.length;while(u<r){let A=D.charCodeAt(u);if(A!==32&&A!==9)break;u++}while(r>u){let A=D.charCodeAt(r-1);if(A!==32&&A!==9)break;r--}return u===0&&r===D.length?D:D.slice(u,r)},_7=(D,u)=>{if(u&&D.indexOf(u)===-1)return{};let r=D.split(";"),A={};for(let f of r){let w=f.indexOf("=");if(w===-1)continue;let F=yW(f.substring(0,w));if(u&&u!==F||!XL.test(F))continue;let E=yW(f.substring(w+1));if(E.startsWith('"')&&E.endsWith('"'))E=E.slice(1,-1);if(iL.test(E)){if(A[F]=E.indexOf("%")!==-1?d2(E,b1):E,u)break}}return A};var cW=W(()=>{X0();XL=/^[\w!#$%&'*.^`|~+-]+$/,iL=/^[ !#-:<-[\]-~]*$/});var tW=(D,u,r)=>{let A=D.req.raw.headers.get("Cookie");if(typeof u==="string"){if(!A)return;let w=u;if(r==="secure")w="__Secure-"+u;else if(r==="host")w="__Host-"+u;return _7(A,w)[w]}if(!A)return{};return _7(A)};var pW=W(()=>{cW()});var B3;var R7=W(()=>{B3=class extends Error{res;status;constructor(D=500,u){super(u?.message,{cause:u?.cause});this.res=u?.res,this.status=D}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var xW=()=>{};var mW=(D,u)=>{return new Response(D,{headers:{"Content-Type":u}}).formData()};var aW=W(()=>{xW()});var UL,YL,ML,n7=(D,u)=>{return async(r,A)=>{let f={},w=r.req.header("Content-Type");switch(D){case"json":if(!w||!UL.test(w))break;try{f=await r.req.json()}catch{throw new B3(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!w||!(YL.test(w)||ML.test(w)))break;let E;if(r.req.bodyCache.formData)E=await r.req.bodyCache.formData;else try{let g=await r.req.arrayBuffer();E=await mW(g,w),r.req.bodyCache.formData=E}catch(g){let _="Malformed FormData request.";throw _+=g instanceof Error?` ${g.message}`:` ${String(g)}`,new B3(400,{message:_})}let $=Object.create(null);E.forEach((g,_)=>{if(_.endsWith("[]"))($[_]??=[]).push(g);else if(Array.isArray($[_]))$[_].push(g);else if(Object.hasOwn($,_))$[_]=[$[_],g];else $[_]=g}),f=$;break}case"query":f=Object.fromEntries(Object.entries(r.req.queries()).map(([E,$])=>{return $.length===1?[E,$[0]]:[E,$]}));break;case"param":f=r.req.param();break;case"header":f=r.req.header();break;case"cookie":f=tW(r);break}let F=await u(f,r);if(F instanceof Response)return F;return r.req.addValidatedData(D,F),await A()}};var eW=W(()=>{pW();R7();aW();UL=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,YL=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ML=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var DJ=W(()=>{eW()});function OL(D,u,r,A){return n7(D,async(f,w)=>{let F=f;if(D==="header"&&"_def"in u||D==="header"&&"_zod"in u){let $=Object.keys("in"in u?u.in.shape:u.shape),g=Object.fromEntries($.map((_)=>[_.toLowerCase(),_]));F=Object.fromEntries(Object.entries(f).map(([_,R])=>[g[_]||_,R]))}let E=A&&A.validationFunction?await A.validationFunction(u,F):await u.safeParseAsync(F);if(r){let $=await r({data:F,...E,target:D},w);if($){if($ instanceof Response)return $;if("response"in $)return $.response}}if(!E.success)return w.json(E,400);return E.data})}var d0;var uJ=W(()=>{DJ();d0=OL});var B7=(D,u,r)=>{return(A,f)=>{let w=-1;return F(0);async function F(E){if(E<=w)throw Error("next() called multiple times");w=E;let $,g=!1,_;if(D[E])_=D[E][0][0],A.req.routeIndex=E;else _=E===D.length&&f||void 0;if(_)try{$=await _(A,()=>F(E+1))}catch(R){if(R instanceof Error&&u)A.error=R,$=await u(R,A),g=!0;else throw R}else if(A.finalized===!1&&r)$=await r(A);if($&&(A.finalized===!1||g))A.res=$;return A}}};var rJ=()=>{};var AJ;var fJ=W(()=>{AJ=Symbol()});async function PL(D,u){let r=await D.formData();if(r)return kL(r,u);return{}}function kL(D,u){let r=Object.create(null);if(D.forEach((A,f)=>{if(!(u.all||f.endsWith("[]")))r[f]=A;else IL(r,f,A)}),u.dot)Object.entries(r).forEach(([A,f])=>{if(A.includes("."))VL(r,A,f),delete r[A]});return r}var FJ=async(D,u=Object.create(null))=>{let{all:r=!1,dot:A=!1}=u,w=(D instanceof W3?D.raw.headers:D.headers).get("Content-Type");if(w?.startsWith("multipart/form-data")||w?.startsWith("application/x-www-form-urlencoded"))return PL(D,{all:r,dot:A});return{}},IL=(D,u,r)=>{if(D[u]!==void 0)if(Array.isArray(D[u]))D[u].push(r);else D[u]=[D[u],r];else if(!u.endsWith("[]"))D[u]=r;else D[u]=[r]},VL=(D,u,r)=>{if(/(?:^|\.)__proto__\./.test(u))return;let A=D,f=u.split(".");f.forEach((w,F)=>{if(F===f.length-1)A[w]=r;else{if(!A[w]||typeof A[w]!=="object"||Array.isArray(A[w])||A[w]instanceof File)A[w]=Object.create(null);A=A[w]}})};var wJ=W(()=>{W7()});var $J=(D)=>d2(D,b1),W3;var W7=W(()=>{R7();fJ();wJ();X0();W3=class{raw;#D;#r;routeIndex=0;path;bodyCache={};constructor(D,u="/",r=[[]]){this.raw=D,this.path=u,this.#r=r,this.#D={}}param(D){return D?this.#A(D):this.#F()}#A(D){let u=this.#r[0][this.routeIndex][1][D],r=this.#u(u);return r&&/\%/.test(r)?$J(r):r}#F(){let D={},u=Object.keys(this.#r[0][this.routeIndex][1]);for(let r of u){let A=this.#u(this.#r[0][this.routeIndex][1][r]);if(A!==void 0)D[r]=/\%/.test(A)?$J(A):A}return D}#u(D){return this.#r[1]?this.#r[1][D]:D}query(D){return dW(this.url,D)}queries(D){return lW(this.url,D)}header(D){if(D)return this.raw.headers.get(D)??void 0;let u={};return this.raw.headers.forEach((r,A)=>{u[A]=r}),u}async parseBody(D){return FJ(this,D)}#f=(D)=>{let{bodyCache:u,raw:r}=this,A=u[D];if(A)return A;let f=Object.keys(u)[0];if(f)return u[f].then((w)=>{if(f==="json")w=JSON.stringify(w);return new Response(w)[D]()});return u[D]=r[D]()};json(){return this.#f("text").then((D)=>JSON.parse(D))}text(){return this.#f("text")}arrayBuffer(){return this.#f("arrayBuffer")}blob(){return this.#f("blob")}formData(){return this.#f("formData")}addValidatedData(D,u){this.#D[D]=u}valid(D){return this.#D[D]}get url(){return this.raw.url}get method(){return this.raw.method}get[AJ](){return this.#r}get matchedRoutes(){return this.#r[0].map(([[,D]])=>D)}get routePath(){return this.#r[0].map(([[,D]])=>D)[this.routeIndex].path}}});var EJ,KL=(D,u)=>{let r=new String(D);return r.isEscaped=!0,r.callbacks=u,r},J7=async(D,u,r,A,f)=>{if(typeof D==="object"&&!(D instanceof String)){if(!(D instanceof Promise))D=D.toString();if(D instanceof Promise)D=await D}let w=D.callbacks;if(!w?.length)return Promise.resolve(D);if(f)f[0]+=D;else f=[D];let F=Promise.all(w.map((E)=>E({phase:u,buffer:f,context:A}))).then((E)=>Promise.all(E.filter(Boolean).map(($)=>J7($,u,!1,A,f))).then(()=>f[0]));if(r)return KL(await F,w);else return F};var gJ=W(()=>{EJ={Stringify:1,BeforeStream:2,Stream:3}});var hL="text/plain; charset=UTF-8",G7=(D,u)=>{return{"Content-Type":D,...u}},s1=(D,u)=>new Response(D,u),SJ=class{#D;#r;env={};#A;finalized=!1;error;#F;#u;#f;#S;#E;#g;#$;#_;#R;constructor(D,u){if(this.#D=D,u)this.#u=u.executionCtx,this.env=u.env,this.#g=u.notFoundHandler,this.#R=u.path,this.#_=u.matchResult}get req(){return this.#r??=new W3(this.#D,this.#R,this.#_),this.#r}get event(){if(this.#u&&"respondWith"in this.#u)return this.#u;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#u)return this.#u;else throw Error("This context has no ExecutionContext")}get res(){return this.#f||=s1(null,{headers:this.#$??=new Headers})}set res(D){if(this.#f&&D){D=s1(D.body,D);for(let[u,r]of this.#f.headers.entries()){if(u==="content-type")continue;if(u==="set-cookie"){let A=this.#f.headers.getSetCookie();D.headers.delete("set-cookie");for(let f of A)D.headers.append("set-cookie",f)}else D.headers.set(u,r)}}this.#f=D,this.finalized=!0}render=(...D)=>{return this.#E??=(u)=>this.html(u),this.#E(...D)};setLayout=(D)=>this.#S=D;getLayout=()=>this.#S;setRenderer=(D)=>{this.#E=D};header=(D,u,r)=>{if(this.finalized)this.#f=s1(this.#f.body,this.#f);let A=this.#f?this.#f.headers:this.#$??=new Headers;if(u===void 0)A.delete(D);else if(r?.append)A.append(D,u);else A.set(D,u)};status=(D)=>{this.#F=D};set=(D,u)=>{this.#A??=new Map,this.#A.set(D,u)};get=(D)=>{return this.#A?this.#A.get(D):void 0};get var(){if(!this.#A)return{};return Object.fromEntries(this.#A)}#w(D,u,r){let A=this.#f?new Headers(this.#f.headers):this.#$??new Headers;if(typeof u==="object"&&"headers"in u){let w=u.headers instanceof Headers?u.headers:new Headers(u.headers);for(let[F,E]of w)if(F.toLowerCase()==="set-cookie")A.append(F,E);else A.set(F,E)}if(r)for(let[w,F]of Object.entries(r))if(typeof F==="string")A.set(w,F);else{A.delete(w);for(let E of F)A.append(w,E)}let f=typeof u==="number"?u:u?.status??this.#F;return s1(D,{status:f,headers:A})}newResponse=(...D)=>this.#w(...D);body=(D,u,r)=>this.#w(D,u,r);text=(D,u,r)=>{return!this.#$&&!this.#F&&!u&&!r&&!this.finalized?new Response(D):this.#w(D,u,G7(hL,r))};json=(D,u,r)=>{return this.#w(JSON.stringify(D),u,G7("application/json",r))};html=(D,u,r)=>{let A=(f)=>this.#w(f,u,G7("text/html; charset=UTF-8",r));return typeof D==="object"?J7(D,EJ.Stringify,!1,{}).then(A):A(D)};redirect=(D,u)=>{let r=String(D);return this.header("Location",!/[^\x00-\xFF]/.test(r)?r:encodeURI(r)),this.newResponse(null,u??302)};notFound=()=>{return this.#g??=()=>s1(),this.#g(this)}};var _J=W(()=>{W7();gJ()});var gD="ALL",RJ="all",nJ,J3="Can not add a route since the matcher is already built.",G3;var l0=W(()=>{nJ=["get","post","put","delete","options","patch"],G3=class extends Error{}});var BJ="__COMPOSED_HANDLER";var WJ=()=>{};var NL=(D)=>{return D.text("404 Not Found",404)},JJ=(D,u)=>{if("getResponse"in D){let r=D.getResponse();return u.newResponse(r.body,r)}return console.error(D),u.text("Internal Server Error",500)},GJ=class D{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#D="/";routes=[];constructor(u={}){[...nJ,RJ].forEach((w)=>{this[w]=(F,...E)=>{if(typeof F==="string")this.#D=F;else this.#F(w,this.#D,F);return E.forEach(($)=>{this.#F(w,this.#D,$)}),this}}),this.on=(w,F,...E)=>{for(let $ of[F].flat()){this.#D=$;for(let g of[w].flat())E.map((_)=>{this.#F(g.toUpperCase(),this.#D,_)})}return this},this.use=(w,...F)=>{if(typeof w==="string")this.#D=w;else this.#D="*",F.unshift(w);return F.forEach((E)=>{this.#F(gD,this.#D,E)}),this};let{strict:A,...f}=u;Object.assign(this,f),this.getPath=A??!0?u.getPath??S7:ZW}#r(){let u=new D({router:this.router,getPath:this.getPath});return u.errorHandler=this.errorHandler,u.#A=this.#A,u.routes=this.routes,u}#A=NL;errorHandler=JJ;route(u,r){let A=this.basePath(u);return r.routes.map((f)=>{let w;if(r.errorHandler===JJ)w=f.handler;else w=async(F,E)=>(await B7([],r.errorHandler)(F,()=>f.handler(F,E))).res,w[BJ]=f.handler;A.#F(f.method,f.path,w)}),this}basePath(u){let r=this.#r();return r._basePath=eu(this._basePath,u),r}onError=(u)=>{return this.errorHandler=u,this};notFound=(u)=>{return this.#A=u,this};mount(u,r,A){let f,w;if(A)if(typeof A==="function")w=A;else if(w=A.optionHandler,A.replaceRequest===!1)f=($)=>$;else f=A.replaceRequest;let F=w?($)=>{let g=w($);return Array.isArray(g)?g:[g]}:($)=>{let g=void 0;try{g=$.executionCtx}catch{}return[$.env,g]};f||=(()=>{let $=eu(this._basePath,u),g=$==="/"?0:$.length;return(_)=>{let R=new URL(_.url);return R.pathname=R.pathname.slice(g)||"/",new Request(R,_)}})();let E=async($,g)=>{let _=await r(f($.req.raw),...F($));if(_)return _;await g()};return this.#F(gD,eu(u,"*"),E),this}#F(u,r,A){u=u.toUpperCase(),r=eu(this._basePath,r);let f={basePath:this._basePath,path:r,method:u,handler:A};this.router.add(u,r,[A,f]),this.routes.push(f)}#u(u,r){if(u instanceof Error)return this.errorHandler(u,r);throw u}#f(u,r,A,f){if(f==="HEAD")return(async()=>new Response(null,await this.#f(u,r,A,"GET")))();let w=this.getPath(u,{env:A}),F=this.router.match(f,w),E=new SJ(u,{path:w,matchResult:F,env:A,executionCtx:r,notFoundHandler:this.#A});if(F[0].length===1){let g;try{g=F[0][0][0][0](E,async()=>{E.res=await this.#A(E)})}catch(_){return this.#u(_,E)}return g instanceof Promise?g.then((_)=>_||(E.finalized?E.res:this.#A(E))).catch((_)=>this.#u(_,E)):g??this.#A(E)}let $=B7(F[0],this.errorHandler,this.#A);return(async()=>{try{let g=await $(E);if(!g.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return g.res}catch(g){return this.#u(g,E)}})()}fetch=(u,...r)=>{return this.#f(u,r[1],r[0],u.method)};request=(u,r,A,f)=>{if(u instanceof Request)return this.fetch(r?new Request(u,r):u,A,f);return u=u.toString(),this.fetch(new Request(/^https?:\/\//.test(u)?u:`http://localhost${eu("/",u)}`,r),A,f)};fire=()=>{addEventListener("fetch",(u)=>{u.respondWith(this.#f(u.request,u,void 0,u.request.method))})}};var CJ=W(()=>{rJ();_J();l0();WJ();X0()});function C3(D,u){let r=this.buildAllMatchers(),A=(f,w)=>{let F=r[f]||r[gD],E=F[2][w];if(E)return E;let $=w.match(F[0]);if(!$)return[[],z1];let g=$.indexOf("",1);return[F[1][g],$]};return this.match=A,A(D,u)}var z1;var C7=W(()=>{l0();z1=[]});function LL(D,u){if(D.length===1)return u.length===1?D<u?-1:1:-1;if(u.length===1)return 1;if(D===j1||D===T1)return 1;else if(u===j1||u===T1)return-1;if(D===H3)return 1;else if(u===H3)return-1;return D.length===u.length?D<u?-1:1:u.length-D.length}var H3="[^/]+",j1=".*",T1="(?:|/.*)",y0,QL,HJ=class D{#D;#r;#A=Object.create(null);insert(u,r,A,f,w){if(u.length===0){if(this.#D!==void 0)throw y0;if(w)return;this.#D=r;return}let[F,...E]=u,$=F==="*"?E.length===0?["","",j1]:["","",H3]:F==="/*"?["","",T1]:F.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),g;if($){let _=$[1],R=$[2]||H3;if(_&&$[2]){if(R===".*")throw y0;if(R=R.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(R))throw y0}if(g=this.#A[R],!g){if(Object.keys(this.#A).some((n)=>n!==j1&&n!==T1))throw y0;if(w)return;if(g=this.#A[R]=new D,_!=="")g.#r=f.varIndex++}if(!w&&_!=="")A.push([_,g.#r])}else if(g=this.#A[F],!g){if(Object.keys(this.#A).some((_)=>_.length>1&&_!==j1&&_!==T1))throw y0;if(w)return;g=this.#A[F]=new D}g.insert(E,r,A,f,w)}buildRegExpStr(){let r=Object.keys(this.#A).sort(LL).map((A)=>{let f=this.#A[A];return(typeof f.#r==="number"?`(${A})@${f.#r}`:QL.has(A)?`\\${A}`:A)+f.buildRegExpStr()});if(typeof this.#D==="number")r.unshift(`#${this.#D}`);if(r.length===0)return"";if(r.length===1)return r[0];return"(?:"+r.join("|")+")"}};var H7=W(()=>{y0=Symbol(),QL=new Set(".\\+*[^]$()")});var XJ=class{#D={varIndex:0};#r=new HJ;insert(D,u,r){let A=[],f=[];for(let F=0;;){let E=!1;if(D=D.replace(/\{[^}]+\}/g,($)=>{let g=`@\\${F}`;return f[F]=[g,$],F++,E=!0,g}),!E)break}let w=D.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let F=f.length-1;F>=0;F--){let[E]=f[F];for(let $=w.length-1;$>=0;$--)if(w[$].indexOf(E)!==-1){w[$]=w[$].replace(E,f[F][1]);break}}return this.#r.insert(w,u,A,this.#D,r),A}buildRegExp(){let D=this.#r.buildRegExpStr();if(D==="")return[/^$/,[],[]];let u=0,r=[],A=[];return D=D.replace(/#(\d+)|@(\d+)|\.\*\$/g,(f,w,F)=>{if(w!==void 0)return r[++u]=Number(w),"$()";if(F!==void 0)return A[Number(F)]=++u,"";return""}),[new RegExp(`^${D}`),r,A]}};var iJ=W(()=>{H7()});function YJ(D){return UJ[D]??=new RegExp(D==="*"?"":`^${D.replace(/\/\*$|([.\\+*[^\]$()])/g,(u,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function bL(){UJ=Object.create(null)}function sL(D){let u=new XJ,r=[];if(D.length===0)return qL;let A=D.map((g)=>[!/\*|\/:/.test(g[0]),...g]).sort(([g,_],[R,n])=>g?1:R?-1:_.length-n.length),f=Object.create(null);for(let g=0,_=-1,R=A.length;g<R;g++){let[n,B,C]=A[g];if(n)f[B]=[C.map(([X])=>[X,Object.create(null)]),z1];else _++;let J;try{J=u.insert(B,_,n)}catch(X){throw X===y0?new G3(B):X}if(n)continue;r[_]=C.map(([X,M])=>{let P=Object.create(null);M-=1;for(;M>=0;M--){let[k,s]=J[M];P[k]=s}return[X,P]})}let[w,F,E]=u.buildRegExp();for(let g=0,_=r.length;g<_;g++)for(let R=0,n=r[g].length;R<n;R++){let B=r[g][R]?.[1];if(!B)continue;let C=Object.keys(B);for(let J=0,X=C.length;J<X;J++)B[C[J]]=E[B[C[J]]]}let $=[];for(let g in F)$[g]=r[F[g]];return[w,$,f]}function l2(D,u){if(!D)return;for(let r of Object.keys(D).sort((A,f)=>f.length-A.length))if(YJ(r).test(u))return[...D[r]];return}var qL,UJ,X3=class{name="RegExpRouter";#D;#r;constructor(){this.#D={[gD]:Object.create(null)},this.#r={[gD]:Object.create(null)}}add(D,u,r){let A=this.#D,f=this.#r;if(!A||!f)throw Error(J3);if(!A[D])[A,f].forEach((E)=>{E[D]=Object.create(null),Object.keys(E[gD]).forEach(($)=>{E[D][$]=[...E[gD][$]]})});if(u==="/*")u="*";let w=(u.match(/\/:/g)||[]).length;if(/\*$/.test(u)){let E=YJ(u);if(D===gD)Object.keys(A).forEach(($)=>{A[$][u]||=l2(A[$],u)||l2(A[gD],u)||[]});else A[D][u]||=l2(A[D],u)||l2(A[gD],u)||[];Object.keys(A).forEach(($)=>{if(D===gD||D===$)Object.keys(A[$]).forEach((g)=>{E.test(g)&&A[$][g].push([r,w])})}),Object.keys(f).forEach(($)=>{if(D===gD||D===$)Object.keys(f[$]).forEach((g)=>E.test(g)&&f[$][g].push([r,w]))});return}let F=n3(u)||[u];for(let E=0,$=F.length;E<$;E++){let g=F[E];Object.keys(f).forEach((_)=>{if(D===gD||D===_)f[_][g]||=[...l2(A[_],g)||l2(A[gD],g)||[]],f[_][g].push([r,w-$+E+1])})}}match=C3;buildAllMatchers(){let D=Object.create(null);return Object.keys(this.#r).concat(Object.keys(this.#D)).forEach((u)=>{D[u]||=this.#A(u)}),this.#D=this.#r=void 0,bL(),D}#A(D){let u=[],r=D===gD;if([this.#D,this.#r].forEach((A)=>{let f=A[D]?Object.keys(A[D]).map((w)=>[w,A[D][w]]):[];if(f.length!==0)r||=!0,u.push(...f);else if(D!==gD)u.push(...Object.keys(A[gD]).map((w)=>[w,A[gD][w]]))}),!r)return null;else return sL(u)}};var X7=W(()=>{l0();X0();C7();H7();iJ();qL=[/^$/,[],Object.create(null)],UJ=Object.create(null)});var zL=class{name="PreparedRegExpRouter";#D;#r;constructor(D,u){this.#D=D,this.#r=u}#A(D,u){let r=this.#D[D];r[1].forEach((A)=>A&&A.push(u)),Object.values(r[2]).forEach((A)=>A[0].push(u))}#F(D,u,r,A,f){let w=this.#D[D];if(!f)w[2][u][0].push([r,{}]);else A.forEach((F)=>{if(typeof F==="number")w[1][F].push([r,f]);else w[2][F||u][0].push([r,f])})}add(D,u,r){if(!this.#D[D]){let f=this.#D[gD],w={};for(let F in f[2])w[F]=[f[2][F][0].slice(),z1];this.#D[D]=[f[0],f[1].map((F)=>Array.isArray(F)?F.slice():0),w]}if(u==="/*"||u==="*"){let f=[r,{}];if(D===gD)for(let w in this.#D)this.#A(w,f);else this.#A(D,f);return}let A=this.#r[u];if(!A)throw Error(`Path ${u} is not registered`);for(let[f,w]of A)if(D===gD)for(let F in this.#D)this.#F(F,u,r,f,w);else this.#F(D,u,r,f,w)}buildAllMatchers(){return this.#D}match=C3};var MJ=W(()=>{l0();C7();X7()});var OJ=W(()=>{X7();MJ()});var i7=class{name="SmartRouter";#D=[];#r=[];constructor(D){this.#D=D.routers}add(D,u,r){if(!this.#r)throw Error(J3);this.#r.push([D,u,r])}match(D,u){if(!this.#r)throw Error("Fatal error");let r=this.#D,A=this.#r,f=r.length,w=0,F;for(;w<f;w++){let E=r[w];try{for(let $=0,g=A.length;$<g;$++)E.add(...A[$]);F=E.match(D,u)}catch($){if($ instanceof G3)continue;throw $}this.match=E.match.bind(E),this.#D=[E],this.#r=void 0;break}if(w===f)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,F}get activeRouter(){if(this.#r||this.#D.length!==1)throw Error("No active router has been determined yet.");return this.#D[0]}};var PJ=W(()=>{l0()});var kJ=W(()=>{PJ()});var v1,jL=(D)=>{for(let u in D)return!0;return!1},IJ=class D{#D;#r;#A;#F=0;#u=v1;constructor(u,r,A){if(this.#r=A||Object.create(null),this.#D=[],u&&r){let f=Object.create(null);f[u]={handler:r,possibleKeys:[],score:0},this.#D=[f]}this.#A=[]}insert(u,r,A){this.#F=++this.#F;let f=this,w=TW(r),F=[];for(let E=0,$=w.length;E<$;E++){let g=w[E],_=w[E+1],R=vW(g,_),n=Array.isArray(R)?R[0]:g;if(n in f.#r){if(f=f.#r[n],R)F.push(R[1]);continue}if(f.#r[n]=new D,R)f.#A.push(R),F.push(R[1]);f=f.#r[n]}return f.#D.push({[u]:{handler:A,possibleKeys:F.filter((E,$,g)=>g.indexOf(E)===$),score:this.#F}}),f}#f(u,r,A,f,w){for(let F=0,E=r.#D.length;F<E;F++){let $=r.#D[F],g=$[A]||$[gD],_={};if(g!==void 0){if(g.params=Object.create(null),u.push(g),f!==v1||w&&w!==v1)for(let R=0,n=g.possibleKeys.length;R<n;R++){let B=g.possibleKeys[R],C=_[g.score];g.params[B]=w?.[B]&&!C?w[B]:f[B]??w?.[B],_[g.score]=!0}}}}search(u,r){let A=[];this.#u=v1;let w=[this],F=g7(r),E=[],$=F.length,g=null;for(let _=0;_<$;_++){let R=F[_],n=_===$-1,B=[];for(let J=0,X=w.length;J<X;J++){let M=w[J],P=M.#r[R];if(P)if(P.#u=M.#u,n){if(P.#r["*"])this.#f(A,P.#r["*"],u,M.#u);this.#f(A,P,u,M.#u)}else B.push(P);for(let k=0,s=M.#A.length;k<s;k++){let q=M.#A[k],Y=M.#u===v1?{}:{...M.#u};if(q==="*"){let WD=M.#r["*"];if(WD)this.#f(A,WD,u,M.#u),WD.#u=Y,B.push(WD);continue}let[v,N,rD]=q;if(!R&&!(rD instanceof RegExp))continue;let _D=M.#r[v];if(rD instanceof RegExp){if(g===null){g=Array($);let qD=r[0]==="/"?1:0;for(let Ar=0;Ar<$;Ar++)g[Ar]=qD,qD+=F[Ar].length+1}let WD=r.substring(g[_]),e=rD.exec(WD);if(e){if(Y[N]=e[0],this.#f(A,_D,u,M.#u,Y),jL(_D.#r)){_D.#u=Y;let qD=e[0].match(/\//)?.length??0;(E[qD]||=[]).push(_D)}continue}}if(rD===!0||rD.test(R))if(Y[N]=R,n){if(this.#f(A,_D,u,Y,M.#u),_D.#r["*"])this.#f(A,_D.#r["*"],u,Y,M.#u)}else _D.#u=Y,B.push(_D)}}let C=E.shift();w=C?B.concat(C):B}if(A.length>1)A.sort((_,R)=>{return _.score-R.score});return[A.map(({handler:_,params:R})=>[_,R])]}};var VJ=W(()=>{l0();X0();v1=Object.create(null)});var U7=class{name="TrieRouter";#D;constructor(){this.#D=new IJ}add(D,u,r){let A=n3(u);if(A){for(let f=0,w=A.length;f<w;f++)this.#D.insert(D,A[f],r);return}this.#D.insert(D,u,r)}match(D,u){return this.#D.search(D,u)}};var KJ=W(()=>{X0();VJ()});var hJ=W(()=>{KJ()});var Y7;var NJ=W(()=>{CJ();OJ();kJ();hJ();Y7=class extends GJ{constructor(D={}){super(D);this.router=D.router??new i7({routers:[new X3,new U7]})}}});var QJ=W(()=>{NJ()});function LJ(D,u){let r={};return Object.keys(D.paths).forEach((A)=>{r[eu(u.replaceAll(/:([^\/]+)/g,"{$1}"),A)]=D.paths[A]}),{...D,paths:r}}function qJ(D){return/^application\/([a-z-\.]+\+)?json/.test(D)}function bJ(D){return D.startsWith("multipart/form-data")||D.startsWith("application/x-www-form-urlencoded")}var sJ;var zJ=W(()=>{jW();uJ();QJ();X0();YD();sJ=class D extends Y7{openAPIRegistry;defaultHook;constructor(u){super(u);this.openAPIRegistry=new f7,this.defaultHook=u?.defaultHook}openapi=({middleware:u,hide:r,...A},f,w=this.defaultHook)=>{if(!r)this.openAPIRegistry.registerPath(A);let F=[];if(A.request?.query){let g=d0("query",A.request.query,w);F.push(g)}if(A.request?.params){let g=d0("param",A.request.params,w);F.push(g)}if(A.request?.headers){let g=d0("header",A.request.headers,w);F.push(g)}if(A.request?.cookies){let g=d0("cookie",A.request.cookies,w);F.push(g)}let E=A.request?.body?.content;if(E)for(let g of Object.keys(E)){if(!E[g])continue;let _=E[g].schema;if(!(_ instanceof p))continue;if(qJ(g)){let R=d0("json",_,w);if(A.request?.body?.required)F.push(R);else{let n=async(B,C)=>{if(B.req.header("content-type")){if(qJ(B.req.header("content-type")))return await R(B,C)}B.req.addValidatedData("json",{}),await C()};F.push(n)}}if(bJ(g)){let R=d0("form",_,w);if(A.request?.body?.required)F.push(R);else{let n=async(B,C)=>{if(B.req.header("content-type")){if(bJ(B.req.header("content-type")))return await R(B,C)}B.req.addValidatedData("form",{}),await C()};F.push(n)}}}let $=u?Array.isArray(u)?u:[u]:[];return this.on([A.method],A.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...$,...F,f),this};getOpenAPIDocument=(u)=>{let A=new w7(this.openAPIRegistry.definitions).generateDocument(u);return this._basePath?LJ(A,this._basePath):A};getOpenAPI31Document=(u)=>{let A=new $7(this.openAPIRegistry.definitions).generateDocument(u);return this._basePath?LJ(A,this._basePath):A};doc=(u,r)=>{return this.get(u,(A)=>{let f=typeof r==="function"?r(A):r;try{let w=this.getOpenAPIDocument(f);return A.json(w)}catch(w){return A.json(w,500)}})};doc31=(u,r)=>{return this.get(u,(A)=>{let f=typeof r==="function"?r(A):r;try{let w=this.getOpenAPI31Document(f);return A.json(w)}catch(w){return A.json(w,500)}})};route(u,r){let A=u.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(u,r),!(r instanceof D))return this;return r.openAPIRegistry.definitions.forEach((f)=>{switch(f.type){case"component":return this.openAPIRegistry.registerComponent(f.componentType,f.name,f.component);case"route":{this.openAPIRegistry.registerPath({...f.route,path:eu(A,r._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),f.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...f.webhook,path:eu(A,r._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),f.webhook.path)});return}case"schema":return this.openAPIRegistry.register(f.schema._def.openapi._internal.refId,f.schema);case"parameter":return this.openAPIRegistry.registerParameter(f.schema._def.openapi._internal.refId,f.schema);default:throw Error(`Unknown registry type: ${f}`)}}),this}basePath(u){return new D({...super.basePath(u),defaultHook:this.defaultHook})}};HW(S)});function M7(D){if(!TL.some((r)=>D.includes(r)))return D;return console.warn("DEPRECATION WARNING: It looks like you're using legacy CSS variables in your custom CSS string. Please migrate them to use the updated prefixes. See https://github.com/scalar/scalar/blob/main/documentation/themes.md#theme-prefix-changes"),jJ.reduce((r,[A,f])=>r.replaceAll(A,f),D)}var jJ,TL;var O7=W(()=>{jJ=[["--theme-","--scalar-"],["--sidebar-","--scalar-sidebar-"]],TL=jJ.map(([D])=>D)});var vL,ZL,oL,k7,dL,vJ,TJ="https://api.scalar.com/request-proxy",P7="https://proxy.scalar.com",ZJ,lL,oJ=(D)=>{let u={...D};if(u.customCss)u.customCss=M7(u.customCss);if(u.proxy){if(console.warn("[DEPRECATED] You\u2019re using the deprecated 'proxy' attribute, rename it to 'proxyUrl' or update the package."),!u.proxyUrl)u.proxyUrl=u.proxy;delete u.proxy}if(u.proxyUrl===TJ)console.warn(`[DEPRECATED] Warning: configuration.proxyUrl points to our old proxy (${TJ}).`),console.warn(`[DEPRECATED] We are overwriting the value and use the new proxy URL (${P7}) instead.`),console.warn(`[DEPRECATED] Action Required: You should manually update your configuration to use the new URL (${P7}). Read more: https://github.com/scalar/scalar`),u.proxyUrl=P7;return u},I7,yL;var dJ=W(()=>{YD();O7();vL=S.enum(["alternate","default","moon","purple","solarized","bluePlanet","deepSpace","saturn","kepler","elysiajs","fastify","mars","none"]),ZL=S.enum(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]),oL=S.enum(["adonisjs","docusaurus","dotnet","elysiajs","express","fastapi","fastify","go","hono","html","laravel","litestar","nestjs","nextjs","nitro","nuxt","platformatic","react","rust","vue"]).nullable(),k7=S.object({url:S.string().optional(),content:S.union([S.string(),S.record(S.any()),S.function().returns(S.record(S.any())),S.null()]).optional(),title:S.string().optional(),slug:S.string().optional()}),dL=S.object({basePath:S.string()}),vJ=S.object({authentication:S.any().optional(),baseServerURL:S.string().optional(),hideClientButton:S.boolean().optional().default(!1).catch(!1),proxyUrl:S.string().optional(),searchHotKey:ZL.optional(),servers:S.array(S.any()).optional(),showSidebar:S.boolean().optional().default(!0).catch(!0),spec:k7.optional(),theme:vL.optional().default("default").catch("default"),_integration:oL.optional()}),ZJ=vJ.merge(S.object({layout:S.enum(["modern","classic"]).optional().default("modern").catch("modern"),proxy:S.string().optional(),isEditable:S.boolean().optional().default(!1).catch(!1),hideModels:S.boolean().optional().default(!1).catch(!1),hideDownloadButton:S.boolean().optional().default(!1).catch(!1),hideTestRequestButton:S.boolean().optional().default(!1).catch(!1),hideSearch:S.boolean().optional().default(!1).catch(!1),darkMode:S.boolean().optional(),forceDarkModeState:S.enum(["dark","light"]).optional(),hideDarkModeToggle:S.boolean().optional().default(!1).catch(!1),metaData:S.any().optional(),favicon:S.string().optional(),hiddenClients:S.union([S.record(S.union([S.boolean(),S.array(S.string())])),S.array(S.string()),S.literal(!0)]).optional(),defaultHttpClient:S.object({targetKey:S.custom(),clientKey:S.string()}).optional(),customCss:S.string().optional(),onSpecUpdate:S.function().args(S.string()).returns(S.void()).optional(),onServerChange:S.function().args(S.string()).returns(S.void()).optional(),pathRouting:dL.optional(),generateHeadingSlug:S.function().args(S.object({slug:S.string().default("headingSlug")})).returns(S.string()).optional(),generateModelSlug:S.function().args(S.object({name:S.string().default("modelName")})).returns(S.string()).optional(),generateTagSlug:S.function().args(S.object({name:S.string().default("tagName")})).returns(S.string()).optional(),generateOperationSlug:S.function().args(S.object({path:S.string(),operationId:S.string().optional(),method:S.string(),summary:S.string().optional()})).returns(S.string()).optional(),generateWebhookSlug:S.function().args(S.object({name:S.string(),method:S.string().optional()})).returns(S.string()).optional(),onLoaded:S.function().returns(S.void()).optional(),redirect:S.function().args(S.string()).returns(S.string().nullable().optional()).optional(),withDefaultFonts:S.boolean().optional().default(!0).catch(!0),defaultOpenAllTags:S.boolean().optional(),tagsSorter:S.union([S.literal("alpha"),S.function().args(S.any(),S.any()).returns(S.number())]).optional(),operationsSorter:S.union([S.literal("alpha"),S.literal("method"),S.function().args(S.any(),S.any()).returns(S.number())]).optional()})),lL=ZJ.merge(S.object({spec:S.object({sources:S.array(k7)})})),I7=ZJ.transform(oJ),yL=lL.transform(oJ)});var V7;var lJ=W(()=>{YD();V7=S.object({cdn:S.string().optional().default("https://cdn.jsdelivr.net/npm/@scalar/api-reference"),pageTitle:S.string().optional().default("Scalar API Reference")})});var yJ=W(()=>{dJ();lJ();O7()});function cL(D,u){return`
1584
1584
  <script
1585
1585
  id="api-reference"
1586
1586
  type="application/json"
1587
- data-configuration="${CL(D)}">${HL(D)}</script>
1587
+ data-configuration="${tL(D)}">${pL(D)}</script>
1588
1588
  <script src="${u}"></script>
1589
- `}var iG=(D,u="")=>{let{cdn:r,pageTitle:A,...f}=D,w=S7.parse({cdn:r,pageTitle:A,customTheme:u}),F=R7.parse(f);return`
1589
+ `}var cJ=(D,u="")=>{let{cdn:r,pageTitle:A,...f}=D,w=V7.parse({cdn:r,pageTitle:A,customTheme:u}),F=I7.parse(f);return`
1590
1590
  <!DOCTYPE html>
1591
1591
  <html>
1592
1592
  <head>
@@ -1600,10 +1600,10 @@ ${A}`)}formatType(D,u,r){let A=HQ[D.type]||nQ[D.level]||"gray";if(u)return YQ(A)
1600
1600
  </style>
1601
1601
  </head>
1602
1602
  <body>
1603
- ${GL(F,w.cdn)}
1603
+ ${cL(F,w.cdn)}
1604
1604
  </body>
1605
1605
  </html>
1606
- `},CL=(D)=>{let u={...D};if(!u.spec?.url)delete u.spec;else if(u.spec?.content)delete u.spec?.content;return JSON.stringify(u).split('"').join("&quot;")},HL=(D)=>D.spec?.content?typeof D.spec?.content==="function"?JSON.stringify(D.spec?.content()):JSON.stringify(D.spec?.content):"";var kG=W(()=>{PG()});var nL,UL=`
1606
+ `},tL=(D)=>{let u={...D};if(!u.spec?.url)delete u.spec;else if(u.spec?.content)delete u.spec?.content;return JSON.stringify(u).split('"').join("&quot;")},pL=(D)=>D.spec?.content?typeof D.spec?.content==="function"?JSON.stringify(D.spec?.content()):JSON.stringify(D.spec?.content):"";var tJ=W(()=>{yJ()});var xL,mL=`
1607
1607
  .light-mode {
1608
1608
  color-scheme: light;
1609
1609
  --scalar-color-1: #2a2f45;
@@ -1703,30 +1703,39 @@ ${A}`)}formatType(D,u,r){let A=HQ[D.type]||nQ[D.level]||"gray";if(u)return YQ(A)
1703
1703
  --scalar-sidebar-search-border-color: transparent;
1704
1704
  --scalar-sidebar-search-color: var(--scalar-color-3);
1705
1705
  }
1706
- `,B7=(D)=>{let u={...nL,...D};return async(r)=>r.html(`${iG(u,UL)}`)};var IG=W(()=>{kG();nL={_integration:"hono"}});var VG=W(()=>{IG()});function KG(D,u){if(D instanceof yu)return u.json(D.toJSON(),D.status);return vr.error("Unhandled error:",D),u.json({error:{code:"INTERNAL_ERROR",message:"An unexpected error occurred"}},500)}var hG=W(()=>{z2();D3()});var NG=async(D,u)=>{let r=performance.now();await u();let A=Math.round(performance.now()-r);vr.info(`${D.req.method} ${D.req.path} ${D.res.status} ${A}ms`)};var QG=W(()=>{D3()});var eG={};dA(eG,{createWorkerApp:()=>hL,bootstrapWorkerApp:()=>vG});import{Buffer as W7}from"buffer";import{spawn as XL,spawnSync as YL}from"child_process";import{createHmac as ML,randomUUID as l2,timingSafeEqual as OL}from"crypto";import{mkdir as PL,readFile as bG,stat as iL}from"fs/promises";import Dr from"path";import zG from"process";import{fileURLToPath as kL}from"url";async function vG(D={}){let u=D.dbPath??X2.WORKER_DB_PATH;await PL(Dr.dirname(u),{recursive:!0}),u2(),W1(u),G1(D.migrationsFolder??X2.WORKER_MIGRATIONS_FOLDER);let r=D.runtimeVersion??IL,A=D.workersRoot??Dr.join(Dr.dirname(u),"workers"),f=new Map,w=XA({executor:D.executor,now:D.now,officialAppsRoot:D.officialAppsRoot,registryContext:()=>{let $=X0();return{availableConnectorIds:$.connectors.map((g)=>g.id),enabledConnectorIds:$.connectors.filter((g)=>g.enabled).map((g)=>g.id),hostVersion:r}},workersRoot:A}),F={authProvider:ZF({token:D.token??X2.AIWORKER_LOCAL_TOKEN}),host:w,mountingAppServices:new Map,mountedAppServices:new Map,runtimes:f,startedAt:new Date().toISOString(),runtimeVersion:r,now:D.now};await F.host.bootstrapOfficialSoulApps();for(let $ of Er()){let g=F.host.createRuntimeForWorker($);await g.init(),f.set($.id,g)}let E=new GG;return E.use(NG),E.onError(KG),E.use("/api/local/*",async($,g)=>{if(NL($,F))return g();let R=F.authProvider.authenticate({authorization:$.req.header("authorization")});if(R.status==="denied")return $.json({error:{code:"UNAUTHORIZED",message:R.reason}},401);if(R.status==="authenticated")TG.set($,R.identity);return g()}),E.get("/health",($)=>$.json({mode:"soul-workspace",status:"ok",workers:Er().map((g)=>({id:g.id,soulId:g.soulId,status:g.status})),runtimeVersion:F.runtimeVersion,startedAt:F.startedAt,checkedAt:new Date().toISOString()})),E.get("/api/local/info",($)=>$.json({runtimeVersion:F.runtimeVersion,startedAt:F.startedAt,workers:Er()})),E.get("/api/local/apps",($)=>$.json({apps:F.host.listApps()})),E.post("/api/local/apps/install",async($)=>{let g=await sD($.req),R=typeof g.manifestPath==="string"&&g.manifestPath.trim()?await F.host.installAppFromPath(g.manifestPath):F.host.installAppManifest({manifest:g.manifest,sourceKind:"inline",sourceRef:"api:inline"});return $.json({app:R,catalog:F.host.listCatalog()},201)}),E.get("/api/local/apps/:appId",($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return iu($,"Soul App");return $.json({app:g})}),E.get("/api/local/apps/:appId/security-review",($)=>{let g=$.req.param("appId");if(!F.host.getApp(g))return iu($,"Soul App");return $.json({review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/enable",($)=>{let g=$.req.param("appId"),R=F.host.enableApp(g);return $.json({app:R,catalog:F.host.listCatalog(),review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/disable",($)=>{let g=$.req.param("appId"),R=F.host.disableApp(g);return aL(F,g),$.json({app:R,catalog:F.host.listCatalog(),review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/healthcheck",($)=>$.json({app:F.host.healthcheckApp($.req.param("appId"))})),E.get("/api/local/apps/:appId/broker/permissions",($)=>{let g=Eu(ku($,F));return $.json({permissions:g.permissions.list()})}),E.get("/api/local/apps/:appId/broker/providers",($)=>{let g=Eu(ku($,F));return $.json({registry:g.providers.list()})}),E.get("/api/local/apps/:appId/broker/search",($)=>{let g=Eu(ku($,F)).search.query($.req.query("query")??"");return l0($,"result",g)}),E.put("/api/local/apps/:appId/broker/search/:itemId{.+}",async($)=>{let g=await $.req.json().catch(()=>({})),R=Eu(ku($,F)).search.upsert($.req.param("itemId"),qL(g));return l0($,"item",R)}),E.get("/api/local/apps/:appId/broker/storage",($)=>{let g=Eu(ku($,F)).storage.list();return l0($,"records",g)}),E.get("/api/local/apps/:appId/broker/storage/:key{.+}",($)=>{let g=Eu(ku($,F)).storage.get($.req.param("key"));return l0($,"record",g)}),E.put("/api/local/apps/:appId/broker/storage/:key{.+}",async($)=>{let g=await sD($.req),R=Eu(ku($,F)).storage.put($.req.param("key"),ir(g.valueJson)?g.valueJson:{},{namespace:g.namespace});return l0($,"record",R)}),E.post("/api/local/apps/:appId/broker/connectors/:connectorId/evidence",async($)=>{let g=await sD($.req),R=Eu(ku($,F)).connectors.readEvidence($.req.param("connectorId"),ir(g.query)?g.query:{});return l0($,"evidence",R)}),E.get("/api/local/apps/:appId/broker/audit",($)=>{let g=Eu(ku($,F));return $.json({events:g.audit.list()})}),E.post("/api/local/apps/:appId/broker/engine/invocations",async($)=>{let g=await sD($.req),R=Eu(ku($,F)).engine.createInvocation({prompt:g.prompt??""});return l0($,"invocation",R)}),E.post("/api/local/apps/:appId/actions/:actionId",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return $.json({error:{code:"SOUL_APP_NOT_FOUND",message:`Soul App was not found: ${$.req.param("appId")}`}},404);if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);let R=zL(g,$.req.param("actionId"));if(!R)return $.json({error:{code:"SOUL_APP_ACTION_NOT_DECLARED",message:`Soul App action is not declared: ${$.req.param("actionId")}`}},404);let S=await sD($.req),B=jL(S.scope),J=LG($,F,R.requiredPermissions,`action ${R.id}`,B);if(J)return G7($,J);return ZL($,F,g,R,ir(S.input)?S.input:{},B)}),E.get("/api/local/apps/:appId/search",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return $.json({error:{code:"SOUL_APP_NOT_FOUND",message:`Soul App was not found: ${$.req.param("appId")}`}},404);if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);let R=$.req.query("providerId")??"",S=g.manifest.ui.shell?.search;if(!S||S.protocolProvider!==R)return $.json({error:{code:"SOUL_APP_SEARCH_NOT_DECLARED",message:`Soul App search provider is not declared: ${R}`}},404);let B=LG($,F,S.requiredPermissions,`search ${S.id}`);if(B)return G7($,B);return oL($,F,g,S)}),E.get("/api/local/apps/:appId/surfaces/:surfaceId",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return iu($,"Soul App");if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);return dL($,F,g,$.req.param("surfaceId"))}),E.get("/api/local/workers",($)=>$.json({workers:Er()})),E.post("/api/local/workers",async($)=>{let g=await sD($.req),R=await F.host.createSoulWorker({defaultEngineId:g.defaultEngineId,id:g.id,metadata:g.metadata,name:Pr(g.name,"name"),soulId:Pr(g.soulId,"soulId")});return F.runtimes.set(R.worker.id,R.runtime),$.json({worker:R.worker,snapshot:R.snapshot},201)}),E.get("/api/local/workers/:workerId",($)=>{let g=PD($.req.param("workerId"));if(!g)return iu($,"worker");return $.json({worker:g,snapshot:eu(F,g.id).snapshot()})}),E.patch("/api/local/workers/:workerId",async($)=>{let g=PD($.req.param("workerId"));if(!g)return iu($,"worker");let R=await sD($.req),S=r2({id:g.id,soulId:g.soulId,name:R.name??g.name,status:R.status??g.status,defaultEngineId:R.defaultEngineId??g.defaultEngineId,metadataJson:R.metadata??g.metadataJson}),B=F.host.createRuntimeForWorker(S);return await B.init(),F.runtimes.set(S.id,B),$.json({worker:S,snapshot:B.snapshot()})}),E.get("/api/local/souls",($)=>$.json({souls:F.host.listSouls()})),E.get("/api/local/souls/:id",($)=>{let g=F.host.findSoul($.req.param("id"));if(!g)return iu($,"soul");return $.json({soul:g})}),E.get("/api/local/templates",($)=>{let g=$.req.query("soulId"),R=F.host.listCapabilityTemplates(g);return $.json({templates:R})}),E.get("/api/local/templates/:id",($)=>{let g=F.host.listCatalog().templates.find((R)=>R.id===$.req.param("id"));if(!g)return iu($,"template");return $.json({template:g})}),E.get("/api/local/workers/:workerId/templates",($)=>{return $.json({templates:F.host.listCapabilityTemplatesForWorker($.req.param("workerId"))})}),E.get("/api/local/workers/:workerId/templates/:templateId",($)=>{let g=sG(F,$.req.param("workerId"),$.req.param("templateId"));return $.json({template:g})}),E.get("/api/local/workspaces",($)=>$.json({workspaces:nu()})),E.get("/api/local/workers/:workerId/workspaces",($)=>{let g=$.req.param("workerId");return eu(F,g),$.json({workspaces:nu(g)})}),E.post("/api/local/workers/:workerId/workspaces",async($)=>{let g=eu(F,$.req.param("workerId")),R=await sD($.req),S=await g.createWorkspace({name:Pr(R.name,"name"),type:R.type??"workspace",sourcePointers:R.sourcePointers??[],metadata:R.metadata??{}});return $.json({workspace:S},201)}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId",($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({workspace:g})}),E.patch("/api/local/workers/:workerId/workspaces/:workspaceId",async($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId")),R=await sD($.req);return $.json({workspace:hF({id:g.id,...R})})}),E.get("/api/local/workspaces/:workspaceId",($)=>{let g=pD($.req.param("workspaceId"));if(!g)return iu($,"workspace");return $.json({workspace:g})}),E.patch("/api/local/workspaces/:workspaceId",async($)=>{let g=await sD($.req);return $.json({workspace:hF({id:$.req.param("workspaceId"),...g})})}),E.get("/api/local/workspaces/:workspaceId/profile",async($)=>{let g=au($.req.param("workspaceId"));return $.text(await eu(F,g.workerId).files(g.id).read("README.md"))}),E.post("/api/local/workspaces/:workspaceId/profile-revisions",async($)=>{let g=au($.req.param("workspaceId")),R=await sD($.req),S=R.verdict??"pass";if(S!=="pass"&&S!=="warn")return $.json({error:{code:"PROFILE_REVISION_NOT_APPROVED",message:"Only pass or warn reviews can promote a profile revision."}},400);let B=await eu(F,g.workerId).promoteProfileRevision({artifactId:Pr(R.artifactId,"artifactId"),findingsJson:R.findingsJson??[],profileMarkdown:R.profileMarkdown,risksJson:R.risksJson??[],tagName:R.tagName,verdict:S,workspaceId:g.id});return $.json({profileRevision:B},201)}),E.get("/api/local/sessions",($)=>$.json({sessions:tr()})),E.get("/api/local/turns",($)=>$.json({turns:gr()})),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/sessions",($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({sessions:tr(g.id)})}),E.post("/api/local/workers/:workerId/workspaces/:workspaceId/sessions",async($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return W3($,F,g,!1)}),E.post("/api/local/workers/:workerId/workspaces/:workspaceId/sessions/stream",async($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return W3($,F,g,!0)}),E.get("/api/local/workspaces/:workspaceId/sessions",($)=>{let g=au($.req.param("workspaceId"));return $.json({sessions:tr(g.id)})}),E.post("/api/local/workspaces/:workspaceId/sessions",async($)=>{let g=au($.req.param("workspaceId"));return W3($,F,g,!1)}),E.post("/api/local/workspaces/:workspaceId/sessions/stream",async($)=>{let g=au($.req.param("workspaceId"));return W3($,F,g,!0)}),E.get("/api/local/sessions/:sessionId",($)=>{let g=fu($.req.param("sessionId"));if(!g)return iu($,"session");return $.json({session:g,turns:gr(g.id),events:_r(g.id)})}),E.get("/api/local/workers/:workerId/sessions/:sessionId",($)=>{let g=TA($.req.param("workerId"),$.req.param("sessionId"));return $.json({session:g,turns:gr(g.id),events:_r(g.id)})}),E.get("/api/local/workers/:workerId/sessions/:sessionId/events",($)=>{let g=TA($.req.param("workerId"),$.req.param("sessionId")),R=Number($.req.query("after")??$.req.header("last-event-id")??0),S=_r(g.id).filter((B)=>!Number.isFinite(R)||B.id>R);return $.json({events:S})}),E.get("/api/local/workers/:workerId/sessions/:sessionId/turns",($)=>{let g=TA($.req.param("workerId"),$.req.param("sessionId"));return $.json({turns:gr(g.id)})}),E.post("/api/local/workers/:workerId/sessions/:sessionId/messages",async($)=>{let g=TA($.req.param("workerId"),$.req.param("sessionId"));return G3($,F,g,!1)}),E.post("/api/local/workers/:workerId/sessions/:sessionId/messages/stream",async($)=>{let g=TA($.req.param("workerId"),$.req.param("sessionId"));return G3($,F,g,!0)}),E.get("/api/local/sessions/:sessionId/events",($)=>{let g=sA($.req.param("sessionId")),R=Number($.req.query("after")??$.req.header("last-event-id")??0),S=_r(g.id).filter((B)=>!Number.isFinite(R)||B.id>R);return $.json({events:S})}),E.get("/api/local/sessions/:sessionId/turns",($)=>{let g=sA($.req.param("sessionId"));return $.json({turns:gr(g.id)})}),E.post("/api/local/sessions/:sessionId/turns/stream",async($)=>{let g=sA($.req.param("sessionId"));return G3($,F,g,!0)}),E.post("/api/local/sessions/:sessionId/turns",async($)=>{let g=sA($.req.param("sessionId"));return G3($,F,g,!1)}),E.get("/api/local/files",($)=>$.json({files:bu()})),E.get("/api/local/workers/:workerId/files",($)=>{let g=C3($.req.param("workerId")),R=new Set(nu(g.id).map((S)=>S.id));return $.json({files:bu().filter((S)=>R.has(S.workspaceId))})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files",($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({files:bu(g.id)})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files/search",($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId")),R=$.req.query("q")?.toLowerCase()??"",S=bu(g.id).filter((B)=>B.path.toLowerCase().includes(R));return $.json({files:S})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId"));return $.text(await eu(F,g.workerId).files(g.id).read($.req.param("path")))}),E.put("/api/local/workers/:workerId/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=sr($.req.param("workerId"),$.req.param("workspaceId")),R=$.req.param("path"),S=await eu(F,g.workerId).files(g.id).write({path:R,content:await $.req.text()}),B=C1({id:l2(),workspaceId:g.id,path:R,kind:S.kind,size:S.size,mtime:S.mtime,hash:S.hash,source:"user"});return $.json({file:B})}),E.get("/api/local/workspaces/:workspaceId/files",($)=>{let g=au($.req.param("workspaceId"));return $.json({files:bu(g.id)})}),E.get("/api/local/workspaces/:workspaceId/files/search",($)=>{let g=au($.req.param("workspaceId")),R=$.req.query("q")?.toLowerCase()??"",S=bu(g.id).filter((B)=>B.path.toLowerCase().includes(R));return $.json({files:S})}),E.get("/api/local/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=au($.req.param("workspaceId"));return $.text(await eu(F,g.workerId).files(g.id).read($.req.param("path")))}),E.put("/api/local/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=au($.req.param("workspaceId")),R=$.req.param("path"),S=await eu(F,g.workerId).files(g.id).write({path:R,content:await $.req.text()}),B=C1({id:l2(),workspaceId:g.id,path:R,kind:S.kind,size:S.size,mtime:S.mtime,hash:S.hash,source:"user"});return $.json({file:B})}),E.get("/api/local/artifacts",($)=>$.json({artifacts:Rr()})),E.get("/api/local/workers/:workerId/artifacts",($)=>{let g=C3($.req.param("workerId")),R=new Set(nu(g.id).map((S)=>S.id));return $.json({artifacts:Rr().filter((S)=>R.has(S.workspaceId))})}),E.get("/api/local/workspaces/:workspaceId/artifacts",($)=>{let g=au($.req.param("workspaceId"));return $.json({artifacts:Rr(g.id)})}),E.get("/api/local/artifacts/:id",($)=>{let g=xr($.req.param("id"));if(!g)return iu($,"artifact");return $.json({artifact:g})}),E.get("/api/local/reviews",($)=>$.json({reviews:A2()})),E.post("/api/local/reviews",async($)=>{let g=await sD($.req),R=Pr(g.workspaceId,"workspaceId"),S=i0({id:l2(),workspaceId:R,sessionId:g.sessionId??null,turnId:g.turnId??null,artifactId:g.artifactId??null,verdict:g.verdict??"needs_review",findingsJson:g.findingsJson??[],risksJson:g.risksJson??[]});return $.json({review:S},201)}),E.get("/api/local/reviews/:id",($)=>{let g=H1($.req.param("id"));if(!g)return iu($,"review");return $.json({review:g})}),E.get("/api/local/lessons",($)=>$.json({lessons:f2()})),E.post("/api/local/lessons",async($)=>{let g=await sD($.req),R=mr({id:l2(),workspaceId:Pr(g.workspaceId,"workspaceId"),sourceReviewId:g.sourceReviewId??null,statement:Pr(g.statement,"statement"),evidenceJson:Array.isArray(g.evidenceJson)?g.evidenceJson:[]});return $.json({lesson:R},201)}),E.patch("/api/local/lessons/:id",async($)=>{let g=await sD($.req);return $.json({lesson:n1($.req.param("id"),g.status)})}),E.get("/api/local/settings",($)=>{let g=X0();return $.json({settings:g})}),E.patch("/api/local/settings",async($)=>{let g=await sD($.req),R=X0(),S=C7({...R,...g,byok:{...R.byok,...g.byok??{}},updatedAt:new Date().toISOString()});return $.json({settings:S})}),E.post("/api/local/settings/engines/rescan",($)=>{let g=X0(),R=C7({...g,engines:mG(),updatedAt:new Date().toISOString()});return $.json({engines:R.engines,settings:R})}),E.post("/api/local/settings/engines/test",async($)=>{let g=await sD($.req),R=X0(),S=g.engineId??R.engineId,B=R.engines.find((J)=>J.id===S);if(!B)return $.json({result:{engineId:S,message:"Engine is not known in local settings.",status:"fail"}},404);if(!B.installed)return $.json({result:{engineId:S,message:`${B.name} is not installed on PATH.`,status:"fail"}});return $.json({result:{engineId:S,message:`${B.name} responded as ${B.version??B.path}.`,status:"pass"}})}),E.get("/api/local/events",($)=>$.json({events:_r()})),E.all("/api/local/apps/:appId/:path{.+}",($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return iu($,"Soul App");if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);return yL($,F,g)}),fq(E),E.doc("/openapi.json",{openapi:"3.1.0",info:{title:"AIWorker Local Daemon API",version:r,description:"Vertical Soul workspace API for Soul workers, workspaces, sessions, turns, artifacts, reviews, memory candidates, and settings."}}),E.get("/docs",B7({spec:{url:"/openapi.json"}})),E.get("/",async($)=>J7($,D.webStaticDir)),E.get("/workers/:path{.+}",async($)=>J7($,D.webStaticDir)),E.get("/workspaces/:path{.+}",async($)=>J7($,D.webStaticDir)),E.get("/favicon.svg",async($)=>vA($,D.webStaticDir,"favicon.svg")),E.get("/logo.svg",async($)=>vA($,D.webStaticDir,"logo.svg")),E.get("/assets/:path{.+}",async($)=>vA($,D.webStaticDir,`assets/${$.req.param("path")}`)),E.get("/fonts/:path{.+}",async($)=>vA($,D.webStaticDir,`fonts/${$.req.param("path")}`)),E.get("/engine-icons/:path{.+}",async($)=>vA($,D.webStaticDir,`engine-icons/${$.req.param("path")}`)),{app:E,port:X2.PORT,state:F}}async function hL(){let{app:D,port:u}=await vG();return{app:D,port:u}}function NL(D,u){let r=QL(new URL(D.req.url).pathname);if(!r)return!1;let A=D.req.header("x-aiworker-mount-token");if(!A)return!1;let f=u.mountedAppServices.get(r);return f?LL(A,f.mountToken):!1}function QL(D){let u=/^\/api\/local\/apps\/([^/]+)\/broker(?:\/|$)/.exec(D);if(!u?.[1])return null;try{return decodeURIComponent(u[1])}catch{return null}}function LL(D,u){let r=W7.from(D),A=W7.from(u);return r.length===A.length&&OL(r,A)}async function sD(D){return await D.json().catch(()=>({}))}function Pr(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`Missing required field: ${u}`);return D.trim()}function iu(D,u){return D.json({error:{code:"NOT_FOUND",message:`${u} not found.`}},404)}function eu(D,u){let r=D.runtimes.get(u);if(r)return r;let A=PD(u);if(!A)throw Error(`Worker not found: ${u}`);let f=D.host.createRuntimeForWorker(A);return D.runtimes.set(u,f),f}function C3(D){let u=PD(D);if(!u)throw Error(`Worker not found: ${D}`);return u}function au(D){let u=pD(D);if(!u)throw Error(`Workspace not found: ${D}`);return u}function sr(D,u){C3(D);let r=au(u);if(r.workerId!==D)throw Error(`Workspace ${u} does not belong to worker ${D}`);return r}function sA(D){let u=fu(D);if(!u)throw Error(`Session not found: ${D}`);return u}function TA(D,u){C3(D);let r=sA(u);if(r.workerId!==D)throw Error(`Session ${u} does not belong to worker ${D}`);return r}function sG(D,u,r){return D.host.requireCapabilityTemplateForWorker(u,r)}function ZG(D,u,r,A){return D.host.enrichTemplateMetadata(u,r,A)}function ku(D,u,r){let A=X0();return{appId:Pr(D.req.param("appId"),"appId"),connectorProviders:A.connectors,enabledConnectorIds:A.connectors.filter((f)=>f.enabled).map((f)=>f.id),now:u.now,operatorId:oG(D)?.operatorId??r?.operatorId??D.req.query("operatorId"),sessionId:r?.sessionId??D.req.query("sessionId"),workerId:r?.workerId??D.req.query("workerId"),workspaceId:r?.workspaceId??D.req.query("workspaceId")}}function l0(D,u,r){if(uq(r)){let A=r.decision.code==="app_not_found"?404:r.decision.code==="app_disabled"?409:403;return D.json({decision:r.decision,error:{code:r.decision.code.toUpperCase(),message:r.decision.reason}},A)}return D.json({[u]:r})}function qL(D){let u=ir(D)?D:{};return{artifactId:gu(u.artifactId),kind:gu(u.kind)??"item",reference:bL(u.reference),reviewId:gu(u.reviewId),sessionId:gu(u.sessionId),summary:gu(u.summary),title:gu(u.title)??"Untitled",workspaceId:gu(u.workspaceId)}}function bL(D){if(!ir(D))return;let u=gu(D.id),r=gu(D.type);if(!u||!r)return;let A=gu(D.url);return{id:u,type:r,...A?{url:A}:{}}}function zL(D,u){let r=D.manifest.ui.shell;return[...r?.primaryAction?[r.primaryAction]:[],...r?.actions??[],...r?.settings?[r.settings]:[]].find((f)=>f.id===u)??null}function LG(D,u,r,A,f){if(!r?.length)return null;let w=Eu(ku(D,u,f));for(let F of r){let E=TL(F);if(!E)return{allowed:!1,code:"permission_denied",reason:`Invalid required permission for ${A}: ${F}. Expected kind:action:target.`};let $=w.permissions.decide(E.kind,E.action,E.target);if(!$.allowed)return $}return null}function jL(D){if(!ir(D))return;let u={},r=gu(D.operatorId),A=gu(D.sessionId),f=gu(D.workerId),w=gu(D.workspaceId);if(r)u.operatorId=r;if(A)u.sessionId=A;if(f)u.workerId=f;if(w)u.workspaceId=w;return Object.keys(u).length>0?u:void 0}function gu(D){return typeof D==="string"&&D.length>0?D:void 0}function TL(D){let u=D.indexOf(":"),r=u>=0?D.indexOf(":",u+1):-1;if(u<=0||r<=u+1||r>=D.length-1)return null;let A=D.slice(0,u),f=D.slice(u+1,r),w=D.slice(r+1);if(!vL(A)||!sL(f))return null;return{action:f,kind:A,target:w}}function vL(D){return["api","artifact","connector","memory","review","search","storage","ui"].includes(D)}function sL(D){return["create","mount","propose","read","serve","write"].includes(D)}async function ZL(D,u,r,A,f,w){let F=await n3(D,u,r);if(F instanceof Response)return F;let E=H3(D.req.raw.headers);U3(E,D,u,r,F,void 0,w),E.set("content-type","application/json");let $=new AbortController,g=setTimeout(()=>$.abort(),Zr);try{let R=await fetch(new URL("/protocol/actions",F.baseUrl),{body:JSON.stringify({actionId:A.id,input:f,protocolAction:A.protocolAction}),headers:E,method:"POST",redirect:"manual",signal:$.signal});if(!R.ok)return D.json({error:{code:"SOUL_APP_PROTOCOL_ERROR",message:await R.text()}},502);return D.json({action:{id:A.id,protocolAction:A.protocolAction},result:await R.json()})}catch(R){let S=$.signal.aborted;return ZA(D,r,S?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",S?`Mounted Soul App service timed out after ${Zr}ms.`:R instanceof Error?R.message:String(R),S?504:502)}finally{clearTimeout(g)}}async function oL(D,u,r,A){let f=await n3(D,u,r);if(f instanceof Response)return f;let w=new URL(D.req.url),F=new URL("/protocol/search",f.baseUrl);F.searchParams.set("providerId",A.protocolProvider),F.searchParams.set("query",w.searchParams.get("query")??w.searchParams.get("q")??""),F.searchParams.set("limit",w.searchParams.get("limit")??"8");let E=H3(D.req.raw.headers);U3(E,D,u,r,f);let $=new AbortController,g=setTimeout(()=>$.abort(),Zr);try{let R=await fetch(F,{headers:E,method:"GET",redirect:"manual",signal:$.signal});if(!R.ok)return D.json({error:{code:"SOUL_APP_PROTOCOL_ERROR",message:await R.text()}},502);return D.json(await R.json())}catch(R){let S=$.signal.aborted;return ZA(D,r,S?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",S?`Mounted Soul App service timed out after ${Zr}ms.`:R instanceof Error?R.message:String(R),S?504:502)}finally{clearTimeout(g)}}async function dL(D,u,r,A){let f=xL(r,A);if(!f)return D.json({error:{code:"SOUL_APP_SURFACE_NOT_FOUND",message:`Mounted surface is not declared: ${A}`}},404);if(f.surface.renderer==="trusted-module")return D.json({error:{code:"SOUL_APP_SURFACE_RENDERER_DISABLED",message:"trusted-module surfaces require a future signed first-party module loader."}},422);let w=tL(D,u,r,f);if(!w.allowed)return G7(D,w);if(f.surface.renderer==="sandboxed-frame"){let B=new URL(D.req.url);return D.json({frame:{sandbox:"allow-scripts allow-forms",title:f.label,url:`/api/local/apps/${r.appId}${f.surface.entry}${B.search}`},surface:dG(f)})}let F=await n3(D,u,r);if(F instanceof Response)return F;let E=new URL(D.req.url),$=new URL(f.surface.entry,F.baseUrl);$.search=E.search;let g=H3(D.req.raw.headers);U3(g,D,u,r,F,f);let R=new AbortController,S=setTimeout(()=>R.abort(),Zr);try{let B=await fetch($,{headers:g,method:"GET",redirect:"manual",signal:R.signal}),J=new Headers(B.headers);if(J.delete("content-encoding"),J.delete("transfer-encoding"),f.surface.renderer==="host-descriptor"&&J.get("content-type")?.includes("application/json")){let H=await B.json();return J.set("content-type","application/json"),new Response(JSON.stringify({...H,appId:r.appId,authority:"soul-app",cache:{cachedAt:(u.now?new Date(u.now()):new Date).toISOString(),freshness:"non-authoritative"}}),{headers:J,status:B.status,statusText:B.statusText})}return new Response(B.body,{headers:J,status:B.status,statusText:B.statusText})}catch(B){let J=R.signal.aborted;return ZA(D,r,J?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",J?`Mounted Soul App service timed out after ${Zr}ms.`:B instanceof Error?B.message:String(B),J?504:502)}finally{clearTimeout(S)}}async function yL(D,u,r){let A=await n3(D,u,r);if(A instanceof Response)return A;let f=new URL(D.req.url),w=new URL(`/${D.req.param("path")}`,A.baseUrl);w.search=f.search;let F=H3(D.req.raw.headers);U3(F,D,u,r,A);let E=new AbortController,$=setTimeout(()=>E.abort(),Zr);try{let g=await fetch(w,{body:D.req.method==="GET"||D.req.method==="HEAD"?void 0:D.req.raw.body,headers:F,method:D.req.method,redirect:"manual",signal:E.signal}),R=new Headers(g.headers);return R.delete("content-encoding"),R.delete("transfer-encoding"),new Response(g.body,{headers:R,status:g.status,statusText:g.statusText})}catch(g){let R=E.signal.aborted;return D.json({error:{code:R?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",message:R?`Mounted Soul App service timed out after ${Zr}ms.`:g instanceof Error?g.message:String(g)},routePrefix:r.mountedContribution.apiRoutePrefix},R?504:502)}finally{clearTimeout($)}}function H3(D){let u=new Headers;for(let[r,A]of D){let f=r.toLowerCase();if(KL.has(f)||f.startsWith("x-forwarded-"))continue;u.set(r,A)}return u}async function n3(D,u,r){try{let A=await mL(u,r);if(A)return A;return ZA(D,r,"SOUL_APP_SERVICE_NOT_CONFIGURED",`Soul App does not declare a mounted local service: ${r.appId}`,424)}catch(A){return ZA(D,r,"SOUL_APP_SERVICE_UNREACHABLE",A instanceof Error?A.message:String(A),502)}}function ZA(D,u,r,A,f){let w=f===424?424:f===504?504:502;return D.json({error:{code:r,message:A},routePrefix:u.mountedContribution.apiRoutePrefix},w)}function U3(D,u,r,A,f,w,F){let E=new URL(u.req.url),$=`${E.protocol}//${E.host}`,g=oG(u),R=g?.operatorId??F?.operatorId??u.req.query("operatorId")??null,S=W7.from(JSON.stringify({appId:A.appId,artifactId:u.req.query("artifactId")??null,brokerGrants:A.manifest.permissions,brokerUrl:`${$}/api/local/apps/${A.appId}/broker`,expiresAt:cL(r),identity:g?lL(g):null,operatorId:R,permissions:A.manifest.permissions,reviewId:u.req.query("reviewId")??null,routePrefix:A.mountedContribution.apiRoutePrefix,sessionId:F?.sessionId??u.req.query("sessionId")??null,surface:w?dG(w):null,workerId:F?.workerId??u.req.query("workerId")??null,workspaceId:F?.workspaceId??u.req.query("workspaceId")??null})).toString("base64url"),B=ML("sha256",f.mountToken).update(S).digest("hex");D.set("x-aiworker-app-id",A.appId),D.set("x-aiworker-host-url",$),D.set("x-aiworker-mount-context",S),D.set("x-aiworker-mount-signature",B),D.set("x-aiworker-mount-token",f.mountToken),D.set("x-aiworker-route-prefix",A.mountedContribution.apiRoutePrefix??"")}function oG(D){return TG.get(D)??null}function lL(D){return{authMethod:D.authMethod,grants:D.grants,operatorId:D.operatorId,providerId:D.providerId,subject:D.subject}}function cL(D){let u=D.now?Date.parse(D.now()):Date.now();return new Date(u+300000).toISOString()}function tL(D,u,r,A){let f=A.surface.requiredPermissions?.find((w)=>w.startsWith("ui:mount:"))?.slice(9)??r.manifest.permissions.find((w)=>w.kind==="ui"&&w.action==="mount")?.target??A.id;return Eu(ku(D,u)).permissions.decide("ui","mount",f)}function G7(D,u){let r=u.code==="app_not_found"?404:u.code==="app_disabled"?409:403;return D.json({decision:u,error:{code:u.code.toUpperCase(),message:u.reason}},r)}function dG(D){return{id:D.id,kind:D.kind,label:D.label,path:D.path??null,renderer:D.surface.renderer,requiredPermissions:D.surface.requiredPermissions??[],scope:D.surface.scope,target:D.target??null}}function xL(D,u){return[...D.manifest.ui.routes.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"route",label:A.label,path:A.path,surface:A.surface})),...D.manifest.ui.panels.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"panel",label:A.label,surface:A.surface,target:A.target})),...D.manifest.ui.artifactPreviews.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"artifact-preview",label:A.label,surface:A.surface,target:A.target})),...D.manifest.ui.reviewPanels.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"review-panel",label:A.label,surface:A.surface,target:A.target})),...(D.manifest.ui.workspaceWidgets??[]).filter((A)=>A.surface).map((A)=>({id:A.id,kind:"workspace-widget",label:A.label,surface:A.surface,target:A.target}))].find((A)=>A.id===u)??null}async function mL(D,u){let r=D.mountedAppServices.get(u.appId);if(r)return r;let A=D.mountingAppServices.get(u.appId);if(A)return A;let f=pL(D,u);D.mountingAppServices.set(u.appId,f);try{return await f}finally{D.mountingAppServices.delete(u.appId)}}async function pL(D,u){let r=u.manifest.api.localService;if(!r)return null;if(r.baseUrl){if(!b2(r.baseUrl))throw Error(`Mounted Soul App service URL must be loopback HTTP: ${r.baseUrl}`);await yG(r.baseUrl,r.healthPath);let $={baseUrl:r.baseUrl,mountToken:l2()};return D.mountedAppServices.set(u.appId,$),$}if(!r.command?.length)return null;let A=eL(u),f=l2(),w=XL(r.command[0],r.command.slice(1),{cwd:A,env:{...zG.env,AIWORKER_MOUNT_TOKEN:f,PORT:"0"},stdio:["ignore","pipe","pipe"]}),E={baseUrl:await Dq(w,r.healthPath),mountToken:f,process:w};return D.mountedAppServices.set(u.appId,E),E}function aL(D,u){let r=D.mountedAppServices.get(u);if(!r)return;if(D.mountedAppServices.delete(u),r.process&&!r.process.killed)r.process.kill("SIGTERM")}function eL(D){if(D.sourceKind==="manifest-path")return Dr.dirname(D.sourceRef);return zG.cwd()}async function yG(D,u){let r=new URL(u,D),A=new AbortController,f=setTimeout(()=>A.abort(),Zr);try{let w=await fetch(r,{signal:A.signal});if(!w.ok)throw Error(`Mounted Soul App healthcheck failed ${w.status}: ${r}`)}finally{clearTimeout(f)}}async function Dq(D,u){let r=await new Promise((A,f)=>{let w="",F=setTimeout(()=>{D.kill(),f(Error("Timed out waiting for mounted Soul App service URL."))},5000);D.once("error",(E)=>{clearTimeout(F),f(E)}),D.stdout.on("data",(E)=>{w+=E.toString("utf8");let $=w.split(/\r?\n/).find((g)=>g.trim().startsWith("{"));if(!$)return;try{let g=JSON.parse($);if(typeof g.url==="string"&&g.url.length>0){if(!b2(g.url)){D.kill(),clearTimeout(F),f(Error(`Mounted Soul App service URL must be loopback HTTP: ${g.url}`));return}clearTimeout(F),A(g.url)}}catch{}}),D.stderr.on("data",(E)=>{w+=E.toString("utf8")}),D.once("exit",(E)=>{clearTimeout(F),f(Error(`Mounted Soul App service exited before readiness: ${E??"signal"}. ${w.trim()}`))})});try{await yG(r,u)}catch(A){throw D.kill(),A}return r}function uq(D){if(!ir(D)||!ir(D.decision))return!1;return D.decision.allowed===!1}function lG(D){return D.engines.find((u)=>u.id===D.engineId)}function cG(D,u){if(D.executionMode!=="local-cli")return null;return u?.path??u?.command??D.engineId}function tG(D,u){return{byok:D.byok,engineCommand:u?.command??null,engineId:D.engineId,engineName:u?.name??null,executionMode:D.executionMode}}async function W3(D,u,r,A){let f=eu(u,r.workerId),w=await sD(D.req),F=sG(u,r.workerId,w.capabilityTemplateId),E=ZG(u,r.workerId,F.id,w.metadata??{}),$=await f.createSession({workspaceId:r.id,capabilityTemplateId:F.id,title:Pr(w.title,"title"),context:w.context??"",metadata:E});if(typeof w.input!=="string"||w.input.trim().length===0)return D.json({session:$},201);let g=X0(),R=lG(g),S={engineCommand:cG(g,R),engineId:g.executionMode==="local-cli"?g.engineId:g.byok.provider,input:w.input,metadata:{...E,...tG(g,R)}};if(A)return xG(f,$,S,[{event:"session",data:$,id:$.id}]);return D.json(await f.startTurn({...S,sessionId:$.id}),201)}async function G3(D,u,r,A){let f=eu(u,r.workerId),w=await sD(D.req),F=Pr(w.input,"input"),E=X0(),$=lG(E),g={engineCommand:cG(E,$),engineId:E.executionMode==="local-cli"?E.engineId:E.byok.provider,input:F,metadata:{...ZG(u,r.workerId,r.capabilityTemplateId,r.metadataJson??{}),...w.metadata??{},...tG(E,$)}};if(A)return xG(f,r,g);return D.json(await f.startTurn({...g,sessionId:r.id}),201)}function xG(D,u,r,A=[]){let f=new TextEncoder,w=!1,F=null,E=new ReadableStream({start($){let g=()=>{if(!w)$.enqueue(f.encode(`: heartbeat
1706
+ `,K7=(D)=>{let u={...xL,...D};return async(r)=>r.html(`${cJ(u,mL)}`)};var pJ=W(()=>{tJ();xL={_integration:"hono"}});var xJ=W(()=>{pJ()});function mJ(D,u){if(D instanceof cu)return u.json(D.toJSON(),D.status);return vr.error("Unhandled error:",D),u.json({error:{code:"INTERNAL_ERROR",message:"An unexpected error occurred"}},500)}var aJ=W(()=>{s2();w3()});var eJ=async(D,u)=>{let r=performance.now();await u();let A=Math.round(performance.now()-r);vr.info(`${D.req.method} ${D.req.path} ${D.res.status} ${A}ms`)};var DG=W(()=>{w3()});var XG={};t1(XG,{createWorkerApp:()=>Eq,bootstrapWorkerApp:()=>$G});import{Buffer as N7}from"buffer";import{spawn as aL,spawnSync as eL}from"child_process";import{createHmac as Dq,randomUUID as y2,timingSafeEqual as uq}from"crypto";import{mkdir as rq,readFile as AG,stat as Aq}from"fs/promises";import rr from"path";import fG from"process";import{fileURLToPath as fq}from"url";async function $G(D={}){let u=D.dbPath??U2.WORKER_DB_PATH;await rq(rr.dirname(u),{recursive:!0}),r2(),WA(u),JA(D.migrationsFolder??U2.WORKER_MIGRATIONS_FOLDER);let r=D.runtimeVersion??Fq,A=D.workersRoot??rr.join(rr.dirname(u),"workers"),f=new Map,w=M1({executor:D.executor,now:D.now,officialAppsRoot:D.officialAppsRoot,registryContext:()=>{let $=i0();return{availableConnectorIds:$.connectors.map((g)=>g.id),enabledConnectorIds:$.connectors.filter((g)=>g.enabled).map((g)=>g.id),hostVersion:r}},workersRoot:A}),F={authProvider:tF({token:D.token??U2.AIWORKER_LOCAL_TOKEN}),host:w,mountingAppServices:new Map,mountedAppServices:new Map,runtimes:f,startedAt:new Date().toISOString(),runtimeVersion:r,now:D.now};await F.host.bootstrapOfficialSoulApps();for(let $ of gr()){let g=F.host.createRuntimeForWorker($);await g.init(),f.set($.id,g)}let E=new sJ;return E.use(eJ),E.onError(mJ),E.use("/api/local/*",async($,g)=>{if(gq($,F))return g();let _=F.authProvider.authenticate({authorization:$.req.header("authorization")});if(_.status==="denied")return $.json({error:{code:"UNAUTHORIZED",message:_.reason}},401);if(_.status==="authenticated")wG.set($,_.identity);return g()}),E.get("/health",($)=>$.json({mode:"soul-workspace",status:"ok",workers:gr().map((g)=>({id:g.id,soulId:g.soulId,status:g.status})),runtimeVersion:F.runtimeVersion,startedAt:F.startedAt,checkedAt:new Date().toISOString()})),E.get("/api/local/info",($)=>$.json({runtimeVersion:F.runtimeVersion,startedAt:F.startedAt,workers:gr()})),E.get("/api/local/apps",($)=>$.json({apps:F.host.listApps()})),E.post("/api/local/apps/install",async($)=>{let g=await oD($.req),_=typeof g.manifestPath==="string"&&g.manifestPath.trim()?await F.host.installAppFromPath(g.manifestPath):F.host.installAppManifest({manifest:g.manifest,sourceKind:"inline",sourceRef:"api:inline"});return $.json({app:_,catalog:F.host.listCatalog()},201)}),E.get("/api/local/apps/:appId",($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return ku($,"Soul App");return $.json({app:g})}),E.get("/api/local/apps/:appId/security-review",($)=>{let g=$.req.param("appId");if(!F.host.getApp(g))return ku($,"Soul App");return $.json({review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/enable",($)=>{let g=$.req.param("appId"),_=F.host.enableApp(g);return $.json({app:_,catalog:F.host.listCatalog(),review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/disable",($)=>{let g=$.req.param("appId"),_=F.host.disableApp(g);return Vq(F,g),$.json({app:_,catalog:F.host.listCatalog(),review:F.host.reviewAppSecurity(g)})}),E.post("/api/local/apps/:appId/healthcheck",($)=>$.json({app:F.host.healthcheckApp($.req.param("appId"))})),E.get("/api/local/apps/:appId/broker/permissions",($)=>{let g=Su(Iu($,F));return $.json({permissions:g.permissions.list()})}),E.get("/api/local/apps/:appId/broker/providers",($)=>{let g=Su(Iu($,F));return $.json({registry:g.providers.list()})}),E.get("/api/local/apps/:appId/broker/search",($)=>{let g=Su(Iu($,F)).search.query($.req.query("query")??"");return c0($,"result",g)}),E.put("/api/local/apps/:appId/broker/search/:itemId{.+}",async($)=>{let g=await $.req.json().catch(()=>({})),_=Su(Iu($,F)).search.upsert($.req.param("itemId"),Rq(g));return c0($,"item",_)}),E.get("/api/local/apps/:appId/broker/storage",($)=>{let g=Su(Iu($,F)).storage.list();return c0($,"records",g)}),E.get("/api/local/apps/:appId/broker/storage/:key{.+}",($)=>{let g=Su(Iu($,F)).storage.get($.req.param("key"));return c0($,"record",g)}),E.put("/api/local/apps/:appId/broker/storage/:key{.+}",async($)=>{let g=await oD($.req),_=Su(Iu($,F)).storage.put($.req.param("key"),kr(g.valueJson)?g.valueJson:{},{namespace:g.namespace});return c0($,"record",_)}),E.post("/api/local/apps/:appId/broker/connectors/:connectorId/evidence",async($)=>{let g=await oD($.req),_=Su(Iu($,F)).connectors.readEvidence($.req.param("connectorId"),kr(g.query)?g.query:{});return c0($,"evidence",_)}),E.get("/api/local/apps/:appId/broker/audit",($)=>{let g=Su(Iu($,F));return $.json({events:g.audit.list()})}),E.post("/api/local/apps/:appId/broker/engine/invocations",async($)=>{let g=await oD($.req),_=Su(Iu($,F)).engine.createInvocation({prompt:g.prompt??""});return c0($,"invocation",_)}),E.post("/api/local/apps/:appId/actions/:actionId",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return $.json({error:{code:"SOUL_APP_NOT_FOUND",message:`Soul App was not found: ${$.req.param("appId")}`}},404);if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);let _=Bq(g,$.req.param("actionId"));if(!_)return $.json({error:{code:"SOUL_APP_ACTION_NOT_DECLARED",message:`Soul App action is not declared: ${$.req.param("actionId")}`}},404);let R=await oD($.req),n=Wq(R.scope),B=uG($,F,_.requiredPermissions,`action ${_.id}`,n);if(B)return Q7($,B);return Hq($,F,g,_,kr(R.input)?R.input:{},n)}),E.get("/api/local/apps/:appId/search",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return $.json({error:{code:"SOUL_APP_NOT_FOUND",message:`Soul App was not found: ${$.req.param("appId")}`}},404);if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);let _=$.req.query("providerId")??"",R=g.manifest.ui.shell?.search;if(!R||R.protocolProvider!==_)return $.json({error:{code:"SOUL_APP_SEARCH_NOT_DECLARED",message:`Soul App search provider is not declared: ${_}`}},404);let n=uG($,F,R.requiredPermissions,`search ${R.id}`);if(n)return Q7($,n);return Xq($,F,g,R)}),E.get("/api/local/apps/:appId/surfaces/:surfaceId",async($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return ku($,"Soul App");if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);return iq($,F,g,$.req.param("surfaceId"))}),E.get("/api/local/workers",($)=>$.json({workers:gr()})),E.post("/api/local/workers",async($)=>{let g=await oD($.req),_=await F.host.createSoulWorker({defaultEngineId:g.defaultEngineId,id:g.id,metadata:g.metadata,name:Pr(g.name,"name"),soulId:Pr(g.soulId,"soulId")});return F.runtimes.set(_.worker.id,_.runtime),$.json({worker:_.worker,snapshot:_.snapshot},201)}),E.get("/api/local/workers/:workerId",($)=>{let g=PD($.req.param("workerId"));if(!g)return ku($,"worker");return $.json({worker:g,snapshot:ur(F,g.id).snapshot()})}),E.patch("/api/local/workers/:workerId",async($)=>{let g=PD($.req.param("workerId"));if(!g)return ku($,"worker");let _=await oD($.req),R=A2({id:g.id,soulId:g.soulId,name:_.name??g.name,status:_.status??g.status,defaultEngineId:_.defaultEngineId??g.defaultEngineId,metadataJson:_.metadata??g.metadataJson}),n=F.host.createRuntimeForWorker(R);return await n.init(),F.runtimes.set(R.id,n),$.json({worker:R,snapshot:n.snapshot()})}),E.get("/api/local/souls",($)=>$.json({souls:F.host.listSouls()})),E.get("/api/local/souls/:id",($)=>{let g=F.host.findSoul($.req.param("id"));if(!g)return ku($,"soul");return $.json({soul:g})}),E.get("/api/local/templates",($)=>{let g=$.req.query("soulId"),_=F.host.listCapabilityTemplates(g);return $.json({templates:_})}),E.get("/api/local/templates/:id",($)=>{let g=F.host.listCatalog().templates.find((_)=>_.id===$.req.param("id"));if(!g)return ku($,"template");return $.json({template:g})}),E.get("/api/local/workers/:workerId/templates",($)=>{return $.json({templates:F.host.listCapabilityTemplatesForWorker($.req.param("workerId"))})}),E.get("/api/local/workers/:workerId/templates/:templateId",($)=>{let g=EG(F,$.req.param("workerId"),$.req.param("templateId"));return $.json({template:g})}),E.get("/api/local/workspaces",($)=>$.json({workspaces:Xu()})),E.get("/api/local/workers/:workerId/workspaces",($)=>{let g=$.req.param("workerId");return ur(F,g),$.json({workspaces:Xu(g)})}),E.post("/api/local/workers/:workerId/workspaces",async($)=>{let g=ur(F,$.req.param("workerId")),_=await oD($.req),R=await g.createWorkspace({name:Pr(_.name,"name"),type:_.type??"workspace",sourcePointers:_.sourcePointers??[],metadata:_.metadata??{}});return $.json({workspace:R},201)}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId",($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({workspace:g})}),E.patch("/api/local/workers/:workerId/workspaces/:workspaceId",async($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId")),_=await oD($.req);return $.json({workspace:sF({id:g.id,..._})})}),E.get("/api/local/workspaces/:workspaceId",($)=>{let g=Du($.req.param("workspaceId"));if(!g)return ku($,"workspace");return $.json({workspace:g})}),E.patch("/api/local/workspaces/:workspaceId",async($)=>{let g=await oD($.req);return $.json({workspace:sF({id:$.req.param("workspaceId"),...g})})}),E.get("/api/local/workspaces/:workspaceId/profile",async($)=>{let g=Dr($.req.param("workspaceId"));return $.text(await ur(F,g.workerId).files(g.id).read("README.md"))}),E.post("/api/local/workspaces/:workspaceId/profile-revisions",async($)=>{let g=Dr($.req.param("workspaceId")),_=await oD($.req),R=_.verdict??"pass";if(R!=="pass"&&R!=="warn")return $.json({error:{code:"PROFILE_REVISION_NOT_APPROVED",message:"Only pass or warn reviews can promote a profile revision."}},400);let n=await ur(F,g.workerId).promoteProfileRevision({artifactId:Pr(_.artifactId,"artifactId"),findingsJson:_.findingsJson??[],profileMarkdown:_.profileMarkdown,risksJson:_.risksJson??[],tagName:_.tagName,verdict:R,workspaceId:g.id});return $.json({profileRevision:n},201)}),E.get("/api/local/sessions",($)=>$.json({sessions:tr()})),E.get("/api/local/turns",($)=>$.json({turns:Sr()})),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/sessions",($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({sessions:tr(g.id)})}),E.post("/api/local/workers/:workerId/workspaces/:workspaceId/sessions",async($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return i3($,F,g,!1)}),E.post("/api/local/workers/:workerId/workspaces/:workspaceId/sessions/stream",async($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return i3($,F,g,!0)}),E.get("/api/local/workspaces/:workspaceId/sessions",($)=>{let g=Dr($.req.param("workspaceId"));return $.json({sessions:tr(g.id)})}),E.post("/api/local/workspaces/:workspaceId/sessions",async($)=>{let g=Dr($.req.param("workspaceId"));return i3($,F,g,!1)}),E.post("/api/local/workspaces/:workspaceId/sessions/stream",async($)=>{let g=Dr($.req.param("workspaceId"));return i3($,F,g,!0)}),E.get("/api/local/sessions/:sessionId",($)=>{let g=wu($.req.param("sessionId"));if(!g)return ku($,"session");return $.json({session:g,turns:Sr(g.id),events:_r(g.id)})}),E.get("/api/local/workers/:workerId/sessions/:sessionId",($)=>{let g=Z1($.req.param("workerId"),$.req.param("sessionId"));return $.json({session:g,turns:Sr(g.id),events:_r(g.id)})}),E.get("/api/local/workers/:workerId/sessions/:sessionId/events",($)=>{let g=Z1($.req.param("workerId"),$.req.param("sessionId")),_=Number($.req.query("after")??$.req.header("last-event-id")??0),R=_r(g.id).filter((n)=>!Number.isFinite(_)||n.id>_);return $.json({events:R})}),E.get("/api/local/workers/:workerId/sessions/:sessionId/turns",($)=>{let g=Z1($.req.param("workerId"),$.req.param("sessionId"));return $.json({turns:Sr(g.id)})}),E.post("/api/local/workers/:workerId/sessions/:sessionId/messages",async($)=>{let g=Z1($.req.param("workerId"),$.req.param("sessionId"));return U3($,F,g,!1)}),E.post("/api/local/workers/:workerId/sessions/:sessionId/messages/stream",async($)=>{let g=Z1($.req.param("workerId"),$.req.param("sessionId"));return U3($,F,g,!0)}),E.get("/api/local/sessions/:sessionId/events",($)=>{let g=d1($.req.param("sessionId")),_=Number($.req.query("after")??$.req.header("last-event-id")??0),R=_r(g.id).filter((n)=>!Number.isFinite(_)||n.id>_);return $.json({events:R})}),E.get("/api/local/sessions/:sessionId/turns",($)=>{let g=d1($.req.param("sessionId"));return $.json({turns:Sr(g.id)})}),E.post("/api/local/sessions/:sessionId/turns/stream",async($)=>{let g=d1($.req.param("sessionId"));return U3($,F,g,!0)}),E.post("/api/local/sessions/:sessionId/turns",async($)=>{let g=d1($.req.param("sessionId"));return U3($,F,g,!1)}),E.get("/api/local/files",($)=>$.json({files:zu()})),E.get("/api/local/workers/:workerId/files",($)=>{let g=Y3($.req.param("workerId")),_=new Set(Xu(g.id).map((R)=>R.id));return $.json({files:zu().filter((R)=>_.has(R.workspaceId))})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files",($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return $.json({files:zu(g.id)})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files/search",($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId")),_=$.req.query("q")?.toLowerCase()??"",R=zu(g.id).filter((n)=>n.path.toLowerCase().includes(_));return $.json({files:R})}),E.get("/api/local/workers/:workerId/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId"));return $.text(await ur(F,g.workerId).files(g.id).read($.req.param("path")))}),E.put("/api/local/workers/:workerId/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=Zr($.req.param("workerId"),$.req.param("workspaceId")),_=$.req.param("path"),R=await ur(F,g.workerId).files(g.id).write({path:_,content:await $.req.text()}),n=GA({id:y2(),workspaceId:g.id,path:_,kind:R.kind,size:R.size,mtime:R.mtime,hash:R.hash,source:"user"});return $.json({file:n})}),E.get("/api/local/workspaces/:workspaceId/files",($)=>{let g=Dr($.req.param("workspaceId"));return $.json({files:zu(g.id)})}),E.get("/api/local/workspaces/:workspaceId/files/search",($)=>{let g=Dr($.req.param("workspaceId")),_=$.req.query("q")?.toLowerCase()??"",R=zu(g.id).filter((n)=>n.path.toLowerCase().includes(_));return $.json({files:R})}),E.get("/api/local/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=Dr($.req.param("workspaceId"));return $.text(await ur(F,g.workerId).files(g.id).read($.req.param("path")))}),E.put("/api/local/workspaces/:workspaceId/files/raw/:path{.+}",async($)=>{let g=Dr($.req.param("workspaceId")),_=$.req.param("path"),R=await ur(F,g.workerId).files(g.id).write({path:_,content:await $.req.text()}),n=GA({id:y2(),workspaceId:g.id,path:_,kind:R.kind,size:R.size,mtime:R.mtime,hash:R.hash,source:"user"});return $.json({file:n})}),E.get("/api/local/artifacts",($)=>$.json({artifacts:Rr()})),E.get("/api/local/workers/:workerId/artifacts",($)=>{let g=Y3($.req.param("workerId")),_=new Set(Xu(g.id).map((R)=>R.id));return $.json({artifacts:Rr().filter((R)=>_.has(R.workspaceId))})}),E.get("/api/local/workspaces/:workspaceId/artifacts",($)=>{let g=Dr($.req.param("workspaceId"));return $.json({artifacts:Rr(g.id)})}),E.get("/api/local/artifacts/:id",($)=>{let g=pr($.req.param("id"));if(!g)return ku($,"artifact");return $.json({artifact:g})}),E.get("/api/local/reviews",($)=>$.json({reviews:f2()})),E.post("/api/local/reviews",async($)=>{let g=await oD($.req),_=Pr(g.workspaceId,"workspaceId"),R=P0({id:y2(),workspaceId:_,sessionId:g.sessionId??null,turnId:g.turnId??null,artifactId:g.artifactId??null,verdict:g.verdict??"needs_review",findingsJson:g.findingsJson??[],risksJson:g.risksJson??[]});return $.json({review:R},201)}),E.get("/api/local/reviews/:id",($)=>{let g=CA($.req.param("id"));if(!g)return ku($,"review");return $.json({review:g})}),E.get("/api/local/lessons",($)=>$.json({lessons:F2()})),E.post("/api/local/lessons",async($)=>{let g=await oD($.req),_=xr({id:y2(),workspaceId:Pr(g.workspaceId,"workspaceId"),sourceReviewId:g.sourceReviewId??null,statement:Pr(g.statement,"statement"),evidenceJson:Array.isArray(g.evidenceJson)?g.evidenceJson:[]});return $.json({lesson:_},201)}),E.patch("/api/local/lessons/:id",async($)=>{let g=await oD($.req);return $.json({lesson:HA($.req.param("id"),g.status)})}),E.get("/api/local/settings",($)=>{let g=i0();return $.json({settings:g})}),E.patch("/api/local/settings",async($)=>{let g=await oD($.req),_=i0(),R=L7({..._,...g,byok:{..._.byok,...g.byok??{}},updatedAt:new Date().toISOString()});return $.json({settings:R})}),E.post("/api/local/settings/engines/rescan",($)=>{let g=i0(),_=L7({...g,engines:GG(),updatedAt:new Date().toISOString()});return $.json({engines:_.engines,settings:_})}),E.post("/api/local/settings/engines/test",async($)=>{let g=await oD($.req),_=i0(),R=g.engineId??_.engineId,n=_.engines.find((B)=>B.id===R);if(!n)return $.json({result:{engineId:R,message:"Engine is not known in local settings.",status:"fail"}},404);if(!n.installed)return $.json({result:{engineId:R,message:`${n.name} is not installed on PATH.`,status:"fail"}});return $.json({result:{engineId:R,message:`${n.name} responded as ${n.version??n.path}.`,status:"pass"}})}),E.get("/api/local/events",($)=>$.json({events:_r()})),E.all("/api/local/apps/:appId/:path{.+}",($)=>{let g=F.host.getApp($.req.param("appId"));if(!g)return ku($,"Soul App");if(g.status!=="enabled")return $.json({error:{code:"SOUL_APP_DISABLED",message:`Soul App is not enabled: ${g.appId}`}},409);return Uq($,F,g)}),qq(E),E.doc("/openapi.json",{openapi:"3.1.0",info:{title:"AIWorker Local Daemon API",version:r,description:"Vertical Soul workspace API for Soul workers, workspaces, sessions, turns, artifacts, reviews, memory candidates, and settings."}}),E.get("/docs",K7({spec:{url:"/openapi.json"}})),E.get("/",async($)=>h7($,D.webStaticDir)),E.get("/workers/:path{.+}",async($)=>h7($,D.webStaticDir)),E.get("/workspaces/:path{.+}",async($)=>h7($,D.webStaticDir)),E.get("/favicon.svg",async($)=>o1($,D.webStaticDir,"favicon.svg")),E.get("/logo.svg",async($)=>o1($,D.webStaticDir,"logo.svg")),E.get("/assets/:path{.+}",async($)=>o1($,D.webStaticDir,`assets/${$.req.param("path")}`)),E.get("/fonts/:path{.+}",async($)=>o1($,D.webStaticDir,`fonts/${$.req.param("path")}`)),E.get("/engine-icons/:path{.+}",async($)=>o1($,D.webStaticDir,`engine-icons/${$.req.param("path")}`)),{app:E,port:U2.PORT,state:F}}async function Eq(){let{app:D,port:u}=await $G();return{app:D,port:u}}function gq(D,u){let r=Sq(new URL(D.req.url).pathname);if(!r)return!1;let A=D.req.header("x-aiworker-mount-token");if(!A)return!1;let f=u.mountedAppServices.get(r);return f?_q(A,f.mountToken):!1}function Sq(D){let u=/^\/api\/local\/apps\/([^/]+)\/broker(?:\/|$)/.exec(D);if(!u?.[1])return null;try{return decodeURIComponent(u[1])}catch{return null}}function _q(D,u){let r=N7.from(D),A=N7.from(u);return r.length===A.length&&uq(r,A)}async function oD(D){return await D.json().catch(()=>({}))}function Pr(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`Missing required field: ${u}`);return D.trim()}function ku(D,u){return D.json({error:{code:"NOT_FOUND",message:`${u} not found.`}},404)}function ur(D,u){let r=D.runtimes.get(u);if(r)return r;let A=PD(u);if(!A)throw Error(`Worker not found: ${u}`);let f=D.host.createRuntimeForWorker(A);return D.runtimes.set(u,f),f}function Y3(D){let u=PD(D);if(!u)throw Error(`Worker not found: ${D}`);return u}function Dr(D){let u=Du(D);if(!u)throw Error(`Workspace not found: ${D}`);return u}function Zr(D,u){Y3(D);let r=Dr(u);if(r.workerId!==D)throw Error(`Workspace ${u} does not belong to worker ${D}`);return r}function d1(D){let u=wu(D);if(!u)throw Error(`Session not found: ${D}`);return u}function Z1(D,u){Y3(D);let r=d1(u);if(r.workerId!==D)throw Error(`Session ${u} does not belong to worker ${D}`);return r}function EG(D,u,r){return D.host.requireCapabilityTemplateForWorker(u,r)}function gG(D,u,r,A){return D.host.enrichTemplateMetadata(u,r,A)}function Iu(D,u,r){let A=i0();return{appId:Pr(D.req.param("appId"),"appId"),connectorProviders:A.connectors,enabledConnectorIds:A.connectors.filter((f)=>f.enabled).map((f)=>f.id),now:u.now,operatorId:SG(D)?.operatorId??r?.operatorId??D.req.query("operatorId"),sessionId:r?.sessionId??D.req.query("sessionId"),workerId:r?.workerId??D.req.query("workerId"),workspaceId:r?.workspaceId??D.req.query("workspaceId")}}function c0(D,u,r){if(Nq(r)){let A=r.decision.code==="app_not_found"?404:r.decision.code==="app_disabled"?409:403;return D.json({decision:r.decision,error:{code:r.decision.code.toUpperCase(),message:r.decision.reason}},A)}return D.json({[u]:r})}function Rq(D){let u=kr(D)?D:{};return{artifactId:_u(u.artifactId),kind:_u(u.kind)??"item",reference:nq(u.reference),reviewId:_u(u.reviewId),sessionId:_u(u.sessionId),summary:_u(u.summary),title:_u(u.title)??"Untitled",workspaceId:_u(u.workspaceId)}}function nq(D){if(!kr(D))return;let u=_u(D.id),r=_u(D.type);if(!u||!r)return;let A=_u(D.url);return{id:u,type:r,...A?{url:A}:{}}}function Bq(D,u){let r=D.manifest.ui.shell;return[...r?.primaryAction?[r.primaryAction]:[],...r?.actions??[],...r?.settings?[r.settings]:[]].find((f)=>f.id===u)??null}function uG(D,u,r,A,f){if(!r?.length)return null;let w=Su(Iu(D,u,f));for(let F of r){let E=Jq(F);if(!E)return{allowed:!1,code:"permission_denied",reason:`Invalid required permission for ${A}: ${F}. Expected kind:action:target.`};let $=w.permissions.decide(E.kind,E.action,E.target);if(!$.allowed)return $}return null}function Wq(D){if(!kr(D))return;let u={},r=_u(D.operatorId),A=_u(D.sessionId),f=_u(D.workerId),w=_u(D.workspaceId);if(r)u.operatorId=r;if(A)u.sessionId=A;if(f)u.workerId=f;if(w)u.workspaceId=w;return Object.keys(u).length>0?u:void 0}function _u(D){return typeof D==="string"&&D.length>0?D:void 0}function Jq(D){let u=D.indexOf(":"),r=u>=0?D.indexOf(":",u+1):-1;if(u<=0||r<=u+1||r>=D.length-1)return null;let A=D.slice(0,u),f=D.slice(u+1,r),w=D.slice(r+1);if(!Gq(A)||!Cq(f))return null;return{action:f,kind:A,target:w}}function Gq(D){return["api","artifact","connector","memory","review","search","storage","ui"].includes(D)}function Cq(D){return["create","mount","propose","read","serve","write"].includes(D)}async function Hq(D,u,r,A,f,w){let F=await O3(D,u,r);if(F instanceof Response)return F;let E=M3(D.req.raw.headers);P3(E,D,u,r,F,void 0,w),E.set("content-type","application/json");let $=new AbortController,g=setTimeout(()=>$.abort(),or);try{let _=await fetch(new URL("/protocol/actions",F.baseUrl),{body:JSON.stringify({actionId:A.id,input:f,protocolAction:A.protocolAction}),headers:E,method:"POST",redirect:"manual",signal:$.signal});if(!_.ok)return D.json({error:{code:"SOUL_APP_PROTOCOL_ERROR",message:await _.text()}},502);return D.json({action:{id:A.id,protocolAction:A.protocolAction},result:await _.json()})}catch(_){let R=$.signal.aborted;return l1(D,r,R?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",R?`Mounted Soul App service timed out after ${or}ms.`:_ instanceof Error?_.message:String(_),R?504:502)}finally{clearTimeout(g)}}async function Xq(D,u,r,A){let f=await O3(D,u,r);if(f instanceof Response)return f;let w=new URL(D.req.url),F=new URL("/protocol/search",f.baseUrl);F.searchParams.set("providerId",A.protocolProvider),F.searchParams.set("query",w.searchParams.get("query")??w.searchParams.get("q")??""),F.searchParams.set("limit",w.searchParams.get("limit")??"8");let E=M3(D.req.raw.headers);P3(E,D,u,r,f);let $=new AbortController,g=setTimeout(()=>$.abort(),or);try{let _=await fetch(F,{headers:E,method:"GET",redirect:"manual",signal:$.signal});if(!_.ok)return D.json({error:{code:"SOUL_APP_PROTOCOL_ERROR",message:await _.text()}},502);return D.json(await _.json())}catch(_){let R=$.signal.aborted;return l1(D,r,R?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",R?`Mounted Soul App service timed out after ${or}ms.`:_ instanceof Error?_.message:String(_),R?504:502)}finally{clearTimeout(g)}}async function iq(D,u,r,A){let f=Pq(r,A);if(!f)return D.json({error:{code:"SOUL_APP_SURFACE_NOT_FOUND",message:`Mounted surface is not declared: ${A}`}},404);if(f.surface.renderer==="trusted-module")return D.json({error:{code:"SOUL_APP_SURFACE_RENDERER_DISABLED",message:"trusted-module surfaces require a future signed first-party module loader."}},422);let w=Oq(D,u,r,f);if(!w.allowed)return Q7(D,w);if(f.surface.renderer==="sandboxed-frame"){let n=new URL(D.req.url);return D.json({frame:{sandbox:"allow-scripts allow-forms",title:f.label,url:`/api/local/apps/${r.appId}${f.surface.entry}${n.search}`},surface:_G(f)})}let F=await O3(D,u,r);if(F instanceof Response)return F;let E=new URL(D.req.url),$=new URL(f.surface.entry,F.baseUrl);$.search=E.search;let g=M3(D.req.raw.headers);P3(g,D,u,r,F,f);let _=new AbortController,R=setTimeout(()=>_.abort(),or);try{let n=await fetch($,{headers:g,method:"GET",redirect:"manual",signal:_.signal}),B=new Headers(n.headers);if(B.delete("content-encoding"),B.delete("transfer-encoding"),f.surface.renderer==="host-descriptor"&&B.get("content-type")?.includes("application/json")){let C=await n.json();return B.set("content-type","application/json"),new Response(JSON.stringify({...C,appId:r.appId,authority:"soul-app",cache:{cachedAt:(u.now?new Date(u.now()):new Date).toISOString(),freshness:"non-authoritative"}}),{headers:B,status:n.status,statusText:n.statusText})}return new Response(n.body,{headers:B,status:n.status,statusText:n.statusText})}catch(n){let B=_.signal.aborted;return l1(D,r,B?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",B?`Mounted Soul App service timed out after ${or}ms.`:n instanceof Error?n.message:String(n),B?504:502)}finally{clearTimeout(R)}}async function Uq(D,u,r){let A=await O3(D,u,r);if(A instanceof Response)return A;let f=new URL(D.req.url),w=new URL(`/${D.req.param("path")}`,A.baseUrl);w.search=f.search;let F=M3(D.req.raw.headers);P3(F,D,u,r,A);let E=new AbortController,$=setTimeout(()=>E.abort(),or);try{let g=await fetch(w,{body:D.req.method==="GET"||D.req.method==="HEAD"?void 0:D.req.raw.body,headers:F,method:D.req.method,redirect:"manual",signal:E.signal}),_=new Headers(g.headers);return _.delete("content-encoding"),_.delete("transfer-encoding"),new Response(g.body,{headers:_,status:g.status,statusText:g.statusText})}catch(g){let _=E.signal.aborted;return D.json({error:{code:_?"SOUL_APP_SERVICE_TIMEOUT":"SOUL_APP_SERVICE_UNREACHABLE",message:_?`Mounted Soul App service timed out after ${or}ms.`:g instanceof Error?g.message:String(g)},routePrefix:r.mountedContribution.apiRoutePrefix},_?504:502)}finally{clearTimeout($)}}function M3(D){let u=new Headers;for(let[r,A]of D){let f=r.toLowerCase();if($q.has(f)||f.startsWith("x-forwarded-"))continue;u.set(r,A)}return u}async function O3(D,u,r){try{let A=await kq(u,r);if(A)return A;return l1(D,r,"SOUL_APP_SERVICE_NOT_CONFIGURED",`Soul App does not declare a mounted local service: ${r.appId}`,424)}catch(A){return l1(D,r,"SOUL_APP_SERVICE_UNREACHABLE",A instanceof Error?A.message:String(A),502)}}function l1(D,u,r,A,f){let w=f===424?424:f===504?504:502;return D.json({error:{code:r,message:A},routePrefix:u.mountedContribution.apiRoutePrefix},w)}function P3(D,u,r,A,f,w,F){let E=new URL(u.req.url),$=`${E.protocol}//${E.host}`,g=SG(u),_=g?.operatorId??F?.operatorId??u.req.query("operatorId")??null,R=N7.from(JSON.stringify({appId:A.appId,artifactId:u.req.query("artifactId")??null,brokerGrants:A.manifest.permissions,brokerUrl:`${$}/api/local/apps/${A.appId}/broker`,expiresAt:Mq(r),identity:g?Yq(g):null,operatorId:_,permissions:A.manifest.permissions,reviewId:u.req.query("reviewId")??null,routePrefix:A.mountedContribution.apiRoutePrefix,sessionId:F?.sessionId??u.req.query("sessionId")??null,surface:w?_G(w):null,workerId:F?.workerId??u.req.query("workerId")??null,workspaceId:F?.workspaceId??u.req.query("workspaceId")??null})).toString("base64url"),n=Dq("sha256",f.mountToken).update(R).digest("hex");D.set("x-aiworker-app-id",A.appId),D.set("x-aiworker-host-url",$),D.set("x-aiworker-mount-context",R),D.set("x-aiworker-mount-signature",n),D.set("x-aiworker-mount-token",f.mountToken),D.set("x-aiworker-route-prefix",A.mountedContribution.apiRoutePrefix??"")}function SG(D){return wG.get(D)??null}function Yq(D){return{authMethod:D.authMethod,grants:D.grants,operatorId:D.operatorId,providerId:D.providerId,subject:D.subject}}function Mq(D){let u=D.now?Date.parse(D.now()):Date.now();return new Date(u+300000).toISOString()}function Oq(D,u,r,A){let f=A.surface.requiredPermissions?.find((w)=>w.startsWith("ui:mount:"))?.slice(9)??r.manifest.permissions.find((w)=>w.kind==="ui"&&w.action==="mount")?.target??A.id;return Su(Iu(D,u)).permissions.decide("ui","mount",f)}function Q7(D,u){let r=u.code==="app_not_found"?404:u.code==="app_disabled"?409:403;return D.json({decision:u,error:{code:u.code.toUpperCase(),message:u.reason}},r)}function _G(D){return{id:D.id,kind:D.kind,label:D.label,path:D.path??null,renderer:D.surface.renderer,requiredPermissions:D.surface.requiredPermissions??[],scope:D.surface.scope,target:D.target??null}}function Pq(D,u){return[...D.manifest.ui.routes.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"route",label:A.label,path:A.path,surface:A.surface})),...D.manifest.ui.panels.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"panel",label:A.label,surface:A.surface,target:A.target})),...D.manifest.ui.artifactPreviews.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"artifact-preview",label:A.label,surface:A.surface,target:A.target})),...D.manifest.ui.reviewPanels.filter((A)=>A.surface).map((A)=>({id:A.id,kind:"review-panel",label:A.label,surface:A.surface,target:A.target})),...(D.manifest.ui.workspaceWidgets??[]).filter((A)=>A.surface).map((A)=>({id:A.id,kind:"workspace-widget",label:A.label,surface:A.surface,target:A.target}))].find((A)=>A.id===u)??null}async function kq(D,u){let r=D.mountedAppServices.get(u.appId);if(r)return r;let A=D.mountingAppServices.get(u.appId);if(A)return A;let f=Iq(D,u);D.mountingAppServices.set(u.appId,f);try{return await f}finally{D.mountingAppServices.delete(u.appId)}}async function Iq(D,u){let r=u.manifest.api.localService;if(!r)return null;if(r.baseUrl){if(!b2(r.baseUrl))throw Error(`Mounted Soul App service URL must be loopback HTTP: ${r.baseUrl}`);await RG(r.baseUrl,r.healthPath);let $={baseUrl:r.baseUrl,mountToken:y2()};return D.mountedAppServices.set(u.appId,$),$}if(!r.command?.length)return null;let A=Kq(u),f=y2(),w=aL(r.command[0],r.command.slice(1),{cwd:A,env:{...fG.env,AIWORKER_MOUNT_TOKEN:f,PORT:"0"},stdio:["ignore","pipe","pipe"]}),E={baseUrl:await hq(w,r.healthPath),mountToken:f,process:w};return D.mountedAppServices.set(u.appId,E),E}function Vq(D,u){let r=D.mountedAppServices.get(u);if(!r)return;if(D.mountedAppServices.delete(u),r.process&&!r.process.killed)r.process.kill("SIGTERM")}function Kq(D){if(D.sourceKind==="manifest-path")return rr.dirname(D.sourceRef);return fG.cwd()}async function RG(D,u){let r=new URL(u,D),A=new AbortController,f=setTimeout(()=>A.abort(),or);try{let w=await fetch(r,{signal:A.signal});if(!w.ok)throw Error(`Mounted Soul App healthcheck failed ${w.status}: ${r}`)}finally{clearTimeout(f)}}async function hq(D,u){let r=await new Promise((A,f)=>{let w="",F=setTimeout(()=>{D.kill(),f(Error("Timed out waiting for mounted Soul App service URL."))},5000);D.once("error",(E)=>{clearTimeout(F),f(E)}),D.stdout.on("data",(E)=>{w+=E.toString("utf8");let $=w.split(/\r?\n/).find((g)=>g.trim().startsWith("{"));if(!$)return;try{let g=JSON.parse($);if(typeof g.url==="string"&&g.url.length>0){if(!b2(g.url)){D.kill(),clearTimeout(F),f(Error(`Mounted Soul App service URL must be loopback HTTP: ${g.url}`));return}clearTimeout(F),A(g.url)}}catch{}}),D.stderr.on("data",(E)=>{w+=E.toString("utf8")}),D.once("exit",(E)=>{clearTimeout(F),f(Error(`Mounted Soul App service exited before readiness: ${E??"signal"}. ${w.trim()}`))})});try{await RG(r,u)}catch(A){throw D.kill(),A}return r}function Nq(D){if(!kr(D)||!kr(D.decision))return!1;return D.decision.allowed===!1}function nG(D){return D.engines.find((u)=>u.id===D.engineId)}function BG(D,u){if(D.executionMode!=="local-cli")return null;return u?.path??u?.command??D.engineId}function WG(D,u){return{byok:D.byok,engineCommand:u?.command??null,engineId:D.engineId,engineName:u?.name??null,executionMode:D.executionMode}}async function i3(D,u,r,A){let f=ur(u,r.workerId),w=await oD(D.req),F=EG(u,r.workerId,w.capabilityTemplateId),E=gG(u,r.workerId,F.id,w.metadata??{}),$=await f.createSession({workspaceId:r.id,capabilityTemplateId:F.id,title:Pr(w.title,"title"),context:w.context??"",metadata:E});if(typeof w.input!=="string"||w.input.trim().length===0)return D.json({session:$},201);let g=i0(),_=nG(g),R={engineCommand:BG(g,_),engineId:g.executionMode==="local-cli"?g.engineId:g.byok.provider,input:w.input,metadata:{...E,...WG(g,_)}};if(A)return JG(f,$,R,[{event:"session",data:$,id:$.id}]);return D.json(await f.startTurn({...R,sessionId:$.id}),201)}async function U3(D,u,r,A){let f=ur(u,r.workerId),w=await oD(D.req),F=Pr(w.input,"input"),E=i0(),$=nG(E),g={engineCommand:BG(E,$),engineId:E.executionMode==="local-cli"?E.engineId:E.byok.provider,input:F,metadata:{...gG(u,r.workerId,r.capabilityTemplateId,r.metadataJson??{}),...w.metadata??{},...WG(E,$)}};if(A)return JG(f,r,g);return D.json(await f.startTurn({...g,sessionId:r.id}),201)}function JG(D,u,r,A=[]){let f=new TextEncoder,w=!1,F=null,E=new ReadableStream({start($){let g=()=>{if(!w)$.enqueue(f.encode(`: heartbeat
1707
1707
 
1708
- `))},R=(B,J,H)=>{if(w)return;let G=[H!==void 0?`id: ${H}`:null,`event: ${B}`,`data: ${JSON.stringify(J)}`,""].filter((U)=>U!==null).join(`
1709
- `);$.enqueue(f.encode(`${G}
1710
- `))},S=D.bus.subscribe((B)=>{if(B.sessionId!==u.id)return;if(B.kind==="event"){let J=B.payload.event;if(ir(J))R("session_event",J,typeof J.id==="number"?J.id:void 0);return}if(B.kind==="turn"&&ir(B.payload.turn))R("turn",B.payload.turn,B.turnId)});for(let B of A)R(B.event,B.data,B.id);R("status",{sessionId:u.id,status:"started"}),F=setInterval(g,5000),D.startTurn({engineCommand:r.engineCommand??null,engineId:r.engineId,input:r.input,metadata:r.metadata,sessionId:u.id}).then((B)=>{R("result",B)}).catch((B)=>{R("error",{message:B instanceof Error?B.message:String(B)})}).finally(()=>{if(S(),F)clearInterval(F),F=null;if(!w)w=!0,$.close()})},cancel(){if(w=!0,F)clearInterval(F),F=null}});return new Response(E,{headers:{"cache-control":"no-cache",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8"}})}function X0(){let D=pr().find((r)=>r.key===jG),u=D?Uf.safeParse(D.valueJson):null;if(u?.success)return u.data;return C7(rq())}function C7(D){let u=Uf.parse(D);return k0(jG,u),u}function rq(){let D=mG(),u=D.find((r)=>r.installed);return{appearance:"system",byok:{apiKeyRef:"",baseUrl:"https://api.openai.com/v1",model:"gpt-4o",provider:"openai-compatible"},connectors:[{enabled:!1,id:"ats",name:"ATS / HRIS",status:"not_configured"},{enabled:!1,id:"docs",name:"Docs workspace",status:"not_configured"},{enabled:!1,id:"issue-tracker",name:"Issue tracker",status:"not_configured"},{enabled:!1,id:"ci",name:"CI / release evidence",status:"not_configured"},{enabled:!1,id:"cloud",name:"Cloud account",status:"not_configured"},{enabled:!1,id:"crm",name:"CRM",status:"not_configured"}],engineId:u?.id??"codex",engines:D,executionMode:u?"local-cli":"byok",externalMcpServers:[{command:"",enabled:!1,id:"team-context",name:"Team context MCP"},{command:"",enabled:!1,id:"evidence-search",name:"Evidence search MCP"}],language:"en",localMcpServer:{enabled:!0,url:"http://127.0.0.1:4319/mcp"},updatedAt:new Date().toISOString()}}function mG(){return VL.map((D)=>{let u=qG("bash",["-lc",`command -v ${D.command}`]).trim();if(!u)return{command:D.command,id:D.id,installed:!1,name:D.name,path:null,version:null};let r=qG(u,["--version"]).split(`
1711
- `)[0]?.trim()||"installed";return{command:D.command,id:D.id,installed:!0,name:D.name,path:u,version:r}})}function qG(D,u){let r=YL(D,u,{encoding:"utf8",timeout:2500});if(r.status!==0)return"";return r.stdout.toString()}function ir(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}async function J7(D,u){let r=aG(pG(u),"index.html");try{return new Response(await bG(r),{headers:{"content-type":"text/html; charset=utf-8"}})}catch{return D.text("Worker Web build not found. Run `bun run --filter '@zonease/aiworker-web' build` first.",404)}}async function vA(D,u,r){let A=pG(u),f=aG(A,r);try{if(!(await iL(f)).isFile())return D.text("Not found",404);return new Response(await bG(f),{headers:{"content-type":Aq(f)}})}catch{return D.text("Not found",404)}}function pG(D){if(D)return Dr.resolve(D);let u=Dr.dirname(kL(import.meta.url));return Dr.resolve(u,"../../../web/dist/worker")}function aG(D,u){let r=Dr.resolve(D),A=Dr.resolve(r,u);if(A!==r&&!A.startsWith(`${r}${Dr.sep}`))throw Error(`Static path escapes Worker Web root: ${u}`);return A}function Aq(D){let u=Dr.extname(D);if(u===".css")return"text/css; charset=utf-8";if(u===".js")return"text/javascript; charset=utf-8";if(u===".json"||u===".map")return"application/json; charset=utf-8";if(u===".svg")return"image/svg+xml";if(u===".png")return"image/png";if(u===".jpg"||u===".jpeg")return"image/jpeg";if(u===".webp")return"image/webp";if(u===".woff2")return"font/woff2";return"application/octet-stream"}function fq(D){let u=_.object({}).passthrough().openapi("LocalResponse"),r={200:{description:"OK",content:{"application/json":{schema:u}}}},A={201:{description:"Created",content:{"application/json":{schema:u}}}},f=[{method:"get",path:"/api/local/info",summary:"Local daemon info",tags:["info"]},{method:"get",path:"/api/local/apps",summary:"List Host Soul Apps",tags:["apps"]},{method:"post",path:"/api/local/apps/install",summary:"Install Host Soul App manifest",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}",summary:"Show Host Soul App",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/security-review",summary:"Review Soul App permissions before enablement",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/enable",summary:"Enable Host Soul App",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/disable",summary:"Disable Host Soul App",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/healthcheck",summary:"Run Host Soul App static healthcheck",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/actions/{actionId}",summary:"Invoke a declared Soul App shell action",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/search",summary:"Search through a declared Soul App provider",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/permissions",summary:"List Soul App broker permissions",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/providers",summary:"List Host broker providers visible to a Soul App",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/search",summary:"Query Soul App broker search index descriptors",tags:["apps"]},{method:"put",path:"/api/local/apps/{appId}/broker/search/{itemId}",summary:"Upsert a Soul App broker search index descriptor",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/storage",summary:"List Soul App scoped storage records",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/storage/{key}",summary:"Read Soul App scoped storage record",tags:["apps"]},{method:"put",path:"/api/local/apps/{appId}/broker/storage/{key}",summary:"Write Soul App scoped storage record",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/broker/connectors/{connectorId}/evidence",summary:"Read brokered connector evidence",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/broker/audit",summary:"List Soul App broker audit events",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/broker/engine/invocations",summary:"Deny raw Soul App engine invocation attempts",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/surfaces/{surfaceId}",summary:"Resolve a declared mounted Soul App UI surface",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/{path}",summary:"Reserved mounted Soul App API namespace",tags:["apps"]},{method:"get",path:"/api/local/workers",summary:"List Soul workers",tags:["workers"]},{method:"post",path:"/api/local/workers",summary:"Create Soul worker",tags:["workers"],created:!0},{method:"get",path:"/api/local/workers/{workerId}",summary:"Show Soul worker",tags:["workers"]},{method:"patch",path:"/api/local/workers/{workerId}",summary:"Update Soul worker",tags:["workers"]},{method:"get",path:"/api/local/souls",summary:"List vertical Souls",tags:["souls"]},{method:"get",path:"/api/local/souls/{id}",summary:"Show vertical Soul",tags:["souls"]},{method:"get",path:"/api/local/templates",summary:"List capability templates",tags:["templates"]},{method:"get",path:"/api/local/templates/{id}",summary:"Show capability template",tags:["templates"]},{method:"get",path:"/api/local/workers/{workerId}/templates",summary:"List worker capability templates",tags:["templates"]},{method:"get",path:"/api/local/workers/{workerId}/templates/{templateId}",summary:"Show worker capability template",tags:["templates"]},{method:"get",path:"/api/local/workspaces",summary:"List workspaces",tags:["workspaces"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces",summary:"List worker workspaces",tags:["workspaces"]},{method:"post",path:"/api/local/workers/{workerId}/workspaces",summary:"Create worker workspace",tags:["workspaces"],created:!0},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}",summary:"Show worker workspace",tags:["workspaces"]},{method:"patch",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}",summary:"Update worker workspace",tags:["workspaces"]},{method:"get",path:"/api/local/workspaces/{workspaceId}",summary:"Show workspace",tags:["workspaces"]},{method:"patch",path:"/api/local/workspaces/{workspaceId}",summary:"Update workspace",tags:["workspaces"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/profile",summary:"Read workspace profile README",tags:["workspaces"]},{method:"post",path:"/api/local/workspaces/{workspaceId}/profile-revisions",summary:"Promote reviewed artifact into workspace profile",tags:["workspaces"],created:!0},{method:"get",path:"/api/local/sessions",summary:"List sessions",tags:["sessions"]},{method:"get",path:"/api/local/turns",summary:"List turns",tags:["turns"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions",summary:"List worker workspace sessions",tags:["sessions"]},{method:"post",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions",summary:"Create worker workspace session",tags:["sessions"],created:!0},{method:"post",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions/stream",summary:"Create worker workspace session with event stream",tags:["sessions"],created:!0},{method:"get",path:"/api/local/workspaces/{workspaceId}/sessions",summary:"List workspace sessions",tags:["sessions"]},{method:"post",path:"/api/local/workspaces/{workspaceId}/sessions",summary:"Create workspace session",tags:["sessions"],created:!0},{method:"post",path:"/api/local/workspaces/{workspaceId}/sessions/stream",summary:"Create workspace session with event stream",tags:["sessions"],created:!0},{method:"get",path:"/api/local/sessions/{sessionId}",summary:"Show session",tags:["sessions"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}",summary:"Show worker session",tags:["sessions"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}/events",summary:"Replay worker session events",tags:["events"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}/turns",summary:"List worker session turns",tags:["turns"]},{method:"post",path:"/api/local/workers/{workerId}/sessions/{sessionId}/messages",summary:"Create worker session message",tags:["turns"],created:!0},{method:"post",path:"/api/local/workers/{workerId}/sessions/{sessionId}/messages/stream",summary:"Create worker session message with event stream",tags:["turns"],created:!0},{method:"get",path:"/api/local/sessions/{sessionId}/events",summary:"Replay session events",tags:["events"]},{method:"get",path:"/api/local/sessions/{sessionId}/turns",summary:"List session turns",tags:["turns"]},{method:"post",path:"/api/local/sessions/{sessionId}/turns",summary:"Create session turn",tags:["turns"],created:!0},{method:"get",path:"/api/local/files",summary:"List files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/files",summary:"List worker files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files",summary:"List worker workspace files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/raw/{path}",summary:"Read worker workspace file",tags:["files"]},{method:"put",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/raw/{path}",summary:"Write worker workspace file",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/search",summary:"Search worker workspace files",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files",summary:"List workspace files",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files/raw/{path}",summary:"Read workspace file",tags:["files"]},{method:"put",path:"/api/local/workspaces/{workspaceId}/files/raw/{path}",summary:"Write workspace file",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files/search",summary:"Search workspace files",tags:["files"]},{method:"get",path:"/api/local/artifacts",summary:"List artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/workers/{workerId}/artifacts",summary:"List worker artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/artifacts",summary:"List workspace artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/artifacts/{id}",summary:"Show artifact",tags:["artifacts"]},{method:"get",path:"/api/local/reviews",summary:"List reviews",tags:["reviews"]},{method:"post",path:"/api/local/reviews",summary:"Create review",tags:["reviews"],created:!0},{method:"get",path:"/api/local/reviews/{id}",summary:"Show review",tags:["reviews"]},{method:"get",path:"/api/local/lessons",summary:"List lessons",tags:["lessons"]},{method:"post",path:"/api/local/lessons",summary:"Create lesson",tags:["lessons"],created:!0},{method:"patch",path:"/api/local/lessons/{id}",summary:"Update lesson",tags:["lessons"]},{method:"get",path:"/api/local/settings",summary:"Show settings",tags:["settings"]},{method:"patch",path:"/api/local/settings",summary:"Update settings",tags:["settings"]},{method:"post",path:"/api/local/settings/engines/rescan",summary:"Rescan engines",tags:["settings"],created:!0},{method:"post",path:"/api/local/settings/engines/test",summary:"Test engine",tags:["settings"],created:!0},{method:"get",path:"/api/local/events",summary:"List session events",tags:["events"]}];for(let w of f)D.openAPIRegistry.registerPath({method:w.method,path:w.path,summary:w.summary,tags:w.tags,responses:w.created?A:r})}var IL="dev",jG="local-settings",TG,VL,Zr=1e4,KL;var DC=W(()=>{CG();VG();J$();z2();Sr();hG();QG();TG=new WeakMap,VL=[{id:"codex",name:"Codex CLI",command:"codex"},{id:"claude-code",name:"Claude Code",command:"claude"},{id:"cursor",name:"Cursor Agent",command:"cursor-agent"},{id:"gemini",name:"Gemini CLI",command:"gemini"},{id:"opencode",name:"OpenCode",command:"opencode"},{id:"qwen",name:"Qwen Code",command:"qwen"}],KL=new Set(["authorization","connection","content-length","cookie","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","x-real-ip"])});J$();k3();z2();Sr();import{Buffer as wC}from"buffer";import{spawn as $C}from"child_process";import{createHash as EC,randomUUID as H7}from"crypto";import{chmodSync as Fq,closeSync as wq,existsSync as ZD,mkdirSync as gC,mkdtempSync as _C,openSync as $q,readdirSync as n7,readFileSync as t2,realpathSync as Eq,renameSync as gq,rmSync as c0,statSync as oA,writeFileSync as Y3}from"fs";import{mkdir as uC,readFile as _q}from"fs/promises";import{tmpdir as Rq}from"os";import L from"path";import a from"process";import{fileURLToPath as Sq}from"url";import{EventEmitter as Xh}from"events";function W$(D){return D==null?[]:Array.isArray(D)?D:[D]}function Yh(D,u,r,A){var f,w=D[u],F=~A.string.indexOf(u)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~A.boolean.indexOf(u)?r==="false"?!1:r==="true"||(D._.push((f=+r,f*0===0)?f:r),!!r):(f=+r,f*0===0)?f:r;D[u]=w==null?F:Array.isArray(w)?w.concat(F):[w,F]}function Mh(D,u){D=D||[],u=u||{};var r,A,f,w,F,E={_:[]},$=0,g=0,R=0,S=D.length;let B=u.alias!==void 0,J=u.unknown!==void 0,H=u.default!==void 0;if(u.alias=u.alias||{},u.string=W$(u.string),u.boolean=W$(u.boolean),B)for(r in u.alias){A=u.alias[r]=W$(u.alias[r]);for($=0;$<A.length;$++)(u.alias[A[$]]=A.concat(r)).splice($,1)}for($=u.boolean.length;$-- >0;){A=u.alias[u.boolean[$]]||[];for(g=A.length;g-- >0;)u.boolean.push(A[g])}for($=u.string.length;$-- >0;){A=u.alias[u.string[$]]||[];for(g=A.length;g-- >0;)u.string.push(A[g])}if(H){for(r in u.default)if(w=typeof u.default[r],A=u.alias[r]=u.alias[r]||[],u[w]!==void 0){u[w].push(r);for($=0;$<A.length;$++)u[w].push(A[$])}}let G=J?Object.keys(u.alias):[];for($=0;$<S;$++){if(f=D[$],f==="--"){E._=E._.concat(D.slice(++$));break}for(g=0;g<f.length;g++)if(f.charCodeAt(g)!==45)break;if(g===0)E._.push(f);else if(f.substring(g,g+3)==="no-"){if(w=f.substring(g+3),J&&!~G.indexOf(w))return u.unknown(f);E[w]=!1}else{for(R=g+1;R<f.length;R++)if(f.charCodeAt(R)===61)break;w=f.substring(g,R),F=f.substring(++R)||($+1===S||(""+D[$+1]).charCodeAt(0)===45||D[++$]),A=g===2?[w]:w;for(R=0;R<A.length;R++){if(w=A[R],J&&!~G.indexOf(w))return u.unknown("-".repeat(g)+w);Yh(E,w,R+1<A.length||F,u)}}}if(H){for(r in u.default)if(E[r]===void 0)E[r]=u.default[r]}if(B)for(r in E){A=u.alias[r]||[];while(A.length>0)E[A.shift()]=E[r]}return E}var xB=(D)=>D.replace(/[<[].+/,"").trim(),Oh=(D)=>{let u=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,A=[],f=(E)=>{let $=!1,g=E[1];if(g.startsWith("..."))g=g.slice(3),$=!0;return{required:E[0].startsWith("<"),value:g,variadic:$}},w;while(w=u.exec(D))A.push(f(w));let F;while(F=r.exec(D))A.push(f(F));return A},Ph=(D)=>{let u={alias:{},boolean:[]};for(let[r,A]of D.entries()){if(A.names.length>1)u.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!D.some((w,F)=>{return F!==r&&w.names.some((E)=>A.names.includes(E))&&typeof w.required==="boolean"}))u.boolean.push(A.names[0])}else u.boolean.push(A.names[0])}return u},cB=(D)=>{return D.sort((u,r)=>{return u.length>r.length?-1:1})[0]},tB=(D,u)=>{return D.length>=u?D:`${D}${" ".repeat(u-D.length)}`},ih=(D)=>{return D.replace(/([a-z])-([a-z])/g,(u,r,A)=>{return r+A.toUpperCase()})},kh=(D,u,r)=>{let A=0,f=u.length,w=D,F;for(;A<f;++A)F=w[u[A]],w=w[u[A]]=A===f-1?r:F!=null?F:!!~u[A+1].indexOf(".")||!(+u[A+1]>-1)?{}:[]},Ih=(D,u)=>{for(let r of Object.keys(u)){let A=u[r];if(A.shouldTransform){if(D[r]=Array.prototype.concat.call([],D[r]),typeof A.transformFunction==="function")D[r]=D[r].map(A.transformFunction)}}},Vh=(D)=>{let u=/([^\\\/]+)$/.exec(D);return u?u[1]:""},mB=(D)=>{return D.split(".").map((u,r)=>{return r===0?ih(u):u}).join(".")};class df extends Error{constructor(D){super(D);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(D).stack}}class pB{constructor(D,u,r){if(this.rawName=D,this.description=u,this.config=Object.assign({},r),D=D.replace(/\.\*/g,""),this.negated=!1,this.names=xB(D).split(",").map((A)=>{let f=A.trim().replace(/^-{1,2}/,"");if(f.startsWith("no-"))this.negated=!0,f=f.replace(/^no-/,"");return mB(f)}).sort((A,f)=>A.length>f.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(D.includes("<"))this.required=!0;else if(D.includes("["))this.required=!1;else this.isBoolean=!0}}var Kh=process.argv,hh=`${process.platform}-${process.arch} node-${process.version}`;class G${constructor(D,u,r={},A){this.rawName=D,this.description=u,this.config=r,this.cli=A,this.options=[],this.aliasNames=[],this.name=xB(D),this.args=Oh(D),this.examples=[]}usage(D){return this.usageText=D,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(D,u="-v, --version"){return this.versionNumber=D,this.option(u,"Display version number"),this}example(D){return this.examples.push(D),this}option(D,u,r){let A=new pB(D,u,r);return this.options.push(A),this}alias(D){return this.aliasNames.push(D),this}action(D){return this.commandAction=D,this}isMatched(D){return this.name===D||this.aliasNames.includes(D)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof C$}hasOption(D){return D=D.split(".")[0],this.options.find((u)=>{return u.names.includes(D)})}outputHelp(){let{name:D,commands:u}=this.cli,{versionNumber:r,options:A,helpCallback:f}=this.cli.globalCommand,w=[{body:`${D}${r?`/${r}`:""}`}];if(w.push({title:"Usage",body:` $ ${D} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&u.length>0){let $=cB(u.map((g)=>g.rawName));w.push({title:"Commands",body:u.map((g)=>{return` ${tB(g.rawName,$.length)} ${g.description}`}).join(`
1708
+ `))},_=(n,B,C)=>{if(w)return;let J=[C!==void 0?`id: ${C}`:null,`event: ${n}`,`data: ${JSON.stringify(B)}`,""].filter((X)=>X!==null).join(`
1709
+ `);$.enqueue(f.encode(`${J}
1710
+ `))},R=D.bus.subscribe((n)=>{if(n.sessionId!==u.id)return;if(n.kind==="event"){let B=n.payload.event;if(kr(B))_("session_event",B,typeof B.id==="number"?B.id:void 0);return}if(n.kind==="turn"&&kr(n.payload.turn))_("turn",n.payload.turn,n.turnId)});for(let n of A)_(n.event,n.data,n.id);_("status",{sessionId:u.id,status:"started"}),F=setInterval(g,5000),D.startTurn({engineCommand:r.engineCommand??null,engineId:r.engineId,input:r.input,metadata:r.metadata,sessionId:u.id}).then((n)=>{_("result",n)}).catch((n)=>{_("error",{message:n instanceof Error?n.message:String(n)})}).finally(()=>{if(R(),F)clearInterval(F),F=null;if(!w)w=!0,$.close()})},cancel(){if(w=!0,F)clearInterval(F),F=null}});return new Response(E,{headers:{"cache-control":"no-cache",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8"}})}function i0(){let D=mr().find((r)=>r.key===FG),u=D?Of.safeParse(D.valueJson):null;if(u?.success)return u.data;return L7(Qq())}function L7(D){let u=Of.parse(D);return k0(FG,u),u}function Qq(){let D=GG(),u=D.find((r)=>r.installed);return{appearance:"system",byok:{apiKeyRef:"",baseUrl:"https://api.openai.com/v1",model:"gpt-4o",provider:"openai-compatible"},connectors:[{enabled:!1,id:"ats",name:"ATS / HRIS",status:"not_configured"},{enabled:!1,id:"docs",name:"Docs workspace",status:"not_configured"},{enabled:!1,id:"issue-tracker",name:"Issue tracker",status:"not_configured"},{enabled:!1,id:"ci",name:"CI / release evidence",status:"not_configured"},{enabled:!1,id:"cloud",name:"Cloud account",status:"not_configured"},{enabled:!1,id:"crm",name:"CRM",status:"not_configured"}],engineId:u?.id??"codex",engines:D,executionMode:u?"local-cli":"byok",externalMcpServers:[{command:"",enabled:!1,id:"team-context",name:"Team context MCP"},{command:"",enabled:!1,id:"evidence-search",name:"Evidence search MCP"}],language:"en",localMcpServer:{enabled:!0,url:"http://127.0.0.1:4319/mcp"},updatedAt:new Date().toISOString()}}function GG(){return wq.map((D)=>{let u=rG("bash",["-lc",`command -v ${D.command}`]).trim();if(!u)return{command:D.command,id:D.id,installed:!1,name:D.name,path:null,version:null};let r=rG(u,["--version"]).split(`
1711
+ `)[0]?.trim()||"installed";return{command:D.command,id:D.id,installed:!0,name:D.name,path:u,version:r}})}function rG(D,u){let r=eL(D,u,{encoding:"utf8",timeout:2500});if(r.status!==0)return"";return r.stdout.toString()}function kr(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}async function h7(D,u){let r=HG(CG(u),"index.html");try{return new Response(await AG(r),{headers:{"content-type":"text/html; charset=utf-8"}})}catch{return D.text("Worker Web build not found. Run `bun run --filter '@zonease/aiworker-web' build` first.",404)}}async function o1(D,u,r){let A=CG(u),f=HG(A,r);try{if(!(await Aq(f)).isFile())return D.text("Not found",404);return new Response(await AG(f),{headers:{"content-type":Lq(f)}})}catch{return D.text("Not found",404)}}function CG(D){if(D)return rr.resolve(D);let u=rr.dirname(fq(import.meta.url));return rr.resolve(u,"../../../web/dist/worker")}function HG(D,u){let r=rr.resolve(D),A=rr.resolve(r,u);if(A!==r&&!A.startsWith(`${r}${rr.sep}`))throw Error(`Static path escapes Worker Web root: ${u}`);return A}function Lq(D){let u=rr.extname(D);if(u===".css")return"text/css; charset=utf-8";if(u===".js")return"text/javascript; charset=utf-8";if(u===".json"||u===".map")return"application/json; charset=utf-8";if(u===".svg")return"image/svg+xml";if(u===".png")return"image/png";if(u===".jpg"||u===".jpeg")return"image/jpeg";if(u===".webp")return"image/webp";if(u===".woff2")return"font/woff2";return"application/octet-stream"}function qq(D){let u=S.object({}).passthrough().openapi("LocalResponse"),r={200:{description:"OK",content:{"application/json":{schema:u}}}},A={201:{description:"Created",content:{"application/json":{schema:u}}}},f=[{method:"get",path:"/api/local/info",summary:"Local daemon info",tags:["info"]},{method:"get",path:"/api/local/apps",summary:"List Host Soul Apps",tags:["apps"]},{method:"post",path:"/api/local/apps/install",summary:"Install Host Soul App manifest",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}",summary:"Show Host Soul App",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/security-review",summary:"Review Soul App permissions before enablement",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/enable",summary:"Enable Host Soul App",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/disable",summary:"Disable Host Soul App",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/healthcheck",summary:"Run Host Soul App static healthcheck",tags:["apps"],created:!0},{method:"post",path:"/api/local/apps/{appId}/actions/{actionId}",summary:"Invoke a declared Soul App shell action",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/search",summary:"Search through a declared Soul App provider",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/permissions",summary:"List Soul App broker permissions",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/providers",summary:"List Host broker providers visible to a Soul App",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/search",summary:"Query Soul App broker search index descriptors",tags:["apps"]},{method:"put",path:"/api/local/apps/{appId}/broker/search/{itemId}",summary:"Upsert a Soul App broker search index descriptor",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/storage",summary:"List Soul App scoped storage records",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/broker/storage/{key}",summary:"Read Soul App scoped storage record",tags:["apps"]},{method:"put",path:"/api/local/apps/{appId}/broker/storage/{key}",summary:"Write Soul App scoped storage record",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/broker/connectors/{connectorId}/evidence",summary:"Read brokered connector evidence",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/broker/audit",summary:"List Soul App broker audit events",tags:["apps"]},{method:"post",path:"/api/local/apps/{appId}/broker/engine/invocations",summary:"Deny raw Soul App engine invocation attempts",tags:["apps"],created:!0},{method:"get",path:"/api/local/apps/{appId}/surfaces/{surfaceId}",summary:"Resolve a declared mounted Soul App UI surface",tags:["apps"]},{method:"get",path:"/api/local/apps/{appId}/{path}",summary:"Reserved mounted Soul App API namespace",tags:["apps"]},{method:"get",path:"/api/local/workers",summary:"List Soul workers",tags:["workers"]},{method:"post",path:"/api/local/workers",summary:"Create Soul worker",tags:["workers"],created:!0},{method:"get",path:"/api/local/workers/{workerId}",summary:"Show Soul worker",tags:["workers"]},{method:"patch",path:"/api/local/workers/{workerId}",summary:"Update Soul worker",tags:["workers"]},{method:"get",path:"/api/local/souls",summary:"List vertical Souls",tags:["souls"]},{method:"get",path:"/api/local/souls/{id}",summary:"Show vertical Soul",tags:["souls"]},{method:"get",path:"/api/local/templates",summary:"List capability templates",tags:["templates"]},{method:"get",path:"/api/local/templates/{id}",summary:"Show capability template",tags:["templates"]},{method:"get",path:"/api/local/workers/{workerId}/templates",summary:"List worker capability templates",tags:["templates"]},{method:"get",path:"/api/local/workers/{workerId}/templates/{templateId}",summary:"Show worker capability template",tags:["templates"]},{method:"get",path:"/api/local/workspaces",summary:"List workspaces",tags:["workspaces"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces",summary:"List worker workspaces",tags:["workspaces"]},{method:"post",path:"/api/local/workers/{workerId}/workspaces",summary:"Create worker workspace",tags:["workspaces"],created:!0},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}",summary:"Show worker workspace",tags:["workspaces"]},{method:"patch",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}",summary:"Update worker workspace",tags:["workspaces"]},{method:"get",path:"/api/local/workspaces/{workspaceId}",summary:"Show workspace",tags:["workspaces"]},{method:"patch",path:"/api/local/workspaces/{workspaceId}",summary:"Update workspace",tags:["workspaces"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/profile",summary:"Read workspace profile README",tags:["workspaces"]},{method:"post",path:"/api/local/workspaces/{workspaceId}/profile-revisions",summary:"Promote reviewed artifact into workspace profile",tags:["workspaces"],created:!0},{method:"get",path:"/api/local/sessions",summary:"List sessions",tags:["sessions"]},{method:"get",path:"/api/local/turns",summary:"List turns",tags:["turns"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions",summary:"List worker workspace sessions",tags:["sessions"]},{method:"post",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions",summary:"Create worker workspace session",tags:["sessions"],created:!0},{method:"post",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/sessions/stream",summary:"Create worker workspace session with event stream",tags:["sessions"],created:!0},{method:"get",path:"/api/local/workspaces/{workspaceId}/sessions",summary:"List workspace sessions",tags:["sessions"]},{method:"post",path:"/api/local/workspaces/{workspaceId}/sessions",summary:"Create workspace session",tags:["sessions"],created:!0},{method:"post",path:"/api/local/workspaces/{workspaceId}/sessions/stream",summary:"Create workspace session with event stream",tags:["sessions"],created:!0},{method:"get",path:"/api/local/sessions/{sessionId}",summary:"Show session",tags:["sessions"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}",summary:"Show worker session",tags:["sessions"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}/events",summary:"Replay worker session events",tags:["events"]},{method:"get",path:"/api/local/workers/{workerId}/sessions/{sessionId}/turns",summary:"List worker session turns",tags:["turns"]},{method:"post",path:"/api/local/workers/{workerId}/sessions/{sessionId}/messages",summary:"Create worker session message",tags:["turns"],created:!0},{method:"post",path:"/api/local/workers/{workerId}/sessions/{sessionId}/messages/stream",summary:"Create worker session message with event stream",tags:["turns"],created:!0},{method:"get",path:"/api/local/sessions/{sessionId}/events",summary:"Replay session events",tags:["events"]},{method:"get",path:"/api/local/sessions/{sessionId}/turns",summary:"List session turns",tags:["turns"]},{method:"post",path:"/api/local/sessions/{sessionId}/turns",summary:"Create session turn",tags:["turns"],created:!0},{method:"get",path:"/api/local/files",summary:"List files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/files",summary:"List worker files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files",summary:"List worker workspace files",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/raw/{path}",summary:"Read worker workspace file",tags:["files"]},{method:"put",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/raw/{path}",summary:"Write worker workspace file",tags:["files"]},{method:"get",path:"/api/local/workers/{workerId}/workspaces/{workspaceId}/files/search",summary:"Search worker workspace files",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files",summary:"List workspace files",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files/raw/{path}",summary:"Read workspace file",tags:["files"]},{method:"put",path:"/api/local/workspaces/{workspaceId}/files/raw/{path}",summary:"Write workspace file",tags:["files"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/files/search",summary:"Search workspace files",tags:["files"]},{method:"get",path:"/api/local/artifacts",summary:"List artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/workers/{workerId}/artifacts",summary:"List worker artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/workspaces/{workspaceId}/artifacts",summary:"List workspace artifacts",tags:["artifacts"]},{method:"get",path:"/api/local/artifacts/{id}",summary:"Show artifact",tags:["artifacts"]},{method:"get",path:"/api/local/reviews",summary:"List reviews",tags:["reviews"]},{method:"post",path:"/api/local/reviews",summary:"Create review",tags:["reviews"],created:!0},{method:"get",path:"/api/local/reviews/{id}",summary:"Show review",tags:["reviews"]},{method:"get",path:"/api/local/lessons",summary:"List lessons",tags:["lessons"]},{method:"post",path:"/api/local/lessons",summary:"Create lesson",tags:["lessons"],created:!0},{method:"patch",path:"/api/local/lessons/{id}",summary:"Update lesson",tags:["lessons"]},{method:"get",path:"/api/local/settings",summary:"Show settings",tags:["settings"]},{method:"patch",path:"/api/local/settings",summary:"Update settings",tags:["settings"]},{method:"post",path:"/api/local/settings/engines/rescan",summary:"Rescan engines",tags:["settings"],created:!0},{method:"post",path:"/api/local/settings/engines/test",summary:"Test engine",tags:["settings"],created:!0},{method:"get",path:"/api/local/events",summary:"List session events",tags:["events"]}];for(let w of f)D.openAPIRegistry.registerPath({method:w.method,path:w.path,summary:w.summary,tags:w.tags,responses:w.created?A:r})}var Fq="dev",FG="local-settings",wG,wq,or=1e4,$q;var iG=W(()=>{zJ();xJ();h$();s2();nr();aJ();DG();wG=new WeakMap,wq=[{id:"codex",name:"Codex CLI",command:"codex"},{id:"claude-code",name:"Claude Code",command:"claude"},{id:"cursor",name:"Cursor Agent",command:"cursor-agent"},{id:"gemini",name:"Gemini CLI",command:"gemini"},{id:"opencode",name:"OpenCode",command:"opencode"},{id:"qwen",name:"Qwen Code",command:"qwen"}],$q=new Set(["authorization","connection","content-length","cookie","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","x-real-ip"])});h$();Q3();s2();nr();import{Buffer as IG}from"buffer";import{spawn as VG}from"child_process";import{createHash as KG,randomUUID as q7}from"crypto";import{chmodSync as bq,closeSync as sq,existsSync as cD,mkdirSync as hG,mkdtempSync as NG,openSync as zq,readdirSync as b7,readFileSync as t2,realpathSync as jq,renameSync as Tq,rmSync as t0,statSync as c1,writeFileSync as I3}from"fs";import{mkdir as UG,readFile as vq}from"fs/promises";import{tmpdir as Zq}from"os";import h from"path";import a from"process";import{fileURLToPath as oq}from"url";import{EventEmitter as ah}from"events";function N$(D){return D==null?[]:Array.isArray(D)?D:[D]}function eh(D,u,r,A){var f,w=D[u],F=~A.string.indexOf(u)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~A.boolean.indexOf(u)?r==="false"?!1:r==="true"||(D._.push((f=+r,f*0===0)?f:r),!!r):(f=+r,f*0===0)?f:r;D[u]=w==null?F:Array.isArray(w)?w.concat(F):[w,F]}function DN(D,u){D=D||[],u=u||{};var r,A,f,w,F,E={_:[]},$=0,g=0,_=0,R=D.length;let n=u.alias!==void 0,B=u.unknown!==void 0,C=u.default!==void 0;if(u.alias=u.alias||{},u.string=N$(u.string),u.boolean=N$(u.boolean),n)for(r in u.alias){A=u.alias[r]=N$(u.alias[r]);for($=0;$<A.length;$++)(u.alias[A[$]]=A.concat(r)).splice($,1)}for($=u.boolean.length;$-- >0;){A=u.alias[u.boolean[$]]||[];for(g=A.length;g-- >0;)u.boolean.push(A[g])}for($=u.string.length;$-- >0;){A=u.alias[u.string[$]]||[];for(g=A.length;g-- >0;)u.string.push(A[g])}if(C){for(r in u.default)if(w=typeof u.default[r],A=u.alias[r]=u.alias[r]||[],u[w]!==void 0){u[w].push(r);for($=0;$<A.length;$++)u[w].push(A[$])}}let J=B?Object.keys(u.alias):[];for($=0;$<R;$++){if(f=D[$],f==="--"){E._=E._.concat(D.slice(++$));break}for(g=0;g<f.length;g++)if(f.charCodeAt(g)!==45)break;if(g===0)E._.push(f);else if(f.substring(g,g+3)==="no-"){if(w=f.substring(g+3),B&&!~J.indexOf(w))return u.unknown(f);E[w]=!1}else{for(_=g+1;_<f.length;_++)if(f.charCodeAt(_)===61)break;w=f.substring(g,_),F=f.substring(++_)||($+1===R||(""+D[$+1]).charCodeAt(0)===45||D[++$]),A=g===2?[w]:w;for(_=0;_<A.length;_++){if(w=A[_],B&&!~J.indexOf(w))return u.unknown("-".repeat(g)+w);eh(E,w,_+1<A.length||F,u)}}}if(C){for(r in u.default)if(E[r]===void 0)E[r]=u.default[r]}if(n)for(r in E){A=u.alias[r]||[];while(A.length>0)E[A.shift()]=E[r]}return E}var JB=(D)=>D.replace(/[<[].+/,"").trim(),uN=(D)=>{let u=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,A=[],f=(E)=>{let $=!1,g=E[1];if(g.startsWith("..."))g=g.slice(3),$=!0;return{required:E[0].startsWith("<"),value:g,variadic:$}},w;while(w=u.exec(D))A.push(f(w));let F;while(F=r.exec(D))A.push(f(F));return A},rN=(D)=>{let u={alias:{},boolean:[]};for(let[r,A]of D.entries()){if(A.names.length>1)u.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!D.some((w,F)=>{return F!==r&&w.names.some((E)=>A.names.includes(E))&&typeof w.required==="boolean"}))u.boolean.push(A.names[0])}else u.boolean.push(A.names[0])}return u},BB=(D)=>{return D.sort((u,r)=>{return u.length>r.length?-1:1})[0]},WB=(D,u)=>{return D.length>=u?D:`${D}${" ".repeat(u-D.length)}`},AN=(D)=>{return D.replace(/([a-z])-([a-z])/g,(u,r,A)=>{return r+A.toUpperCase()})},fN=(D,u,r)=>{let A=0,f=u.length,w=D,F;for(;A<f;++A)F=w[u[A]],w=w[u[A]]=A===f-1?r:F!=null?F:!!~u[A+1].indexOf(".")||!(+u[A+1]>-1)?{}:[]},FN=(D,u)=>{for(let r of Object.keys(u)){let A=u[r];if(A.shouldTransform){if(D[r]=Array.prototype.concat.call([],D[r]),typeof A.transformFunction==="function")D[r]=D[r].map(A.transformFunction)}}},wN=(D)=>{let u=/([^\\\/]+)$/.exec(D);return u?u[1]:""},GB=(D)=>{return D.split(".").map((u,r)=>{return r===0?AN(u):u}).join(".")};class xf extends Error{constructor(D){super(D);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(D).stack}}class CB{constructor(D,u,r){if(this.rawName=D,this.description=u,this.config=Object.assign({},r),D=D.replace(/\.\*/g,""),this.negated=!1,this.names=JB(D).split(",").map((A)=>{let f=A.trim().replace(/^-{1,2}/,"");if(f.startsWith("no-"))this.negated=!0,f=f.replace(/^no-/,"");return GB(f)}).sort((A,f)=>A.length>f.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(D.includes("<"))this.required=!0;else if(D.includes("["))this.required=!1;else this.isBoolean=!0}}var $N=process.argv,EN=`${process.platform}-${process.arch} node-${process.version}`;class Q${constructor(D,u,r={},A){this.rawName=D,this.description=u,this.config=r,this.cli=A,this.options=[],this.aliasNames=[],this.name=JB(D),this.args=uN(D),this.examples=[]}usage(D){return this.usageText=D,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(D,u="-v, --version"){return this.versionNumber=D,this.option(u,"Display version number"),this}example(D){return this.examples.push(D),this}option(D,u,r){let A=new CB(D,u,r);return this.options.push(A),this}alias(D){return this.aliasNames.push(D),this}action(D){return this.commandAction=D,this}isMatched(D){return this.name===D||this.aliasNames.includes(D)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof L$}hasOption(D){return D=D.split(".")[0],this.options.find((u)=>{return u.names.includes(D)})}outputHelp(){let{name:D,commands:u}=this.cli,{versionNumber:r,options:A,helpCallback:f}=this.cli.globalCommand,w=[{body:`${D}${r?`/${r}`:""}`}];if(w.push({title:"Usage",body:` $ ${D} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&u.length>0){let $=BB(u.map((g)=>g.rawName));w.push({title:"Commands",body:u.map((g)=>{return` ${WB(g.rawName,$.length)} ${g.description}`}).join(`
1712
1712
  `)}),w.push({title:"For more info, run any command with the `--help` flag",body:u.map((g)=>` $ ${D}${g.name===""?"":` ${g.name}`} --help`).join(`
1713
- `)})}let E=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)E=E.filter(($)=>$.name!=="version");if(E.length>0){let $=cB(E.map((g)=>g.rawName));w.push({title:"Options",body:E.map((g)=>{return` ${tB(g.rawName,$.length)} ${g.description} ${g.config.default===void 0?"":`(default: ${g.config.default})`}`}).join(`
1713
+ `)})}let E=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)E=E.filter(($)=>$.name!=="version");if(E.length>0){let $=BB(E.map((g)=>g.rawName));w.push({title:"Options",body:E.map((g)=>{return` ${WB(g.rawName,$.length)} ${g.description} ${g.config.default===void 0?"":`(default: ${g.config.default})`}`}).join(`
1714
1714
  `)})}if(this.examples.length>0)w.push({title:"Examples",body:this.examples.map(($)=>{if(typeof $==="function")return $(D);return $}).join(`
1715
1715
  `)});if(f)w=f(w)||w;console.log(w.map(($)=>{return $.title?`${$.title}:
1716
1716
  ${$.body}`:$.body}).join(`
1717
1717
 
1718
- `))}outputVersion(){let{name:D}=this.cli,{versionNumber:u}=this.cli.globalCommand;if(u)console.log(`${D}/${u} ${hh}`)}checkRequiredArgs(){let D=this.args.filter((u)=>u.required).length;if(this.cli.args.length<D)throw new df(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:D,globalCommand:u}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(D))if(r!=="--"&&!this.hasOption(r)&&!u.hasOption(r))throw new df(`Unknown option \`${r.length>1?`--${r}`:`-${r}`}\``)}}checkOptionValue(){let{options:D,globalCommand:u}=this.cli,r=[...u.options,...this.options];for(let A of r){let f=D[A.name.split(".")[0]];if(A.required){let w=r.some((F)=>F.negated&&F.names.includes(A.name));if(f===!0||f===!1&&!w)throw new df(`option \`${A.rawName}\` value is missing`)}}}}class C$ extends G${constructor(D){super("@@global@@","",{},D)}}var of=Object.assign;class aB extends Xh{constructor(D=""){super();this.name=D,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new C$(this),this.globalCommand.usage("<command> [options]")}usage(D){return this.globalCommand.usage(D),this}command(D,u,r){let A=new G$(D,u||"",r,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(D,u,r){return this.globalCommand.option(D,u,r),this}help(D){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=D,this.showHelpOnExit=!0,this}version(D,u="-v, --version"){return this.globalCommand.version(D,u),this.showVersionOnExit=!0,this}example(D){return this.globalCommand.example(D),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:D,options:u},r,A){if(this.args=D,this.options=u,r)this.matchedCommand=r;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(D=Kh,{run:u=!0}={}){if(this.rawArgs=D,!this.name)this.name=D[1]?Vh(D[1]):"cli";let r=!0;for(let f of this.commands){let w=this.mri(D.slice(2),f),F=w.args[0];if(f.isMatched(F)){r=!1;let E=of(of({},w),{args:w.args.slice(1)});this.setParsedInfo(E,f,F),this.emit(`command:${F}`,f)}}if(r){for(let f of this.commands)if(f.name===""){r=!1;let w=this.mri(D.slice(2),f);this.setParsedInfo(w,f),this.emit("command:!",f)}}if(r){let f=this.mri(D.slice(2));this.setParsedInfo(f)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),u=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),u=!1,this.unsetMatchedCommand();let A={args:this.args,options:this.options};if(u)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return A}mri(D,u){let r=[...this.globalCommand.options,...u?u.options:[]],A=Ph(r),f=[],w=D.indexOf("--");if(w>-1)f=D.slice(w+1),D=D.slice(0,w);let F=Mh(D,A);F=Object.keys(F).reduce((S,B)=>{return of(of({},S),{[mB(B)]:F[B]})},{_:[]});let E=F._,$={"--":f},g=u&&u.config.ignoreOptionDefaultValue?u.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,R=Object.create(null);for(let S of r){if(!g&&S.config.default!==void 0)for(let B of S.names)$[B]=S.config.default;if(Array.isArray(S.config.type)){if(R[S.name]===void 0)R[S.name]=Object.create(null),R[S.name].shouldTransform=!0,R[S.name].transformFunction=S.config.type[0]}}for(let S of Object.keys(F))if(S!=="_"){let B=S.split(".");kh($,B,F[S]),Ih($,R)}return{args:E,options:$}}runMatchedCommand(){let{args:D,options:u,matchedCommand:r}=this;if(!r||!r.commandAction)return;r.checkUnknownOptions(),r.checkOptionValue(),r.checkRequiredArgs();let A=[];return r.args.forEach((f,w)=>{if(f.variadic)A.push(D.slice(w));else A.push(D[w])}),A.push(u),r.commandAction.apply(this,A)}}var Nh=(D="")=>new aB(D),eB=Nh;D3();var Pu={name:"@zonease/aiworker-cli",type:"module",version:"0.15.1",description:"AIWorker CLI \u2014 local Host and vertical Soul workspace runtime",license:"MIT",homepage:"https://github.com/ZonEaseTech/aiworker#readme",repository:{type:"git",url:"git+https://github.com/ZonEaseTech/aiworker.git"},publishConfig:{access:"public"},bin:{aiworker:"./dist/aiworker.js"},files:["README.md","dist/"],engines:{bun:">=1.1"},scripts:{typecheck:"tsc --noEmit",test:"bun test --timeout=15000","test:stress":"bun test --timeout=15000 --rerun-each=3 src/commands/worker/init.integration.test.ts src/commands/worker/sessions.test.ts",build:"bun run --filter '@zonease/aiworker-web' build && bun run build:bundle","build:bundle":"bun run --filter '@zonease/aiworker-hr' build && bun run --filter '@zonease/aiworker-qa' build && bun build --target=bun --minify --outfile=dist/aiworker-bun.js src/aiworker.ts && bun scripts/build-publish-manifest.ts",prepublishOnly:"bun run build","smoke:dist-release":"bun scripts/smoke-dist-release.ts"},devDependencies:{"@types/bun":"^1.2.13","@zonease/aiworker-api":"workspace:*","@zonease/aiworker-core":"workspace:*","@zonease/aiworker-fs-layout":"workspace:*","@zonease/aiworker-shared":"workspace:*","@zonease/aiworker-storage-sqlite":"workspace:*",cac:"^6.7.14",consola:"^3.4.2",typescript:"^5.8.3",yaml:"^2.7.1"}};import PA from"process";var dJ="@zonease/aiworker-cli",iQ="https://registry.npmjs.org/@zonease%2Faiworker-cli",kQ="https://api.github.com/repos/ZonEaseTech/aiworker/releases/latest";function b$(D,u){if(u.channel!==void 0&&u.channel!=="stable"&&u.channel!=="preview")throw Error(`unsupported update channel: ${u.channel}`);let r=u.pre===!0||u.channel==="preview",A=u.check===!0?"check":u.dryRun===!0?"dry-run":"apply";return{channel:r?"preview":"stable",command:D,mode:A,prerelease:r,target:u.target,yes:u.yes===!0}}function z$(D){let u=A3(D.argv1),r=A3(D.realArgv1),A=A3(D.moduleDir),f=[u,r,A].filter(Boolean).join(`
1719
- `);if(A.includes("/apps/cli/src")||r.endsWith("/apps/cli/src/aiworker.ts"))return{canAutoUpgrade:!1,kind:"source-checkout",reason:"source checkout cannot self-modify"};if(f.includes("/.npm/_npx/")||f.includes("/.bun/install/cache/"))return{canAutoUpgrade:!1,kind:"ephemeral",reason:"ephemeral runner cache cannot be upgraded in place"};if(r3(u,D.npmGlobalBinDirs)||r3(r,D.npmGlobalBinDirs))return{canAutoUpgrade:!0,kind:"npm-global",packageManager:"npm"};if(r3(u,D.bunGlobalBinDirs)||r3(r,D.bunGlobalBinDirs))return{canAutoUpgrade:!0,kind:"bun-global",packageManager:"bun"};if(A.includes("/aiworker-darwin-")||A.includes("/aiworker-linux-"))return{canAutoUpgrade:!0,kind:"github-tarball"};return{canAutoUpgrade:!1,kind:"unknown",reason:"installation source could not be proven"}}function j$(D){let u=[],r;if(QQ(D.currentVersion,D.target.version)>=0)r="already_current";else if(D.source.kind==="unknown")r="source_unknown";else if(!D.source.canAutoUpgrade&&D.options.mode!=="check")r="source_not_supported";else if(D.source.kind==="github-tarball"&&D.options.mode!=="check"&&(!D.target.downloadUrl||!D.target.checksumUrl))r="source_not_supported";else r="update_available";if(r==="update_available"&&D.options.mode!=="check"){if(D.source.packageManager)u.push(VQ(D.source.packageManager,D.target.version));else if(D.source.kind==="github-tarball"&&D.target.downloadUrl&&D.target.checksumUrl)u.push({checksumUrl:D.target.checksumUrl,downloadUrl:D.target.downloadUrl,kind:"github-tarball"});if(D.options.mode==="apply"&&u.length>0)u.push({kind:"host-convergence"},{kind:"daemon-restart"})}return{actions:u,currentVersion:D.currentVersion,mode:D.options.mode,requiresConfirmation:D.options.mode==="apply"&&u.length>0&&!D.options.yes,source:D.source,status:r,target:D.target,targetVersion:D.target.version}}async function T$(D){if(D.options.target)return{checksumUrl:null,downloadUrl:null,isPrerelease:D.options.prerelease,source:D.source.kind==="github-tarball"?"github":"npm",version:D.options.target};if(D.source.kind==="github-tarball"){let f=hQ(await yJ(D.fetch,kQ)),w=(D.platformAssetName??IQ)(),F=f.assets.find(($)=>$.name===w),E=f.assets.find(($)=>$.name===`${w}.sha256`);return{checksumUrl:lJ(E,`${w}.sha256`),downloadUrl:lJ(F,w),isPrerelease:D.options.prerelease,source:"github",version:f.tag_name.replace(/^v/,"")}}let u=KQ(await yJ(D.fetch,iQ)),r=D.options.prerelease?"preview":"latest",A=u["dist-tags"]?.[r];if(typeof A!=="string"||A.length===0)throw Error(`npm dist-tag not found: ${r}`);return{checksumUrl:null,downloadUrl:null,isPrerelease:D.options.prerelease,source:"npm",version:A}}async function xJ(D){if(D.plan.mode==="dry-run")return{completedActions:[],status:"dry_run"};if(D.plan.status!=="update_available"||D.plan.actions.length===0)return{completedActions:[],status:"skipped"};let u=[];for(let r of D.plan.actions){if(r.kind==="package-manager"){if(!r.command||!r.args)throw Error("package-manager upgrade action is missing command or args");await u3(D.runCommand,"runCommand")(r.command,r.args)}else if(r.kind==="github-tarball"){if(!r.downloadUrl||!r.checksumUrl)throw Error("github tarball upgrade action requires downloadUrl and checksumUrl");await u3(D.downloadAndReplace,"downloadAndReplace")({checksumUrl:r.checksumUrl,downloadUrl:r.downloadUrl})}else if(r.kind==="host-convergence")await u3(D.convergeHost,"convergeHost")();else await u3(D.restartDaemon,"restartDaemon")();u.push(r.kind)}return{completedActions:u,status:"completed"}}function mJ(D,u){if(!D?.checkedAt)return{canCheck:!0,latestSeenVersion:D?.latestSeenVersion??null};let r=new Date(D.checkedAt),A=u.getTime()-r.getTime();return{canCheck:!Number.isFinite(r.getTime())||A<0||A>=86400000,latestSeenVersion:D.latestSeenVersion??null}}function IQ(){let D=PA.platform==="win32"?"windows":PA.platform,u=PA.arch==="x64"?"x64":PA.arch==="arm64"?"arm64":PA.arch;return`aiworker-${D}-${u}.tar.gz`}function VQ(D,u){if(D==="bun")return{args:["install","-g",`${dJ}@${u}`],command:"bun",kind:"package-manager",packageManager:D};return{args:["install","-g",`${dJ}@${u}`],command:"npm",kind:"package-manager",packageManager:D}}async function yJ(D,u){let r=await(D??globalThis.fetch)(u);if(!r.ok)throw Error(`failed to resolve release target from ${u}: HTTP ${r.status}`);return await r.json()}function KQ(D){if(!f3(D))return{};let u=D["dist-tags"];if(!f3(u))return{};return{"dist-tags":Object.fromEntries(Object.entries(u).filter((r)=>typeof r[1]==="string"))}}function hQ(D){if(!f3(D)||typeof D.tag_name!=="string"||D.tag_name.length===0)throw Error("github release tag not found");if(!Array.isArray(D.assets))throw Error("github release assets invalid");return{assets:D.assets.filter(NQ),tag_name:D.tag_name}}function NQ(D){return f3(D)&&(D.name===void 0||typeof D.name==="string")}function lJ(D,u){if(D===void 0)return null;if(typeof D.browser_download_url!=="string"||D.browser_download_url.trim().length===0)throw Error(`github release asset url invalid: ${u}`);return D.browser_download_url}function u3(D,u){if(D===void 0)throw Error(`upgrade executor hook missing: ${u}`);return D}function f3(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}function QQ(D,u){let r=tJ(D),A=tJ(u);for(let f=0;f<3;f+=1){let w=r.core[f]??0,F=A.core[f]??0;if(w>F)return 1;if(w<F)return-1}return LQ(r.prerelease,A.prerelease)}function r3(D,u){if(!D)return!1;return(u??[]).map(A3).some((r)=>{if(!r)return!1;return D===r||D.startsWith(`${r}/`)})}function A3(D){if(!D)return"";return D.replaceAll("\\","/").replace(/\/+/g,"/").replace(/\/$/,"")}function LQ(D,u){if(D.length===0&&u.length===0)return 0;if(D.length===0)return 1;if(u.length===0)return-1;let r=Math.max(D.length,u.length);for(let A=0;A<r;A+=1){let f=D[A],w=u[A];if(f===void 0)return-1;if(w===void 0)return 1;let F=cJ(f),E=cJ(w);if(F!==void 0&&E!==void 0){if(F>E)return 1;if(F<E)return-1;continue}if(F!==void 0)return-1;if(E!==void 0)return 1;if(f>w)return 1;if(f<w)return-1}return 0}function cJ(D){if(!/^\d+$/.test(D))return;return Number.parseInt(D,10)}function tJ(D){let u=D.replace(/^v/,"").split("+",1)[0]??"",r=u.indexOf("-"),A=r===-1?u:u.slice(0,r),f=r===-1?void 0:u.slice(r+1);return{core:(A??"").split(".").slice(0,3).map((w)=>Number.parseInt(w,10)).map((w)=>Number.isFinite(w)?w:0),prerelease:f?f.split("."):[]}}var v=eB("aiworker"),x2=L.dirname(Sq(import.meta.url)),rC="soul-app.manifest.json";function RC(D=x2){let u=L.resolve(D,"official-apps");if(ZD(L.join(u,"aiworker-hr",rC)))return u;let r=L.resolve(D,"../../apps");if(ZD(L.join(r,"aiworker-hr",rC)))return r;return}function Bq(D=x2){let u=L.resolve(D,"web","worker");if(ZD(L.join(u,"index.html")))return u;let r=L.resolve(D,"../../web/dist/worker");if(ZD(L.join(r,"index.html")))return r;return}var Jq=".aiworker-dev",Wq=".aiworker";function Gq(D=x2){let u=ZD(L.join(D,"official-apps")),r=ZD(L.join(D,"web","worker"));return u||r?Wq:Jq}function Cq(D=x2){let u=P3({defaultHomeDir:Gq(D)}).home;return{home:u,dbPath:a.env.WORKER_DB_PATH??L.join(u,"aiworker.db"),workersRoot:L.join(u,"workers"),pidFile:L.join(u,"aiworker-daemon.pid"),logFile:L.join(u,"aiworker-daemon.log")}}function Hq(D){a.env.AIWORKER_HOME??=D.home,a.env.WORKER_DB_PATH??=D.dbPath}function m2(){let D=Cq();return Hq(D),D}async function gD(){let D=m2();return await uC(D.home,{recursive:!0}),await uC(L.dirname(D.dbPath),{recursive:!0}),W1(D.dbPath),G1(Zu().WORKER_MIGRATIONS_FOLDER),D}function nq(){let u=pr().find((r)=>r.key==="selected-worker")?.valueJson;return u&&typeof u.workerId==="string"?u.workerId:null}function U7(){return{hostVersion:Pu.version}}function lD(D,u={}){return XA({executor:u.executor,officialAppsRoot:u.officialAppsRoot??RC(),registryContext:u.registryContext??U7,workersRoot:D.workersRoot})}async function p2(D={}){let u=await gD(),r=D.worker??nq();if(!r)throw Error("worker is required; pass --worker or run `aiworker worker select <id>`");let A=PD(r);if(!A)throw Error(`worker not found: ${r}`);let f=lD(u).createRuntimeForWorker(A);return await f.init(),f}async function Iu(){return await gD(),Er()}function Z(D){a.stdout.write(`${JSON.stringify(D,null,2)}
1720
- `)}function Vu(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`${u} is required`);return D.trim()}function c2(D){let u=D?.[0];return typeof u==="number"&&Number.isFinite(u)?u:void 0}function Uq(D){try{return a.kill(D,0),!0}catch{return!1}}async function Xq(){let D=await gD();Z({home:D.home,dbPath:D.dbPath,workersRoot:D.workersRoot,workers:Er()})}async function Yq(){let D=await gD(),u=await SC();Z({ok:!0,home:D.home,dbPath:D.dbPath,apps:lD(D).listApps(),workers:Er(),workspaces:nu(),daemon:M3(),settings:pr(),updateNotice:u})}async function AC(D,u){let r=b$(D,u),A=X7(a.argv[1]),f=z$({argv1:A,bunGlobalBinDirs:JC(),moduleDir:x2,npmGlobalBinDirs:BC(),realArgv1:Y7(A)}),w=await T$({fetch:($)=>fetch($),options:r,source:f}),F=j$({currentVersion:Pu.version,options:r,source:f,target:w});if(r.mode!=="apply"){Z({update:F});return}if(F.status==="source_not_supported"||F.status==="source_unknown")throw Z({update:F}),Error(`update_not_supported: ${F.source.detail??F.source.reason??F.source.kind}`);if(F.status==="update_available"&&F.actions.length===0)throw Z({update:F}),Error("update_not_actionable");if(F.status!=="update_available"){Z({update:F});return}if(F.requiresConfirmation)throw Z({update:F}),Error("update requires --yes to apply changes");let E=await xJ({convergeHost:async()=>{await Db()},downloadAndReplace:async($)=>{await Mq($)},plan:F,restartDaemon:async()=>{vr.info("AIWorker daemon requires manual restart after CLI upgrade")},runCommand:async($,g)=>{if(await Bun.spawn([$,...g],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited!==0)throw Error(`package manager upgrade failed: ${$} ${g.join(" ")}`)}});Z({update:F,result:E})}async function Mq(D,u={}){let r=Y7(X7(u.currentPath??a.argv[1]));if(!r)throw Error("current binary path is required");let A=u.renameSync??gq,f=u.spawnSync??((J)=>Bun.spawnSync(J)),w=u.fetch??fetch,F=L.dirname(r),E=L.dirname(F),$=_C(L.join(E,".aiworker-update-")),g=L.join($,"aiworker.tar.gz"),R=L.join(E,`.aiworker-next-${a.pid}-${H7()}`),S=L.join(E,`.aiworker-backup-${a.pid}-${H7()}`),B=!1;try{let[J,H]=await Promise.all([Pq(D.checksumUrl,w),Oq(D.downloadUrl,w)]),G=J.trim().split(/\s+/)[0],U=EC("sha256").update(H).digest("hex");if(!G||U!==G)throw Error("checksum_mismatch");Y3(g,H);let O=f(["tar","-xzf",g,"-C",$]);if(O.exitCode!==0){let M=fC(O.stderr);throw Error(`staging_failed: ${M||`tar exited ${O.exitCode}`}`)}let i=n7($).map((M)=>L.join($,M)).filter((M)=>oA(M).isDirectory()),k=i.find((M)=>ZD(L.join(M,"aiworker")));if(!k)throw Error(i.length>0?"staging_failed: aiworker binary not found":"staging_failed: extracted directory not found");let z=L.join(k,"aiworker");if(!ZD(z)||!oA(z).isFile())throw Error("staging_failed: aiworker binary not found");if(!ZD(L.join(k,"web"))||!oA(L.join(k,"web")).isDirectory())throw Error("staging_failed: web assets not found");if(!ZD(L.join(k,"drizzle"))||!oA(L.join(k,"drizzle")).isDirectory())throw Error("staging_failed: drizzle migrations not found");c0(R,{force:!0,recursive:!0}),c0(S,{force:!0,recursive:!0}),A(k,R),Fq(L.join(R,"aiworker"),493);let q=f([L.join(R,"aiworker"),"--version"]);if(q.exitCode!==0){let M=fC(q.stderr);throw Error(`staging_failed: version probe failed${M?`: ${M}`:""}`)}A(F,S);try{A(R,F)}catch(M){throw A(S,F),M}return B=!0,{backupPath:S,installedPath:r}}finally{if(c0($,{recursive:!0,force:!0}),!B)c0(R,{recursive:!0,force:!0})}}function fC(D){if(!D)return"";if(typeof D==="string")return D.trim();return wC.from(D.buffer,D.byteOffset,D.byteLength).toString("utf8").trim()}async function Oq(D,u=fetch){let r=await u(D);if(!r.ok)throw Error(`update asset fetch failed: HTTP ${r.status}`);return wC.from(await r.arrayBuffer())}async function Pq(D,u=fetch){let r=await u(D);if(!r.ok)throw Error(`update checksum fetch failed: HTTP ${r.status}`);return await r.text()}async function SC(){let D=new Date;try{await gD();let r=pr().find((g)=>g.key==="update.notice")?.valueJson??null,A=mJ(r,D);if(!A.canCheck)return A.latestSeenVersion&&kq(A.latestSeenVersion,Pu.version)>0?{channel:"stable",command:"aiworker update",currentVersion:Pu.version,targetVersion:A.latestSeenVersion}:null;let f=b$("update",{check:!0,channel:"stable"}),w=X7(a.argv[1]),F=z$({argv1:w,bunGlobalBinDirs:JC(),moduleDir:x2,npmGlobalBinDirs:BC(),realArgv1:Y7(w)}),E=await T$({fetch:(g)=>iq(g),options:f,source:F}),$=j$({currentVersion:Pu.version,options:f,source:F,target:E});return k0("update.notice",{checkedAt:D.toISOString(),latestSeenVersion:E.version}),$.status==="update_available"?{channel:"stable",command:"aiworker update",currentVersion:Pu.version,targetVersion:E.version}:null}catch(u){let r=u instanceof Error?u.message:String(u);try{let A=pr().find((f)=>f.key==="update.notice")?.valueJson.latestSeenVersion;k0("update.notice",{checkedAt:D.toISOString(),errorMessage:r,latestSeenVersion:typeof A==="string"?A:Pu.version})}catch{}return null}}function BC(){return WC([a.env.npm_config_prefix?L.join(a.env.npm_config_prefix,"bin"):void 0,a.env.PREFIX?L.join(a.env.PREFIX,"bin"):void 0,"/usr/local/bin","/opt/homebrew/bin"])}function JC(){return WC([a.env.BUN_INSTALL?L.join(a.env.BUN_INSTALL,"bin"):void 0,a.env.HOME?L.join(a.env.HOME,".bun","bin"):void 0])}function WC(D){return[...new Set(D.filter((u)=>typeof u==="string"&&u.length>0).map((u)=>L.resolve(u)))]}function X7(D){return D?L.resolve(D):void 0}function Y7(D){if(!D)return;try{return Eq(D)}catch{return D}}async function iq(D){let u=new AbortController,r=setTimeout(()=>u.abort(),750);try{return await fetch(D,{signal:u.signal})}finally{clearTimeout(r)}}function kq(D,u){let r=D.split(/[.-]/).map((w)=>Number.parseInt(w,10)||0),A=u.split(/[.-]/).map((w)=>Number.parseInt(w,10)||0),f=Math.max(r.length,A.length);for(let w=0;w<f;w++){let F=(r[w]??0)-(A[w]??0);if(F!==0)return F}return 0}function M3(){let D=m2();if(!ZD(D.pidFile))return{pid:null,running:!1,logFile:D.logFile};let u=Number.parseInt(t2(D.pidFile,"utf8"),10);return{pid:Number.isFinite(u)?u:null,running:Number.isFinite(u)&&Uq(u),logFile:D.logFile}}async function Iq(D={}){let u=m2();gC(u.home,{recursive:!0});let r=M3();if(r.running)throw Error(`daemon already running: pid=${r.pid}`);Y3(u.logFile,"");let A=$q(u.logFile,"a"),f=$C(a.execPath,[L.resolve(a.argv[1]??"aiworker"),"daemon","foreground",...D.host?["--host",D.host]:[],...D.port?["--port",String(D.port)]:[]],{cwd:a.cwd(),detached:!0,env:{...a.env,AIWORKER_HOME:u.home,WORKER_DB_PATH:u.dbPath},stdio:["ignore",A,A]});if(f.unref(),wq(A),!f.pid)throw Error("daemon did not return a pid");Y3(u.pidFile,String(f.pid)),Z({started:!0,pid:f.pid,logFile:u.logFile,url:`http://127.0.0.1:${D.port??Zu().PORT}`})}async function Vq(){let D=m2(),u=M3();if(!u.pid||!u.running){c0(D.pidFile,{force:!0}),Z({stopped:!1,running:!1});return}a.kill(u.pid,"SIGTERM"),c0(D.pidFile,{force:!0}),Z({stopped:!0,pid:u.pid})}async function FC(D={}){m2();let u=await SC();if(u)vr.info(`[aiworker-daemon] update available: ${u.currentVersion} -> ${u.targetVersion}; run ${u.command}`);let{bootstrapWorkerApp:r}=await Promise.resolve().then(() => (DC(),eG)),{app:A,port:f}=await r({officialAppsRoot:RC(),runtimeVersion:Pu.version,webStaticDir:Bq()}),w=Zu(),F=Bun.serve({fetch:A.fetch,hostname:D.host??w.AIWORKER_WORKER_HOST,idleTimeout:255,port:D.port??f});vr.success(`[aiworker-daemon] listening on http://${F.hostname}:${F.port}`),await new Promise((E)=>{let $=setInterval(()=>{return},60000),g=()=>{clearInterval($),F.stop(),E()};a.once("SIGINT",g),a.once("SIGTERM",g)})}async function Kq(D={}){let u=Zu(),r=`http://${D.host??u.AIWORKER_WORKER_HOST}:${D.port??u.PORT}/health`,A=await fetch(r);Z({ok:A.ok,status:A.status,body:await A.json().catch(()=>null)})}async function hq(D={}){let u=m2().logFile;if(!ZD(u))return;let A=(await _q(u,"utf8")).split(/\r?\n/);a.stdout.write(`${A.slice(-(D.tail??80)).join(`
1718
+ `))}outputVersion(){let{name:D}=this.cli,{versionNumber:u}=this.cli.globalCommand;if(u)console.log(`${D}/${u} ${EN}`)}checkRequiredArgs(){let D=this.args.filter((u)=>u.required).length;if(this.cli.args.length<D)throw new xf(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:D,globalCommand:u}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(D))if(r!=="--"&&!this.hasOption(r)&&!u.hasOption(r))throw new xf(`Unknown option \`${r.length>1?`--${r}`:`-${r}`}\``)}}checkOptionValue(){let{options:D,globalCommand:u}=this.cli,r=[...u.options,...this.options];for(let A of r){let f=D[A.name.split(".")[0]];if(A.required){let w=r.some((F)=>F.negated&&F.names.includes(A.name));if(f===!0||f===!1&&!w)throw new xf(`option \`${A.rawName}\` value is missing`)}}}}class L$ extends Q${constructor(D){super("@@global@@","",{},D)}}var pf=Object.assign;class HB extends ah{constructor(D=""){super();this.name=D,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new L$(this),this.globalCommand.usage("<command> [options]")}usage(D){return this.globalCommand.usage(D),this}command(D,u,r){let A=new Q$(D,u||"",r,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(D,u,r){return this.globalCommand.option(D,u,r),this}help(D){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=D,this.showHelpOnExit=!0,this}version(D,u="-v, --version"){return this.globalCommand.version(D,u),this.showVersionOnExit=!0,this}example(D){return this.globalCommand.example(D),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:D,options:u},r,A){if(this.args=D,this.options=u,r)this.matchedCommand=r;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(D=$N,{run:u=!0}={}){if(this.rawArgs=D,!this.name)this.name=D[1]?wN(D[1]):"cli";let r=!0;for(let f of this.commands){let w=this.mri(D.slice(2),f),F=w.args[0];if(f.isMatched(F)){r=!1;let E=pf(pf({},w),{args:w.args.slice(1)});this.setParsedInfo(E,f,F),this.emit(`command:${F}`,f)}}if(r){for(let f of this.commands)if(f.name===""){r=!1;let w=this.mri(D.slice(2),f);this.setParsedInfo(w,f),this.emit("command:!",f)}}if(r){let f=this.mri(D.slice(2));this.setParsedInfo(f)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),u=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),u=!1,this.unsetMatchedCommand();let A={args:this.args,options:this.options};if(u)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return A}mri(D,u){let r=[...this.globalCommand.options,...u?u.options:[]],A=rN(r),f=[],w=D.indexOf("--");if(w>-1)f=D.slice(w+1),D=D.slice(0,w);let F=DN(D,A);F=Object.keys(F).reduce((R,n)=>{return pf(pf({},R),{[GB(n)]:F[n]})},{_:[]});let E=F._,$={"--":f},g=u&&u.config.ignoreOptionDefaultValue?u.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,_=Object.create(null);for(let R of r){if(!g&&R.config.default!==void 0)for(let n of R.names)$[n]=R.config.default;if(Array.isArray(R.config.type)){if(_[R.name]===void 0)_[R.name]=Object.create(null),_[R.name].shouldTransform=!0,_[R.name].transformFunction=R.config.type[0]}}for(let R of Object.keys(F))if(R!=="_"){let n=R.split(".");fN($,n,F[R]),FN($,_)}return{args:E,options:$}}runMatchedCommand(){let{args:D,options:u,matchedCommand:r}=this;if(!r||!r.commandAction)return;r.checkUnknownOptions(),r.checkOptionValue(),r.checkRequiredArgs();let A=[];return r.args.forEach((f,w)=>{if(f.variadic)A.push(D.slice(w));else A.push(D[w])}),A.push(u),r.commandAction.apply(this,A)}}var gN=(D="")=>new HB(D),XB=gN;w3();var Pu={name:"@zonease/aiworker-cli",type:"module",version:"0.16.0",description:"AIWorker CLI \u2014 local Host and vertical Soul workspace runtime",license:"MIT",homepage:"https://github.com/ZonEaseTech/aiworker#readme",repository:{type:"git",url:"git+https://github.com/ZonEaseTech/aiworker.git"},publishConfig:{access:"public"},bin:{aiworker:"./dist/aiworker.js"},files:["README.md","dist/"],engines:{bun:">=1.1"},scripts:{typecheck:"tsc --noEmit",test:"bun test --timeout=15000","test:stress":"bun test --timeout=15000 --rerun-each=3 src/commands/worker/init.integration.test.ts src/commands/worker/sessions.test.ts",build:"bun run --filter '@zonease/aiworker-web' build && bun run build:bundle","build:bundle":"bun run --filter '@zonease/aiworker-hr' build && bun run --filter '@zonease/aiworker-qa' build && bun build --target=bun --minify --outfile=dist/aiworker-bun.js src/aiworker.ts && bun scripts/build-publish-manifest.ts",prepublishOnly:"bun run build","smoke:dist-release":"bun scripts/smoke-dist-release.ts"},devDependencies:{"@types/bun":"^1.2.13","@zonease/aiworker-api":"workspace:*","@zonease/aiworker-core":"workspace:*","@zonease/aiworker-fs-layout":"workspace:*","@zonease/aiworker-shared":"workspace:*","@zonease/aiworker-storage-sqlite":"workspace:*",cac:"^6.7.14",consola:"^3.4.2",typescript:"^5.8.3",yaml:"^2.7.1"}};import I1 from"process";var _W="@zonease/aiworker-cli",AL="https://registry.npmjs.org/@zonease%2Faiworker-cli",fL="https://api.github.com/repos/ZonEaseTech/aiworker/releases/latest";function e$(D,u){if(u.channel!==void 0&&u.channel!=="stable"&&u.channel!=="preview")throw Error(`unsupported update channel: ${u.channel}`);let r=u.pre===!0||u.channel==="preview",A=u.check===!0?"check":u.dryRun===!0?"dry-run":"apply";return{channel:r?"preview":"stable",command:D,mode:A,prerelease:r,target:u.target,yes:u.yes===!0}}function D7(D){let u=g3(D.argv1),r=g3(D.realArgv1),A=g3(D.moduleDir),f=[u,r,A].filter(Boolean).join(`
1719
+ `);if(A.includes("/apps/cli/src")||r.endsWith("/apps/cli/src/aiworker.ts"))return{canAutoUpgrade:!1,kind:"source-checkout",reason:"source checkout cannot self-modify"};if(f.includes("/.npm/_npx/")||f.includes("/.bun/install/cache/"))return{canAutoUpgrade:!1,kind:"ephemeral",reason:"ephemeral runner cache cannot be upgraded in place"};if(E3(u,D.npmGlobalBinDirs)||E3(r,D.npmGlobalBinDirs))return{canAutoUpgrade:!0,kind:"npm-global",packageManager:"npm"};if(E3(u,D.bunGlobalBinDirs)||E3(r,D.bunGlobalBinDirs))return{canAutoUpgrade:!0,kind:"bun-global",packageManager:"bun"};if(f.includes("/.bun/install/global/node_modules/@zonease/aiworker-cli"))return{canAutoUpgrade:!0,kind:"bun-global",packageManager:"bun"};if(f.includes("/lib/node_modules/@zonease/aiworker-cli"))return{canAutoUpgrade:!0,kind:"npm-global",packageManager:"npm"};if(A.includes("/aiworker-darwin-")||A.includes("/aiworker-linux-"))return{canAutoUpgrade:!0,kind:"github-tarball"};return{canAutoUpgrade:!1,kind:"unknown",reason:"installation source could not be proven"}}function u7(D){let u=[],r;if(SL(D.currentVersion,D.target.version)>=0)r="already_current";else if(D.source.kind==="unknown")r="source_unknown";else if(!D.source.canAutoUpgrade&&D.options.mode!=="check")r="source_not_supported";else if(D.source.kind==="github-tarball"&&D.options.mode!=="check"&&(!D.target.downloadUrl||!D.target.checksumUrl))r="source_not_supported";else r="update_available";if(r==="update_available"&&D.options.mode!=="check"){if(D.source.packageManager)u.push(wL(D.source.packageManager,D.target.version));else if(D.source.kind==="github-tarball"&&D.target.downloadUrl&&D.target.checksumUrl)u.push({checksumUrl:D.target.checksumUrl,downloadUrl:D.target.downloadUrl,kind:"github-tarball"});if(D.options.mode==="apply"&&u.length>0)u.push({kind:"host-convergence"},{kind:"daemon-restart"})}return{actions:u,currentVersion:D.currentVersion,mode:D.options.mode,requiresConfirmation:D.options.mode==="apply"&&u.length>0&&!D.options.yes,source:D.source,status:r,target:D.target,targetVersion:D.target.version}}async function r7(D){if(D.options.target)return{checksumUrl:null,downloadUrl:null,isPrerelease:D.options.prerelease,source:D.source.kind==="github-tarball"?"github":"npm",version:D.options.target};if(D.source.kind==="github-tarball"){let f=EL(await RW(D.fetch,fL)),w=(D.platformAssetName??FL)(),F=f.assets.find(($)=>$.name===w),E=f.assets.find(($)=>$.name===`${w}.sha256`);return{checksumUrl:nW(E,`${w}.sha256`),downloadUrl:nW(F,w),isPrerelease:D.options.prerelease,source:"github",version:f.tag_name.replace(/^v/,"")}}let u=$L(await RW(D.fetch,AL)),r=D.options.prerelease?"preview":"latest",A=u["dist-tags"]?.[r];if(typeof A!=="string"||A.length===0)throw Error(`npm dist-tag not found: ${r}`);return{checksumUrl:null,downloadUrl:null,isPrerelease:D.options.prerelease,source:"npm",version:A}}async function JW(D){if(D.plan.mode==="dry-run")return{completedActions:[],status:"dry_run"};if(D.plan.status!=="update_available"||D.plan.actions.length===0)return{completedActions:[],status:"skipped"};let u=[];for(let r of D.plan.actions){if(r.kind==="package-manager"){if(!r.command||!r.args)throw Error("package-manager upgrade action is missing command or args");await $3(D.runCommand,"runCommand")(r.command,r.args)}else if(r.kind==="github-tarball"){if(!r.downloadUrl||!r.checksumUrl)throw Error("github tarball upgrade action requires downloadUrl and checksumUrl");await $3(D.downloadAndReplace,"downloadAndReplace")({checksumUrl:r.checksumUrl,downloadUrl:r.downloadUrl})}else if(r.kind==="host-convergence")await $3(D.convergeHost,"convergeHost")();else await $3(D.restartDaemon,"restartDaemon")();u.push(r.kind)}return{completedActions:u,status:"completed"}}function GW(D,u){if(!D?.checkedAt)return{canCheck:!0,latestSeenVersion:D?.latestSeenVersion??null};let r=new Date(D.checkedAt),A=u.getTime()-r.getTime();return{canCheck:!Number.isFinite(r.getTime())||A<0||A>=86400000,latestSeenVersion:D.latestSeenVersion??null}}function FL(){let D=I1.platform==="win32"?"windows":I1.platform,u=I1.arch==="x64"?"x64":I1.arch==="arm64"?"arm64":I1.arch;return`aiworker-${D}-${u}.tar.gz`}function wL(D,u){if(D==="bun")return{args:["install","-g",`${_W}@${u}`],command:"bun",kind:"package-manager",packageManager:D};return{args:["install","-g",`${_W}@${u}`],command:"npm",kind:"package-manager",packageManager:D}}async function RW(D,u){let r=await(D??globalThis.fetch)(u);if(!r.ok)throw Error(`failed to resolve release target from ${u}: HTTP ${r.status}`);return await r.json()}function $L(D){if(!S3(D))return{};let u=D["dist-tags"];if(!S3(u))return{};return{"dist-tags":Object.fromEntries(Object.entries(u).filter((r)=>typeof r[1]==="string"))}}function EL(D){if(!S3(D)||typeof D.tag_name!=="string"||D.tag_name.length===0)throw Error("github release tag not found");if(!Array.isArray(D.assets))throw Error("github release assets invalid");return{assets:D.assets.filter(gL),tag_name:D.tag_name}}function gL(D){return S3(D)&&(D.name===void 0||typeof D.name==="string")}function nW(D,u){if(D===void 0)return null;if(typeof D.browser_download_url!=="string"||D.browser_download_url.trim().length===0)throw Error(`github release asset url invalid: ${u}`);return D.browser_download_url}function $3(D,u){if(D===void 0)throw Error(`upgrade executor hook missing: ${u}`);return D}function S3(D){return typeof D==="object"&&D!==null&&!Array.isArray(D)}function SL(D,u){let r=WW(D),A=WW(u);for(let f=0;f<3;f+=1){let w=r.core[f]??0,F=A.core[f]??0;if(w>F)return 1;if(w<F)return-1}return _L(r.prerelease,A.prerelease)}function E3(D,u){if(!D)return!1;return(u??[]).map(g3).some((r)=>{if(!r)return!1;return D===r||D.startsWith(`${r}/`)})}function g3(D){if(!D)return"";return D.replaceAll("\\","/").replace(/\/+/g,"/").replace(/\/$/,"")}function _L(D,u){if(D.length===0&&u.length===0)return 0;if(D.length===0)return 1;if(u.length===0)return-1;let r=Math.max(D.length,u.length);for(let A=0;A<r;A+=1){let f=D[A],w=u[A];if(f===void 0)return-1;if(w===void 0)return 1;let F=BW(f),E=BW(w);if(F!==void 0&&E!==void 0){if(F>E)return 1;if(F<E)return-1;continue}if(F!==void 0)return-1;if(E!==void 0)return 1;if(f>w)return 1;if(f<w)return-1}return 0}function BW(D){if(!/^\d+$/.test(D))return;return Number.parseInt(D,10)}function WW(D){let u=D.replace(/^v/,"").split("+",1)[0]??"",r=u.indexOf("-"),A=r===-1?u:u.slice(0,r),f=r===-1?void 0:u.slice(r+1);return{core:(A??"").split(".").slice(0,3).map((w)=>Number.parseInt(w,10)).map((w)=>Number.isFinite(w)?w:0),prerelease:f?f.split("."):[]}}var T=XB("aiworker"),p2=h.dirname(oq(import.meta.url)),YG="soul-app.manifest.json";function QG(D=p2){let u=h.resolve(D,"official-apps");if(cD(h.join(u,"aiworker-hr",YG)))return u;let r=h.resolve(D,"../../apps");if(cD(h.join(r,"aiworker-hr",YG)))return r;return}function dq(D=p2){let u=h.resolve(D,"web","worker");if(cD(h.join(u,"index.html")))return u;let r=h.resolve(D,"../../web/dist/worker");if(cD(h.join(r,"index.html")))return r;return}var lq=".aiworker-dev",yq=".aiworker";function cq(D=p2){let u=cD(h.join(D,"official-apps")),r=cD(h.join(D,"web","worker"));return u||r?yq:lq}function tq(D=p2){let u=h3({defaultHomeDir:cq(D)}).home;return{home:u,dbPath:a.env.WORKER_DB_PATH??h.join(u,"aiworker.db"),workersRoot:h.join(u,"workers"),pidFile:h.join(u,"aiworker-daemon.pid"),logFile:h.join(u,"aiworker-daemon.log")}}function pq(D){a.env.AIWORKER_HOME??=D.home,a.env.WORKER_DB_PATH??=D.dbPath}function x2(){let D=tq();return pq(D),D}async function SD(){let D=x2();return await UG(D.home,{recursive:!0}),await UG(h.dirname(D.dbPath),{recursive:!0}),WA(D.dbPath),JA(du().WORKER_MIGRATIONS_FOLDER),D}function xq(){let u=mr().find((r)=>r.key==="selected-worker")?.valueJson;return u&&typeof u.workerId==="string"?u.workerId:null}function s7(){return{hostVersion:Pu.version}}function tD(D,u={}){return M1({executor:u.executor,officialAppsRoot:u.officialAppsRoot??QG(),registryContext:u.registryContext??s7,workersRoot:D.workersRoot})}async function m2(D={}){let u=await SD(),r=D.worker??xq();if(!r)throw Error("worker is required; pass --worker or run `aiworker worker select <id>`");let A=PD(r);if(!A)throw Error(`worker not found: ${r}`);let f=tD(u).createRuntimeForWorker(A);return await f.init(),f}async function Vu(){return await SD(),gr()}function Z(D){a.stdout.write(`${JSON.stringify(D,null,2)}
1720
+ `)}function Ku(D,u){if(typeof D!=="string"||D.trim().length===0)throw Error(`${u} is required`);return D.trim()}function c2(D){let u=D?.[0];return typeof u==="number"&&Number.isFinite(u)?u:void 0}function mq(D){try{return a.kill(D,0),!0}catch{return!1}}async function aq(){let D=await SD();Z({home:D.home,dbPath:D.dbPath,workersRoot:D.workersRoot,workers:gr()})}async function eq(){let D=await SD(),u=await LG();Z({ok:!0,home:D.home,dbPath:D.dbPath,apps:tD(D).listApps(),workers:gr(),workspaces:Xu(),daemon:V3(),settings:mr(),updateNotice:u})}async function MG(D,u){let r=e$(D,u),A=z7(a.argv[1]),f=D7({argv1:A,bunGlobalBinDirs:bG(),moduleDir:p2,npmGlobalBinDirs:qG(),realArgv1:j7(A)}),w=await r7({fetch:($)=>fetch($),options:r,source:f}),F=u7({currentVersion:Pu.version,options:r,source:f,target:w});if(r.mode!=="apply"){Z({update:F});return}if(F.status==="source_not_supported"||F.status==="source_unknown")throw Z({update:F}),Error(`update_not_supported: ${F.source.detail??F.source.reason??F.source.kind}`);if(F.status==="update_available"&&F.actions.length===0)throw Z({update:F}),Error("update_not_actionable");if(F.status!=="update_available"){Z({update:F});return}if(F.requiresConfirmation)throw Z({update:F}),Error("update requires --yes to apply changes");let E=await JW({convergeHost:async()=>{await hb()},downloadAndReplace:async($)=>{await Db($)},plan:F,restartDaemon:async()=>{vr.info("AIWorker daemon requires manual restart after CLI upgrade")},runCommand:async($,g)=>{if(await Bun.spawn([$,...g],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited!==0)throw Error(`package manager upgrade failed: ${$} ${g.join(" ")}`)}});Z({update:F,result:E})}async function Db(D,u={}){let r=j7(z7(u.currentPath??a.argv[1]));if(!r)throw Error("current binary path is required");let A=u.renameSync??Tq,f=u.spawnSync??((B)=>Bun.spawnSync(B)),w=u.fetch??fetch,F=h.dirname(r),E=h.dirname(F),$=NG(h.join(E,".aiworker-update-")),g=h.join($,"aiworker.tar.gz"),_=h.join(E,`.aiworker-next-${a.pid}-${q7()}`),R=h.join(E,`.aiworker-backup-${a.pid}-${q7()}`),n=!1;try{let[B,C]=await Promise.all([rb(D.checksumUrl,w),ub(D.downloadUrl,w)]),J=B.trim().split(/\s+/)[0],X=KG("sha256").update(C).digest("hex");if(!J||X!==J)throw Error("checksum_mismatch");I3(g,C);let M=f(["tar","-xzf",g,"-C",$]);if(M.exitCode!==0){let Y=OG(M.stderr);throw Error(`staging_failed: ${Y||`tar exited ${M.exitCode}`}`)}let P=b7($).map((Y)=>h.join($,Y)).filter((Y)=>c1(Y).isDirectory()),k=P.find((Y)=>cD(h.join(Y,"aiworker")));if(!k)throw Error(P.length>0?"staging_failed: aiworker binary not found":"staging_failed: extracted directory not found");let s=h.join(k,"aiworker");if(!cD(s)||!c1(s).isFile())throw Error("staging_failed: aiworker binary not found");if(!cD(h.join(k,"web"))||!c1(h.join(k,"web")).isDirectory())throw Error("staging_failed: web assets not found");if(!cD(h.join(k,"drizzle"))||!c1(h.join(k,"drizzle")).isDirectory())throw Error("staging_failed: drizzle migrations not found");t0(_,{force:!0,recursive:!0}),t0(R,{force:!0,recursive:!0}),A(k,_),bq(h.join(_,"aiworker"),493);let q=f([h.join(_,"aiworker"),"--version"]);if(q.exitCode!==0){let Y=OG(q.stderr);throw Error(`staging_failed: version probe failed${Y?`: ${Y}`:""}`)}A(F,R);try{A(_,F)}catch(Y){throw A(R,F),Y}return n=!0,{backupPath:R,installedPath:r}}finally{if(t0($,{recursive:!0,force:!0}),!n)t0(_,{recursive:!0,force:!0})}}function OG(D){if(!D)return"";if(typeof D==="string")return D.trim();return IG.from(D.buffer,D.byteOffset,D.byteLength).toString("utf8").trim()}async function ub(D,u=fetch){let r=await u(D);if(!r.ok)throw Error(`update asset fetch failed: HTTP ${r.status}`);return IG.from(await r.arrayBuffer())}async function rb(D,u=fetch){let r=await u(D);if(!r.ok)throw Error(`update checksum fetch failed: HTTP ${r.status}`);return await r.text()}async function LG(){let D=new Date;try{await SD();let r=mr().find((g)=>g.key==="update.notice")?.valueJson??null,A=GW(r,D);if(!A.canCheck)return A.latestSeenVersion&&fb(A.latestSeenVersion,Pu.version)>0?{channel:"stable",command:"aiworker update",currentVersion:Pu.version,targetVersion:A.latestSeenVersion}:null;let f=e$("update",{check:!0,channel:"stable"}),w=z7(a.argv[1]),F=D7({argv1:w,bunGlobalBinDirs:bG(),moduleDir:p2,npmGlobalBinDirs:qG(),realArgv1:j7(w)}),E=await r7({fetch:(g)=>Ab(g),options:f,source:F}),$=u7({currentVersion:Pu.version,options:f,source:F,target:E});return k0("update.notice",{checkedAt:D.toISOString(),latestSeenVersion:E.version}),$.status==="update_available"?{channel:"stable",command:"aiworker update",currentVersion:Pu.version,targetVersion:E.version}:null}catch(u){let r=u instanceof Error?u.message:String(u);try{let A=mr().find((f)=>f.key==="update.notice")?.valueJson.latestSeenVersion;k0("update.notice",{checkedAt:D.toISOString(),errorMessage:r,latestSeenVersion:typeof A==="string"?A:Pu.version})}catch{}return null}}function qG(){return sG([a.env.npm_config_prefix?h.join(a.env.npm_config_prefix,"bin"):void 0,a.env.PREFIX?h.join(a.env.PREFIX,"bin"):void 0,"/usr/local/bin","/opt/homebrew/bin"])}function bG(){return sG([a.env.BUN_INSTALL?h.join(a.env.BUN_INSTALL,"bin"):void 0,a.env.HOME?h.join(a.env.HOME,".bun","bin"):void 0])}function sG(D){return[...new Set(D.filter((u)=>typeof u==="string"&&u.length>0).map((u)=>h.resolve(u)))]}function z7(D){return D?h.resolve(D):void 0}function j7(D){if(!D)return;try{return jq(D)}catch{return D}}async function Ab(D){let u=new AbortController,r=setTimeout(()=>u.abort(),750);try{return await fetch(D,{signal:u.signal})}finally{clearTimeout(r)}}function fb(D,u){let r=D.split(/[.-]/).map((w)=>Number.parseInt(w,10)||0),A=u.split(/[.-]/).map((w)=>Number.parseInt(w,10)||0),f=Math.max(r.length,A.length);for(let w=0;w<f;w++){let F=(r[w]??0)-(A[w]??0);if(F!==0)return F}return 0}function V3(){let D=x2();if(!cD(D.pidFile))return{pid:null,running:!1,logFile:D.logFile};let u=Number.parseInt(t2(D.pidFile,"utf8"),10);return{pid:Number.isFinite(u)?u:null,running:Number.isFinite(u)&&mq(u),logFile:D.logFile}}async function Fb(D={}){let u=x2();hG(u.home,{recursive:!0});let r=V3();if(r.running)throw Error(`daemon already running: pid=${r.pid}`);I3(u.logFile,"");let A=zq(u.logFile,"a"),f=VG(a.execPath,[h.resolve(a.argv[1]??"aiworker"),"daemon","foreground",...D.host?["--host",D.host]:[],...D.port?["--port",String(D.port)]:[]],{cwd:a.cwd(),detached:!0,env:{...a.env,AIWORKER_HOME:u.home,WORKER_DB_PATH:u.dbPath},stdio:["ignore",A,A]});if(f.unref(),sq(A),!f.pid)throw Error("daemon did not return a pid");I3(u.pidFile,String(f.pid)),Z({started:!0,pid:f.pid,logFile:u.logFile,url:`http://127.0.0.1:${D.port??du().PORT}`})}async function wb(){let D=x2(),u=V3();if(!u.pid||!u.running){t0(D.pidFile,{force:!0}),Z({stopped:!1,running:!1});return}a.kill(u.pid,"SIGTERM"),t0(D.pidFile,{force:!0}),Z({stopped:!0,pid:u.pid})}async function PG(D={}){x2();let u=await LG();if(u)vr.info(`[aiworker-daemon] update available: ${u.currentVersion} -> ${u.targetVersion}; run ${u.command}`);let{bootstrapWorkerApp:r}=await Promise.resolve().then(() => (iG(),XG)),{app:A,port:f}=await r({officialAppsRoot:QG(),runtimeVersion:Pu.version,webStaticDir:dq()}),w=du(),F=Bun.serve({fetch:A.fetch,hostname:D.host??w.AIWORKER_WORKER_HOST,idleTimeout:255,port:D.port??f});vr.success(`[aiworker-daemon] listening on http://${F.hostname}:${F.port}`),await new Promise((E)=>{let $=setInterval(()=>{return},60000),g=()=>{clearInterval($),F.stop(),E()};a.once("SIGINT",g),a.once("SIGTERM",g)})}async function $b(D={}){let u=du(),r=`http://${D.host??u.AIWORKER_WORKER_HOST}:${D.port??u.PORT}/health`,A=await fetch(r);Z({ok:A.ok,status:A.status,body:await A.json().catch(()=>null)})}async function Eb(D={}){let u=x2().logFile;if(!cD(u))return;let A=(await vq(u,"utf8")).split(/\r?\n/);a.stdout.write(`${A.slice(-(D.tail??80)).join(`
1721
1721
  `)}
1722
- `)}async function Nq(D){let u=await gD(),r=await lD(u).createSoulWorker({id:D.id,name:Vu(D.name,"name"),soulId:Vu(D.soul,"soul")});Z({worker:r.snapshot.worker})}async function Qq(D){await gD();let u=PD(D);if(!u)throw Error(`worker not found: ${D}`);Z({setting:k0("selected-worker",{workerId:u.id})})}async function Lq(D){let u=await p2({worker:D.worker});Z({workspace:await u.createWorkspace({name:Vu(D.name,"name")})})}async function qq(D){if(!D.worker){await gD(),Z({workspaces:nu()});return}let u=await p2({worker:D.worker});Z({workspaces:nu(u.workerId)})}async function bq(D){let u=await gD(),r=await p2({worker:D.worker}),A=Vu(D.workspace,"workspace"),f=pD(A);if(!f||f.workerId!==r.workerId)throw Error(`workspace not found for ${r.workerId}: ${A}`);let w=Vu(D.skill,"skill"),F=lD(u).requireCapabilityTemplateForWorker(r.workerId,w),E=await r.createSession({workspaceId:A,capabilityTemplateId:F.id,title:Vu(D.title,"title"),context:D.context??"",metadata:{inputHints:F.inputHints,outputKind:F.outputKind,reviewRubric:F.reviewRubric,skillName:F.name}}),$=Vu(D.input,"input");Z(await r.startTurn({sessionId:E.id,input:$,engineId:"codex",engineCommand:"codex",metadata:{inputHints:F.inputHints,outputKind:F.outputKind,reviewRubric:F.reviewRubric,skillName:F.name,executionMode:"local-cli"}}))}async function zq(D){await gD();let u=Vu(D.session,"session"),r=fu(u);if(!r)throw Error(`session not found: ${u}`);let A=await p2({worker:D.worker??r.workerId});Z(await A.startTurn({sessionId:u,input:Vu(D.input,"input"),engineId:"codex",engineCommand:"codex",metadata:{executionMode:"local-cli"}}))}async function jq(D){await Iu(),Z({sessions:tr(D.workspace)})}async function Tq(D){await Iu(),Z({session:fu(D),turns:gr(D)})}async function vq(D){await Iu(),Z({files:bu(D.workspace)})}async function sq(D,u){await gD();let r=Vu(u.workspace,"workspace"),A=pD(r);if(!A)throw Error(`workspace not found: ${r}`);let f=await p2({worker:u.worker??A.workerId});a.stdout.write(await f.files(r).read(D))}async function Zq(D,u){await gD();let r=xr(D);if(!r)throw Error(`artifact not found: ${D}`);let A=pD(r.workspaceId);if(!A)throw Error(`workspace not found for artifact: ${D}`);let w=(await p2({worker:u.worker??A.workerId})).files(A.id).resolve(r.path);Bun.spawn(["open",w]),Z({opened:w})}async function oq(D){await Iu(),Z({artifacts:Rr(D.workspace)})}async function dq(D){await Iu(),Z({reviews:A2(D.workspace)})}async function yq(D){await Iu();let u=Vu(D.workspace,"workspace"),r=mr({id:H7(),workspaceId:u,sourceReviewId:D.review??null,statement:Vu(D.statement,"statement"),evidenceJson:D.review?[{reviewId:D.review}]:[]});Z({lesson:r})}async function lq(){let D=await gD();Z({apps:lD(D).listApps()})}async function cq(D){let u=await gD();Z({app:lD(u).getApp(D)})}async function tq(D){let u=await gD();Z({app:await lD(u).installAppFromPath(D)})}async function xq(D){let u=await gD(),r=lD(u);Z({app:r.enableApp(D),catalog:r.listCatalog()})}async function mq(D){let u=await gD(),r=lD(u);Z({app:r.disableApp(D),catalog:r.listCatalog()})}async function pq(D){let u=await gD();Z({app:lD(u).healthcheckApp(D)})}async function aq(D){let u=await gD(),r=lD(u).getApp(D);Z({appId:D,permissions:r?.manifest.permissions??[]})}async function eq(D){let u=await gD();if(D!=="official")throw Error(`unsupported app bootstrap scope: ${D}`);let r=await lD(u).bootstrapOfficialSoulApps();if(Z({bootstrap:r,catalog:r.catalog}),r.status==="fail")a.exitCode=1}async function Db(){let D=await gD(),r=await lD(D).bootstrapOfficialSoulApps();if(r.status==="fail")throw Error("host convergence failed while bootstrapping official Soul Apps");return{bootstrap:r,home:D.home}}async function ub(D,u={}){let r=RD.parse(D),A=L.resolve(u.dir??r);if(ZD(A)&&n7(A).length>0)throw Error(`target directory is not empty: ${A}`);let f=$b(r),w=GC(r);ur(L.join(A,"soul-app.manifest.json"),`${JSON.stringify(f,null,2)}
1723
- `),ur(L.join(A,"package.json"),`${JSON.stringify(Rb(r),null,2)}
1724
- `),ur(L.join(A,"tsconfig.json"),`${JSON.stringify(Sb(),null,2)}
1725
- `),ur(L.join(A,"README.md"),Jb(r)),ur(L.join(A,"src/index.ts"),Wb()),ur(L.join(A,"src/standalone.ts"),Gb()),ur(L.join(A,"src/host-mounted.ts"),Cb()),ur(L.join(A,"schemas/brief.schema.json"),w),ur(L.join(A,"capabilities/brief/prompt.md"),Hb(r)),ur(L.join(A,"review/brief.md"),nb(r)),ur(L.join(A,"packs",r,"SOUL.md"),Ub(r)),Z({appId:r,files:["soul-app.manifest.json","package.json","tsconfig.json","README.md","src/index.ts","src/standalone.ts","src/host-mounted.ts","schemas/brief.schema.json","capabilities/brief/prompt.md","review/brief.md",`packs/${r}/SOUL.md`],next:[`cd ${A}`,"aiworker app validate .","aiworker app smoke ."],path:A})}async function rb(D){let u=CC(D);if(Z({validation:HC(u)}),u.status!=="pass")a.exitCode=1}async function Ab(D){let u=CC(D);if(u.status!=="pass"){Z({smoke:{status:"fail",validation:HC(u)}}),a.exitCode=1;return}let r=u.manifest;if(!r||!u.manifestPath)throw Error("Soul App validation passed without a parsed manifest.");let A=_C(L.join(Rq(),"aiworker-app-smoke-")),f=null;try{f=await gb(r,u.rootDir);let w=f.url?{...r,api:{...r.api,localService:{baseUrl:f.url,healthPath:r.api.localService?.healthPath??"/health"}}}:r;u2();let F={dbPath:L.join(A,"worker.db"),home:A,logFile:L.join(A,"aiworker-daemon.log"),pidFile:L.join(A,"aiworker-daemon.pid"),workersRoot:L.join(A,"workers")};W1(F.dbPath),G1();let E=[...w.connectors.required.map((i)=>i.id),...w.connectors.optional.map((i)=>i.id)],$=()=>({availableConnectorIds:E,enabledConnectorIds:w.connectors.required.map((i)=>i.id),hostVersion:Pu.version}),g=lD(F,{registryContext:$});g.installAppManifest({manifest:w,sourceKind:"manifest-path",sourceRef:u.manifestPath});let R=g.enableApp(w.id),S=g.listCatalog().templates.find((i)=>i.soulId===r.id);if(!S)throw Error(`No mounted capability template available for ${r.id}`);let B=lD(F,{executor:{async invoke(i){return{artifacts:[{content:`# ${r.name} smoke artifact
1726
-
1727
- ${i.prompt}`,kind:S.outputKind,path:`artifacts/${i.sessionId}/smoke.md`,title:`${r.name} Smoke Artifact`}],review:{findings:[{message:"Generated app smoke review created by Host runtime."}],risks:[],verdict:"needs_review"},summary:"Generated Soul App smoke completed."}}},registryContext:$}),{runtime:J}=await B.createSoulWorker({defaultEngineId:"smoke",id:`${r.id}-smoke-worker`,metadata:{description:r.description,domain:r.soul.domain,soulAppId:r.id},name:`${r.name} Smoke`,soulId:r.id}),H=await J.createWorkspace({name:`${r.name} Smoke Workspace`,type:r.workspaceTypes[0].id}),G=await J.createSession({capabilityTemplateId:S.id,context:"Validate generated Soul App through Host-mounted smoke.",metadata:{capabilityTemplateId:S.id,inputHints:S.inputHints,outputKind:S.outputKind,reviewRubric:S.reviewRubric,soulAppId:r.id,soulName:r.soul.name},title:`${r.name} Smoke Session`,workspaceId:H.id}),U=await J.startTurn({engineId:"smoke",input:"Create a reviewable smoke artifact.",metadata:{soulAppId:r.id},sessionId:G.id}),O=await Eb(r);Z({smoke:{appId:r.id,artifactCount:U.artifacts.length,hostedStatus:R.status,mounted:"pass",mountedService:f.status,mountedServiceHttpStatus:f.httpStatus,mountedServiceUrl:f.url,reviewStatus:U.review?.verdict??null,standalone:O.status,standaloneHttpStatus:O.httpStatus,standaloneUrl:O.url,status:"pass",workspaceId:H.id}})}finally{f?.stop(),u2(),c0(A,{recursive:!0,force:!0})}}var fb=["@zonease/aiworker-api","@zonease/aiworker-cli","@zonease/aiworker-core","@zonease/aiworker-fs-layout","@zonease/aiworker-shared","@zonease/aiworker-storage-sqlite","@zonease/aiworker-web"],Fb=["@zonease/aiworker-hr","@zonease/aiworker-qa"],wb="Soul Apps must use createSoulAppWebStorage(...) instead of raw browser Web Storage APIs.";function $b(D){let u=`/api/local/apps/${D}`,r={api:{entry:"./src/host-mounted.ts",localService:{command:["bun","src/host-mounted.ts"],healthPath:"/health"},routePrefix:u},artifactTypes:[{description:"Reviewable brief artifact for the starter Soul App.",id:"brief",name:"Brief",previewRef:"./src/index.ts",reviewPolicyRef:"./review/brief.md",schemaRef:"./schemas/brief.schema.json",schemaSha256:nC(GC(D)),version:"0.1.0"}],capabilities:[{artifactTypes:["brief"],description:"Create a source-backed starter brief.",id:"brief",name:"Brief",outputKind:"brief",packRefs:[D],promptRef:"./capabilities/brief/prompt.md",reviewRubricRef:"./review/brief.md",version:"0.1.0",workspaceTypes:["case"]}],compatibility:{host:{minVersion:Pu.version},sdk:{minVersion:"0.1.0"}},connectors:{optional:[],required:[]},description:`${D} starter Soul App for one vertical workspace, capability, artifact, and review policy.`,exports:{artifact:"./src/index.ts",connector:"./src/index.ts",lifecycle:"./src/index.ts",review:"./src/index.ts",runtime:"./src/index.ts",ui:"./src/index.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:D,memory:{admissionPolicy:"manual-review",namespace:D},modes:{hostMounted:{entry:"./src/host-mounted.ts",supported:!0},standalone:{entry:"./src/standalone.ts",supported:!0}},name:or(D),pack:{refs:[{id:D,ref:`./packs/${D}/SOUL.md`,source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped metadata for the starter workspace.",target:D},{action:"write",kind:"storage",reason:"Write app-scoped metadata for the starter workspace.",target:D},{action:"write",kind:"artifact",reason:"Create reviewable starter artifacts.",target:"brief"},{action:"create",kind:"review",reason:"Create starter review rubrics and findings.",target:"brief-review"},{action:"propose",kind:"memory",reason:"Propose reviewed lessons into the app namespace.",target:D},{action:"mount",kind:"ui",reason:"Mount starter workbench contributions.",target:`${D}-workbench`},{action:"serve",kind:"api",reason:"Serve app-scoped local API routes.",target:u}],protocol:"soul-app/v1",soul:{description:`${or(D)} vertical Soul for app-scoped workspaces and reviewable artifacts.`,domain:D,id:D,name:or(D),version:"0.1.0"},storage:{migrations:[],namespace:D},ui:{artifactPreviews:[{entry:"./src/index.ts",id:"brief-preview",label:"Brief preview",slot:"artifact-preview",target:"brief"}],panels:[{entry:"./src/index.ts",id:"brief-panel",label:"Brief panel",slot:"panel",surface:{entry:"/surfaces/panels/brief-panel",renderer:"host-descriptor",requiredPermissions:[`storage:read:${D}`],scope:"workspace"}}],reviewPanels:[{entry:"./src/index.ts",id:"brief-review-panel",label:"Brief review panel",slot:"review-panel"}],routes:[{entry:"./src/standalone.ts",id:"brief-home",label:or(D),path:`/${D}`,surface:{entry:"/surfaces/routes/brief-home",renderer:"host-descriptor",requiredPermissions:[`ui:mount:${D}-workbench`],scope:"app"}}],workspaceWidgets:[{entry:"./src/index.ts",id:"brief-widget",label:"Brief widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/brief-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"case"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["brief"],defaultCapabilityIds:["brief"],description:"Starter workspace for one app-scoped case.",id:"case",name:"Case"}]},A=RA(JSON.stringify(r),U7());if(A.status!=="ok")throw Error(A.error);return A.manifest}async function Eb(D){if(!D.modes.standalone.supported)return{httpStatus:null,status:"skip",url:null};let u=Bun.serve({fetch(){return new Response(["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">',`<title>${X3(D.name)}</title>`,"</head>",`<body data-soul-app-id="${X3(D.id)}">`,`<main><h1>${X3(D.name)}</h1><p>${X3(D.description)}</p></main>`,"</body>","</html>"].join(""),{headers:{"content-type":"text/html; charset=utf-8"}})},hostname:"127.0.0.1",port:0}),r=`http://127.0.0.1:${u.port}/`;try{let A=await fetch(r),f=await A.text();if(!A.ok||!f.includes(`data-soul-app-id="${D.id}"`))throw Error(`Standalone browser smoke failed for ${D.id}`);return{httpStatus:A.status,status:"pass",url:r}}finally{u.stop()}}async function gb(D,u){let r=D.api.localService;if(!D.modes.hostMounted.supported||!r?.command?.length||!u)return{httpStatus:null,status:"skip",stop:()=>{},url:null};let A=$C(r.command[0],r.command.slice(1),{cwd:L.resolve(u,r.cwd??"."),env:{...a.env,PORT:"0"},stdio:["ignore","pipe","pipe"]}),f=!1,w=()=>{if(!f)f=!0,A.kill()},F=await _b(A,w),E=new URL(r.healthPath,F),$=await fetch(E);if(!$.ok)throw w(),Error(`Mounted Soul App service healthcheck failed ${$.status}: ${E}`);return{httpStatus:$.status,status:"pass",stop:w,url:F}}async function _b(D,u){return await new Promise((r,A)=>{let f="",w=setTimeout(()=>{u(),A(Error("Timed out waiting for mounted Soul App service URL."))},5000);D.once("error",(F)=>{clearTimeout(w),A(F)}),D.stdout.on("data",(F)=>{f+=F.toString("utf8");let E=f.split(/\r?\n/).find(($)=>$.trim().startsWith("{"));if(!E)return;try{let $=JSON.parse(E);if(typeof $.url==="string"&&$.url.length>0)clearTimeout(w),r($.url)}catch{}}),D.stderr.on("data",(F)=>{f+=F.toString("utf8")}),D.once("exit",(F)=>{clearTimeout(w),A(Error(`Mounted Soul App service exited before readiness: ${F??"signal"}. ${f.trim()}`))})})}function Rb(D){return{name:`@aiworker-soul-app/${D}`,private:!0,scripts:{build:"bun build src/index.ts src/standalone.ts src/host-mounted.ts --outdir dist --target bun",dev:"bun src/standalone.ts --serve",serve:"bun src/host-mounted.ts",smoke:"aiworker app smoke .",test:"bun test",typecheck:"tsc --noEmit",validate:"aiworker app validate ."},type:"module",version:"0.1.0",dependencies:{"@zonease/aiworker-soul-app-sdk":"workspace:*"},devDependencies:{"@types/bun":"^1.2.13",typescript:"^5.8.3"}}}function Sb(){return{compilerOptions:{allowImportingTsExtensions:!0,module:"ESNext",moduleResolution:"Bundler",noEmit:!0,resolveJsonModule:!0,strict:!0,target:"ES2022"},include:["src/**/*.ts"]}}function Bb(D){return{$schema:"https://json-schema.org/draft/2020-12/schema",additionalProperties:!1,properties:{appId:{const:D},evidence:{items:{type:"string"},minItems:1,type:"array"},summary:{minLength:1,type:"string"}},required:["appId","summary","evidence"],title:`${or(D)} Brief`,type:"object"}}function GC(D){return`${JSON.stringify(Bb(D),null,2)}
1728
- `}function Jb(D){return[`# ${or(D)} Soul App`,"","This starter app stays inside the public Soul App SDK boundary.","It is a source-checkout preview scaffold: the generated package uses `workspace:*` while the SDK is still unpublished; replace `workspace:*` after the SDK is published.","","## Local Checks","","```bash","aiworker app validate .","aiworker app smoke .","```","","## Contribution Checklist","","- Keep app code on `@zonease/aiworker-soul-app-sdk`; do not import Host private packages.","- Keep storage permissions scoped to this app namespace.","- Add one artifact schema and one review policy for each new artifact type.","- Run PMA, focused tests, and code-review-graph before submitting Host changes.",""].join(`
1729
- `)}function Wb(){return`import type {
1722
+ `)}async function gb(D){let u=await SD(),r=await tD(u).createSoulWorker({id:D.id,name:Ku(D.name,"name"),soulId:Ku(D.soul,"soul")});Z({worker:r.snapshot.worker})}async function Sb(D){await SD();let u=PD(D);if(!u)throw Error(`worker not found: ${D}`);Z({setting:k0("selected-worker",{workerId:u.id})})}async function _b(D){let u=await m2({worker:D.worker});Z({workspace:await u.createWorkspace({name:Ku(D.name,"name")})})}async function Rb(D){if(!D.worker){await SD(),Z({workspaces:Xu()});return}let u=await m2({worker:D.worker});Z({workspaces:Xu(u.workerId)})}async function nb(D){let u=await SD(),r=await m2({worker:D.worker}),A=Ku(D.workspace,"workspace"),f=Du(A);if(!f||f.workerId!==r.workerId)throw Error(`workspace not found for ${r.workerId}: ${A}`);let w=Ku(D.skill,"skill"),F=tD(u).requireCapabilityTemplateForWorker(r.workerId,w),E=await r.createSession({workspaceId:A,capabilityTemplateId:F.id,title:Ku(D.title,"title"),context:D.context??"",metadata:{inputHints:F.inputHints,outputKind:F.outputKind,reviewRubric:F.reviewRubric,skillName:F.name}}),$=Ku(D.input,"input");Z(await r.startTurn({sessionId:E.id,input:$,engineId:"codex",engineCommand:"codex",metadata:{inputHints:F.inputHints,outputKind:F.outputKind,reviewRubric:F.reviewRubric,skillName:F.name,executionMode:"local-cli"}}))}async function Bb(D){await SD();let u=Ku(D.session,"session"),r=wu(u);if(!r)throw Error(`session not found: ${u}`);let A=await m2({worker:D.worker??r.workerId});Z(await A.startTurn({sessionId:u,input:Ku(D.input,"input"),engineId:"codex",engineCommand:"codex",metadata:{executionMode:"local-cli"}}))}async function Wb(D){await Vu(),Z({sessions:tr(D.workspace)})}async function Jb(D){await Vu(),Z({session:wu(D),turns:Sr(D)})}async function Gb(D){await Vu(),Z({files:zu(D.workspace)})}async function Cb(D,u){await SD();let r=Ku(u.workspace,"workspace"),A=Du(r);if(!A)throw Error(`workspace not found: ${r}`);let f=await m2({worker:u.worker??A.workerId});a.stdout.write(await f.files(r).read(D))}async function Hb(D,u){await SD();let r=pr(D);if(!r)throw Error(`artifact not found: ${D}`);let A=Du(r.workspaceId);if(!A)throw Error(`workspace not found for artifact: ${D}`);let w=(await m2({worker:u.worker??A.workerId})).files(A.id).resolve(r.path);Bun.spawn(["open",w]),Z({opened:w})}async function Xb(D){await Vu(),Z({artifacts:Rr(D.workspace)})}async function ib(D){await Vu(),Z({reviews:f2(D.workspace)})}async function Ub(D){await Vu();let u=Ku(D.workspace,"workspace"),r=xr({id:q7(),workspaceId:u,sourceReviewId:D.review??null,statement:Ku(D.statement,"statement"),evidenceJson:D.review?[{reviewId:D.review}]:[]});Z({lesson:r})}async function Yb(){let D=await SD();Z({apps:tD(D).listApps()})}async function Mb(D){let u=await SD();Z({app:tD(u).getApp(D)})}async function Ob(D){let u=await SD();Z({app:await tD(u).installAppFromPath(D)})}async function Pb(D){let u=await SD(),r=tD(u);Z({app:r.enableApp(D),catalog:r.listCatalog()})}async function kb(D){let u=await SD(),r=tD(u);Z({app:r.disableApp(D),catalog:r.listCatalog()})}async function Ib(D){let u=await SD();Z({app:tD(u).healthcheckApp(D)})}async function Vb(D){let u=await SD(),r=tD(u).getApp(D);Z({appId:D,permissions:r?.manifest.permissions??[]})}async function Kb(D){let u=await SD();if(D!=="official")throw Error(`unsupported app bootstrap scope: ${D}`);let r=await tD(u).bootstrapOfficialSoulApps();if(Z({bootstrap:r,catalog:r.catalog}),r.status==="fail")a.exitCode=1}async function hb(){let D=await SD(),r=await tD(D).bootstrapOfficialSoulApps();if(r.status==="fail")throw Error("host convergence failed while bootstrapping official Soul Apps");return{bootstrap:r,home:D.home}}async function Nb(D,u={}){let r=ED.parse(D),A=h.resolve(u.dir??r);if(cD(A)&&b7(A).length>0)throw Error(`target directory is not empty: ${A}`);let f=zb(r),w=zG(r);iD(h.join(A,"soul-app.manifest.json"),`${JSON.stringify(f,null,2)}
1723
+ `),iD(h.join(A,"package.json"),`${JSON.stringify(Zb(r),null,2)}
1724
+ `),iD(h.join(A,"tsconfig.json"),`${JSON.stringify(ob(),null,2)}
1725
+ `),iD(h.join(A,"README.md"),lb(r)),iD(h.join(A,"engine-assets/workspace/AGENTS.md"),yb(r)),iD(h.join(A,"engine-assets/workspace/CLAUDE.md"),`@AGENTS.md
1726
+ `),iD(h.join(A,"engine-assets/workspace/README.md"),cb(r)),iD(h.join(A,"engine-assets/workspace/.gitignore"),tb()),iD(h.join(A,"engine-assets/skills/brief/SKILL.md"),pb(r)),iD(h.join(A,"host-adapter/index.ts"),xb()),iD(h.join(A,"host-adapter/api.ts"),mb()),iD(h.join(A,"host-adapter/standalone/standalone.ts"),ab()),iD(h.join(A,"host-adapter/mounted/host-mounted.ts"),eb()),iD(h.join(A,"product/artifacts/schemas/brief.schema.json"),w),iD(h.join(A,"product/workflows/brief/prompt.md"),Ds(r)),iD(h.join(A,"product/workflows/brief/review.md"),kG(r)),iD(h.join(A,"product/reviews/brief.md"),kG(r)),iD(h.join(A,"product/profiles",r,"SOUL.md"),us(r)),iD(h.join(A,"product/web/artifact-previews/brief-preview.tsx"),y1("briefPreview")),iD(h.join(A,"product/web/panels/brief-panel.tsx"),y1("briefPanel")),iD(h.join(A,"product/web/panels/brief-review-panel.tsx"),y1("briefReviewPanel")),iD(h.join(A,"product/web/routes/brief-route.tsx"),y1("briefRoute")),iD(h.join(A,"product/web/widgets/brief-widget.tsx"),y1("briefWidget")),Z({appId:r,files:["soul-app.manifest.json","package.json","tsconfig.json","README.md","engine-assets/workspace/AGENTS.md","engine-assets/workspace/CLAUDE.md","engine-assets/workspace/README.md","engine-assets/workspace/.gitignore","engine-assets/skills/brief/SKILL.md","host-adapter/index.ts","host-adapter/api.ts","host-adapter/standalone/standalone.ts","host-adapter/mounted/host-mounted.ts","product/artifacts/schemas/brief.schema.json","product/workflows/brief/prompt.md","product/workflows/brief/review.md","product/reviews/brief.md",`product/profiles/${r}/SOUL.md`,"product/web/artifact-previews/brief-preview.tsx","product/web/panels/brief-panel.tsx","product/web/panels/brief-review-panel.tsx","product/web/routes/brief-route.tsx","product/web/widgets/brief-widget.tsx"],next:[`cd ${A}`,"aiworker app validate .","aiworker app smoke ."],path:A})}async function Qb(D){let u=jG(D);if(Z({validation:TG(u)}),u.status!=="pass")a.exitCode=1}async function Lb(D){let u=jG(D);if(u.status!=="pass"){Z({smoke:{status:"fail",validation:TG(u)}}),a.exitCode=1;return}let r=u.manifest;if(!r||!u.manifestPath)throw Error("Soul App validation passed without a parsed manifest.");let A=NG(h.join(Zq(),"aiworker-app-smoke-")),f=null;try{f=await Tb(r,u.rootDir);let w=f.url?{...r,api:{...r.api,localService:{baseUrl:f.url,healthPath:r.api.localService?.healthPath??"/health"}}}:r;r2();let F={dbPath:h.join(A,"worker.db"),home:A,logFile:h.join(A,"aiworker-daemon.log"),pidFile:h.join(A,"aiworker-daemon.pid"),workersRoot:h.join(A,"workers")};WA(F.dbPath),JA();let E=[...w.connectors.required.map((P)=>P.id),...w.connectors.optional.map((P)=>P.id)],$=()=>({availableConnectorIds:E,enabledConnectorIds:w.connectors.required.map((P)=>P.id),hostVersion:Pu.version}),g=tD(F,{registryContext:$});g.installAppManifest({manifest:w,sourceKind:"manifest-path",sourceRef:u.manifestPath});let _=g.enableApp(w.id),R=g.listCatalog().templates.find((P)=>P.soulId===r.id);if(!R)throw Error(`No mounted capability template available for ${r.id}`);let n=tD(F,{executor:{async invoke(P){return{artifacts:[{content:`# ${r.name} smoke artifact
1727
+
1728
+ ${P.prompt}`,kind:R.outputKind,path:`artifacts/${P.sessionId}/smoke.md`,title:`${r.name} Smoke Artifact`}],review:{findings:[{message:"Generated app smoke review created by Host runtime."}],risks:[],verdict:"needs_review"},summary:"Generated Soul App smoke completed."}}},registryContext:$}),{runtime:B}=await n.createSoulWorker({defaultEngineId:"smoke",id:`${r.id}-smoke-worker`,metadata:{description:r.description,domain:r.soul.domain,soulAppId:r.id},name:`${r.name} Smoke`,soulId:r.id}),C=await B.createWorkspace({name:`${r.name} Smoke Workspace`,type:r.workspaceTypes[0].id}),J=await B.createSession({capabilityTemplateId:R.id,context:"Validate generated Soul App through Host-mounted smoke.",metadata:{capabilityTemplateId:R.id,inputHints:R.inputHints,outputKind:R.outputKind,reviewRubric:R.reviewRubric,soulAppId:r.id,soulName:r.soul.name},title:`${r.name} Smoke Session`,workspaceId:C.id}),X=await B.startTurn({engineId:"smoke",input:"Create a reviewable smoke artifact.",metadata:{soulAppId:r.id},sessionId:J.id}),M=await jb(r);Z({smoke:{appId:r.id,artifactCount:X.artifacts.length,hostedStatus:_.status,mounted:"pass",mountedService:f.status,mountedServiceHttpStatus:f.httpStatus,mountedServiceUrl:f.url,reviewStatus:X.review?.verdict??null,standalone:M.status,standaloneHttpStatus:M.httpStatus,standaloneUrl:M.url,status:"pass",workspaceId:C.id}})}finally{f?.stop(),r2(),t0(A,{recursive:!0,force:!0})}}var qb=["@zonease/aiworker-api","@zonease/aiworker-cli","@zonease/aiworker-core","@zonease/aiworker-fs-layout","@zonease/aiworker-shared","@zonease/aiworker-storage-sqlite","@zonease/aiworker-web"],bb=["@zonease/aiworker-hr","@zonease/aiworker-qa"],sb="Soul Apps must use createSoulAppWebStorage(...) instead of raw browser Web Storage APIs.";function zb(D){let u=`/api/local/apps/${D}`,r={api:{entry:"./host-adapter/api.ts",localService:{command:["bun","host-adapter/mounted/host-mounted.ts"],healthPath:"/health"},routePrefix:u},artifactTypes:[{description:"Reviewable brief artifact for the starter Soul App.",id:"brief",name:"Brief",previewRef:"./product/web/artifact-previews/brief-preview.tsx",reviewPolicyRef:"./product/reviews/brief.md",schemaRef:"./product/artifacts/schemas/brief.schema.json",schemaSha256:vG(zG(D)),version:"0.1.0"}],capabilities:[{artifactTypes:["brief"],description:"Create a source-backed starter brief.",id:"brief",name:"Brief",outputKind:"brief",packRefs:[D],promptRef:"./product/workflows/brief/prompt.md",reviewRubricRef:"./product/workflows/brief/review.md",version:"0.1.0",workspaceTypes:["case"]}],compatibility:{host:{minVersion:Pu.version},sdk:{minVersion:"0.1.0"}},connectors:{optional:[],required:[]},description:`${D} starter Soul App for one vertical workspace, capability, artifact, and review policy.`,engineAssets:{skills:{source:"./engine-assets/skills",targets:["codex","claude-code"]},workspace:{source:"./engine-assets/workspace"}},exports:{artifact:"./host-adapter/index.ts",connector:"./host-adapter/index.ts",lifecycle:"./host-adapter/index.ts",review:"./host-adapter/index.ts",runtime:"./host-adapter/index.ts",ui:"./host-adapter/index.ts"},healthcheck:{kind:"protocol-handler",ref:"healthcheck",timeoutMs:5000},id:D,memory:{admissionPolicy:"manual-review",namespace:D},modes:{hostMounted:{entry:"./host-adapter/mounted/host-mounted.ts",supported:!0},standalone:{entry:"./host-adapter/standalone/standalone.ts",supported:!0}},name:hu(D),pack:{refs:[{id:D,ref:`./product/profiles/${D}/SOUL.md`,source:"embedded",version:"0.1.0"}]},permissions:[{action:"read",kind:"storage",reason:"Read app-scoped metadata for the starter workspace.",target:D},{action:"write",kind:"storage",reason:"Write app-scoped metadata for the starter workspace.",target:D},{action:"write",kind:"artifact",reason:"Create reviewable starter artifacts.",target:"brief"},{action:"create",kind:"review",reason:"Create starter review rubrics and findings.",target:"brief-review"},{action:"propose",kind:"memory",reason:"Propose reviewed lessons into the app namespace.",target:D},{action:"mount",kind:"ui",reason:"Mount starter workbench contributions.",target:`${D}-workbench`},{action:"serve",kind:"api",reason:"Serve app-scoped local API routes.",target:u}],protocol:"soul-app/v1",soul:{description:`${hu(D)} vertical Soul for app-scoped workspaces and reviewable artifacts.`,domain:D,id:D,name:hu(D),version:"0.1.0"},storage:{migrations:[],namespace:D},ui:{artifactPreviews:[{entry:"./product/web/artifact-previews/brief-preview.tsx",id:"brief-preview",label:"Brief preview",slot:"artifact-preview",target:"brief"}],panels:[{entry:"./product/web/panels/brief-panel.tsx",id:"brief-panel",label:"Brief panel",slot:"panel",surface:{entry:"/surfaces/panels/brief-panel",renderer:"host-descriptor",requiredPermissions:[`storage:read:${D}`],scope:"workspace"}}],reviewPanels:[{entry:"./product/web/panels/brief-review-panel.tsx",id:"brief-review-panel",label:"Brief review panel",slot:"review-panel"}],routes:[{entry:"./product/web/routes/brief-route.tsx",id:"brief-home",label:hu(D),path:`/${D}`,surface:{entry:"/surfaces/routes/brief-home",renderer:"host-descriptor",requiredPermissions:[`ui:mount:${D}-workbench`],scope:"app"}}],workspaceWidgets:[{entry:"./product/web/widgets/brief-widget.tsx",id:"brief-widget",label:"Brief widget",slot:"workspace-widget",surface:{entry:"/frames/widgets/brief-widget",renderer:"sandboxed-frame",scope:"workspace"},target:"case"}]},version:"0.1.0",workspaceTypes:[{artifactTypes:["brief"],defaultCapabilityIds:["brief"],description:"Starter workspace for one app-scoped case.",id:"case",name:"Case"}]},A=B1(JSON.stringify(r),s7());if(A.status!=="ok")throw Error(A.error);return A.manifest}async function jb(D){if(!D.modes.standalone.supported)return{httpStatus:null,status:"skip",url:null};let u=Bun.serve({fetch(){return new Response(["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">',`<title>${k3(D.name)}</title>`,"</head>",`<body data-soul-app-id="${k3(D.id)}">`,`<main><h1>${k3(D.name)}</h1><p>${k3(D.description)}</p></main>`,"</body>","</html>"].join(""),{headers:{"content-type":"text/html; charset=utf-8"}})},hostname:"127.0.0.1",port:0}),r=`http://127.0.0.1:${u.port}/`;try{let A=await fetch(r),f=await A.text();if(!A.ok||!f.includes(`data-soul-app-id="${D.id}"`))throw Error(`Standalone browser smoke failed for ${D.id}`);return{httpStatus:A.status,status:"pass",url:r}}finally{u.stop()}}async function Tb(D,u){let r=D.api.localService;if(!D.modes.hostMounted.supported||!r?.command?.length||!u)return{httpStatus:null,status:"skip",stop:()=>{},url:null};let A=VG(r.command[0],r.command.slice(1),{cwd:h.resolve(u,r.cwd??"."),env:{...a.env,PORT:"0"},stdio:["ignore","pipe","pipe"]}),f=!1,w=()=>{if(!f)f=!0,A.kill()},F=await vb(A,w),E=new URL(r.healthPath,F),$=await fetch(E);if(!$.ok)throw w(),Error(`Mounted Soul App service healthcheck failed ${$.status}: ${E}`);return{httpStatus:$.status,status:"pass",stop:w,url:F}}async function vb(D,u){return await new Promise((r,A)=>{let f="",w=setTimeout(()=>{u(),A(Error("Timed out waiting for mounted Soul App service URL."))},5000);D.once("error",(F)=>{clearTimeout(w),A(F)}),D.stdout.on("data",(F)=>{f+=F.toString("utf8");let E=f.split(/\r?\n/).find(($)=>$.trim().startsWith("{"));if(!E)return;try{let $=JSON.parse(E);if(typeof $.url==="string"&&$.url.length>0)clearTimeout(w),r($.url)}catch{}}),D.stderr.on("data",(F)=>{f+=F.toString("utf8")}),D.once("exit",(F)=>{clearTimeout(w),A(Error(`Mounted Soul App service exited before readiness: ${F??"signal"}. ${f.trim()}`))})})}function Zb(D){return{name:`@aiworker-soul-app/${D}`,private:!0,scripts:{build:"bun build host-adapter/index.ts host-adapter/standalone/standalone.ts host-adapter/mounted/host-mounted.ts --outdir dist --target bun",dev:"bun host-adapter/standalone/standalone.ts --serve",serve:"bun host-adapter/mounted/host-mounted.ts",smoke:"aiworker app smoke .",test:"bun test",typecheck:"tsc --noEmit",validate:"aiworker app validate ."},type:"module",version:"0.1.0",dependencies:{"@zonease/aiworker-soul-app-sdk":"workspace:*"},devDependencies:{"@types/bun":"^1.2.13",typescript:"^5.8.3"}}}function ob(){return{compilerOptions:{allowImportingTsExtensions:!0,module:"ESNext",moduleResolution:"Bundler",noEmit:!0,resolveJsonModule:!0,strict:!0,target:"ES2022"},include:["host-adapter/**/*.ts"]}}function db(D){return{$schema:"https://json-schema.org/draft/2020-12/schema",additionalProperties:!1,properties:{appId:{const:D},evidence:{items:{type:"string"},minItems:1,type:"array"},summary:{minLength:1,type:"string"}},required:["appId","summary","evidence"],title:`${hu(D)} Brief`,type:"object"}}function zG(D){return`${JSON.stringify(db(D),null,2)}
1729
+ `}function lb(D){return[`# ${hu(D)} Soul App`,"","This starter app stays inside the public Soul App SDK boundary.","It is a source-checkout preview scaffold: the generated package uses `workspace:*` while the SDK is still unpublished; replace `workspace:*` after the SDK is published.","","## Local Checks","","```bash","aiworker app validate .","aiworker app smoke .","```","","## Contribution Checklist","","- Keep app code on `@zonease/aiworker-soul-app-sdk`; do not import Host private packages.","- Keep storage permissions scoped to this app namespace.","- Add one artifact schema and one review policy for each new artifact type.","- Run PMA, focused tests, and code-review-graph before submitting Host changes.",""].join(`
1730
+ `)}function yb(D){return[`# ${hu(D)} Workspace Instructions`,"","This workspace belongs to an AIWorker Soul App.","Treat action-started sessions as explicit native skill selections.","Keep generated artifacts reviewable before they become accepted workspace state.",""].join(`
1731
+ `)}function cb(D){return["# {{workspaceName}}","",`Workspace for ${hu(D)}.`,""].join(`
1732
+ `)}function tb(){return[".aiworker/sessions/",".aiworker/projections.json","evidence/raw/",""].join(`
1733
+ `)}function pb(D){return["---","name: brief",`description: Create source-backed ${hu(D)} briefs.`,"---","","# Brief","","Create a concise, source-backed brief and surface missing evidence for human review.",""].join(`
1734
+ `)}function y1(D){return`export const ${D} = {
1735
+ renderer: 'host-descriptor',
1736
+ status: 'scaffold',
1737
+ }
1738
+ `}function xb(){return`import type {
1730
1739
  SoulAppArtifactValidationResult,
1731
1740
  SoulAppCapability,
1732
1741
  SoulAppProtocolResult,
@@ -1844,9 +1853,10 @@ function lifecycleHandlers(message: string) {
1844
1853
  upgrade: ok,
1845
1854
  }
1846
1855
  }
1847
- `}function Gb(){return`import process from 'node:process'
1856
+ `}function mb(){return`export { soulApp } from './index'
1857
+ `}function ab(){return`import process from 'node:process'
1848
1858
 
1849
- import manifestJson from '../soul-app.manifest.json' with { type: 'json' }
1859
+ import manifestJson from '../../soul-app.manifest.json' with { type: 'json' }
1850
1860
 
1851
1861
  const manifest = manifestJson
1852
1862
 
@@ -1884,9 +1894,9 @@ if (import.meta.main) {
1884
1894
  const server = serveStandalone()
1885
1895
  process.stdout.write(\`\${JSON.stringify({ appId: manifest.id, mode: 'standalone', url: \`http://\${server.hostname}:\${server.port}\` })}\\n\`)
1886
1896
  }
1887
- `}function Cb(){return`import process from 'node:process'
1897
+ `}function eb(){return`import process from 'node:process'
1888
1898
 
1889
- import manifestJson from '../soul-app.manifest.json' with { type: 'json' }
1899
+ import manifestJson from '../../soul-app.manifest.json' with { type: 'json' }
1890
1900
 
1891
1901
  const manifest = manifestJson
1892
1902
 
@@ -1964,9 +1974,9 @@ function verifyMountToken(request: Request): Response | null {
1964
1974
  ? null
1965
1975
  : Response.json({ error: { code: 'INVALID_MOUNT_TOKEN', message: 'Host mount token is required.' } }, { status: 401 })
1966
1976
  }
1967
- `}function Hb(D){return[`# ${or(D)} Brief Prompt`,"","Create a concise, source-backed business brief.","","- Cite evidence references provided by the Host or connector broker.","- Mark missing facts explicitly.","- Separate summary, risks, and next actions.",""].join(`
1968
- `)}function nb(D){return[`# ${or(D)} Brief Review`,"","- Evidence is cited and scoped to the workspace.","- Missing facts are explicit.","- Risks and next actions are separated.","- Memory candidates require human review before promotion.",""].join(`
1969
- `)}function Ub(D){return[`# ${or(D)} Soul Pack`,"","This pack describes the starter domain stance for the generated Soul App.","","- Keep work inside the app workspace.","- Produce reviewable artifacts, not generic chat output.","- Use brokered connectors and scoped storage only.",""].join(`
1970
- `)}function ur(D,u){gC(L.dirname(D),{recursive:!0}),Y3(D,u,{flag:"wx"})}function CC(D){let u=Xb(D);if(!u)return{appId:null,assetIssues:[],checkedAssets:[],manifestIssues:[{code:"missing_manifest",message:"Soul App manifest not found. Pass a manifest path or a directory containing soul-app.manifest.json.",severity:"error"}],manifestPath:null,privateImportIssues:[],rootDir:null,status:"fail",version:null,webStorageIssues:[]};let r=RA(t2(u.manifestPath,"utf8"),U7()),A=r.status==="ok"?[]:r.issues,f=r.status==="ok"?r.manifest:void 0,w=f?Yb(u.rootDir,f):{checkedAssets:[],issues:[]},F=Ob(u.rootDir),E=Pb(u.rootDir),$=f&&A.every((g)=>g.severity!=="error")&&w.issues.every((g)=>g.severity!=="error")&&F.length===0&&E.length===0?"pass":"fail";return{appId:f?.id??null,assetIssues:w.issues,checkedAssets:w.checkedAssets,manifest:f,manifestIssues:A,manifestPath:u.manifestPath,privateImportIssues:F,rootDir:u.rootDir,status:$,version:f?.version??null,webStorageIssues:E}}function HC(D){return{appId:D.appId,assetIssues:D.assetIssues,checkedAssets:D.checkedAssets,manifestIssues:D.manifestIssues,manifestPath:D.manifestPath,privateImportIssues:D.privateImportIssues,rootDir:D.rootDir,status:D.status,version:D.version,webStorageIssues:D.webStorageIssues}}function Xb(D){let u=L.resolve(D);if(!ZD(u))return null;let r=oA(u),A=r.isDirectory()?L.join(u,"soul-app.manifest.json"):u;if(!ZD(A))return null;return{manifestPath:A,rootDir:r.isDirectory()?u:L.dirname(A)}}function Yb(D,u){let r=Mb(u),A=[],f=[];for(let w of r){let F=L.resolve(D,w.path);if(A.push(w.path),!ZD(F)){f.push({code:"missing_asset",message:`Missing ${w.kind} asset: ${w.path}`,path:w.path,severity:"error"});continue}if(w.kind==="artifact-schema"){let E=t2(F,"utf8");try{JSON.parse(E)}catch($){f.push({code:"invalid_artifact_schema",message:`Artifact schema is not valid JSON: ${$ instanceof Error?$.message:String($)}`,path:w.path,severity:"error"})}}if(w.sha256){let E=nC(t2(F,"utf8"));if(E!==w.sha256)f.push({code:"asset_hash_mismatch",message:`${w.kind} SHA-256 mismatch for ${w.path}: expected ${w.sha256}, got ${E}`,path:w.path,severity:"error"})}}return{checkedAssets:[...new Set(A)].sort(),issues:f}}function nC(D){return EC("sha256").update(D).digest("hex")}function Mb(D){let u=[];for(let r of D.artifactTypes){if(u.push({kind:"artifact-schema",path:r.schemaRef,sha256:r.schemaSha256}),r.previewRef)u.push({kind:"artifact-preview",path:r.previewRef});if(r.reviewPolicyRef)u.push({kind:"review-policy",path:r.reviewPolicyRef})}for(let r of D.capabilities)if(u.push({kind:"capability-prompt",path:r.promptRef}),r.reviewRubricRef)u.push({kind:"capability-review",path:r.reviewRubricRef});for(let r of D.pack.refs)if(r.source!=="package")u.push({kind:"soul-pack",path:r.ref});for(let r of D.storage.migrations)u.push({kind:"storage-migration",path:r.path,sha256:r.sha256});for(let r of[...Object.values(D.exports),D.api.entry,D.modes.hostMounted.entry,D.modes.standalone.entry,...D.ui.routes.map((A)=>A.entry),...D.ui.panels.map((A)=>A.entry),...D.ui.artifactPreviews.map((A)=>A.entry),...D.ui.reviewPanels.map((A)=>A.entry),...(D.ui.workspaceWidgets??[]).map((A)=>A.entry)])if(r)u.push({kind:"entry",path:r});return u.filter((r,A,f)=>f.findIndex((w)=>w.kind===r.kind&&w.path===r.path)===A)}function Ob(D){let u=L.join(D,"src");if(!ZD(u))return[];let r=[];for(let A of M7(u)){let f=t2(A,"utf8");for(let w of Ib(f)){if(!Vb(D,w))continue;r.push({file:L.relative(D,A),importPath:w,message:"Soul Apps must use @zonease/aiworker-soul-app-sdk instead of Host private packages or sibling Soul Apps."})}}return r}function Pb(D){let u=L.join(D,"src");if(!ZD(u))return[];let r=[];for(let A of M7(u)){if(kb(A))continue;let f=t2(A,"utf8");for(let w of ib(f))r.push({file:L.relative(D,A),message:wb,symbol:w})}return r}function ib(D){let u=[],r=/\b(?:window\.)?(?:localStorage|sessionStorage)\.clear\s*\(/g;for(let f of D.matchAll(r))if(f.index!==void 0)u.push({index:f.index,symbol:f[0].replace(/\s*\($/,"")});let A=/\b(?:window\.)?(?:localStorage|sessionStorage)\b/g;for(let f of D.matchAll(A)){if(f.index===void 0)continue;let w=f[0];if(D.slice(f.index+w.length).match(/^\s*\.clear\s*\(/))continue;u.push({index:f.index,symbol:w})}return u.sort((f,w)=>f.index-w.index).filter((f,w,F)=>F.findIndex((E)=>E.index===f.index&&E.symbol===f.symbol)===w).map((f)=>f.symbol)}function kb(D){return/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(D)}function M7(D){let u=[];for(let r of n7(D,{withFileTypes:!0})){if(r.name==="node_modules"||r.name==="dist")continue;let A=L.join(D,r.name);if(r.isDirectory()){u.push(...M7(A));continue}if(/\.[cm]?[jt]sx?$/.test(r.name))u.push(A)}return u}function Ib(D){let u=[],r=[/\bfrom\s*['"]([^'"]+)['"]/g,/^\s*import\s*['"]([^'"]+)['"]/gm,/\b(?:import|require)\(\s*['"]([^'"]+)['"]\s*\)/g];for(let A of r)for(let f of D.matchAll(A)){let w=f[1];if(w)u.push(w)}return[...new Set(u)]}function Vb(D,u){if(fb.some((r)=>u===r||u.startsWith(`${r}/`)))return!0;if(Kb(D,u))return!0;return["apps/api","apps/cli","apps/web","packages/core","packages/fs-layout","packages/shared","packages/storage-sqlite"].some((r)=>u.includes(r))}function Kb(D,u){let r=L.basename(D),A=`@zonease/${r}`;if(Fb.some((w)=>w!==A&&(u===w||u.startsWith(`${w}/`))))return!0;if(!u.includes("apps/aiworker-"))return!1;return!u.replaceAll("\\\\","/").includes(`apps/${r}/`)}function or(D){return D.split("-").map((u)=>u?`${u[0].toUpperCase()}${u.slice(1)}`:"").join(" ")}function X3(D){return D.replace(/[&<>"']/g,(u)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[u]??u)}function hb(){v.command("init","initialize host-local AIWorker home and Soul workers").action(Xq),v.command("dev","run local daemon and hosted Worker Web in foreground").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>FC({host:D.host,port:c2(D.port)})),v.command("doctor","inspect host-local daemon readiness").action(Yq),v.command("update","check or apply an AIWorker CLI update").option("--check","check for updates without changing files").option("--dry-run","print planned update actions without applying them").option("--yes","confirm update application").option("--target <version>","explicit target version").option("--channel <channel>","release channel: stable or preview").option("--pre","use preview release channel").action((D)=>AC("update",D)),v.command("upgrade","alias for aiworker update").option("--check","check for updates without changing files").option("--dry-run","print planned update actions without applying them").option("--yes","confirm update application").option("--target <version>","explicit target version").option("--channel <channel>","release channel: stable or preview").option("--pre","use preview release channel").action((D)=>AC("upgrade",D)),v.command("daemon start","start local daemon in background").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>Iq({host:D.host,port:c2(D.port)})),v.command("daemon foreground","run local daemon in foreground").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>FC({host:D.host,port:c2(D.port)})),v.command("daemon status","show local daemon status").action(()=>Z(M3())),v.command("daemon stop","stop local daemon").action(Vq),v.command("daemon logs","show local daemon logs").option("--tail <n>","line count",{type:[Number]}).action((D)=>hq({tail:c2(D.tail)})),v.command("daemon check","check local daemon health").option("--host <host>","host").option("--port <n>","port",{type:[Number]}).action((D)=>Kq({host:D.host,port:c2(D.port)})),v.command("app list","list installed Host Soul Apps").action(lq),v.command("app show <id>","show one installed Host Soul App").action(cq),v.command("app install <manifest>","install a local Soul App manifest").action(tq),v.command("app enable <id>","enable an installed Soul App").action(xq),v.command("app disable <id>","disable an installed Soul App").action(mq),v.command("app doctor <id>","run static Soul App healthcheck").action(pq),v.command("app permissions <id>","show declared Soul App permissions").action(aq),v.command("app bootstrap <scope>","install and enable first-party Soul Apps by shortcut scope").action(eq),v.command("app create <id>","scaffold a minimal Soul App").option("--dir <path>","target directory").action(ub),v.command("app validate <path>","validate a Soul App manifest and app boundary").action(rb),v.command("app smoke <path>","run standalone and Host-mounted Soul App smoke checks").action(Ab),v.command("soul list","list installed app-projected vertical Souls").action(async()=>{let D=await gD();Z({souls:lD(D).listSouls()})}),v.command("worker create","create a local Soul worker").option("--id <id>","worker id").option("--name <text>","worker name").option("--soul <id>","Soul id").action(Nq),v.command("worker list","list local Soul workers").action(async()=>{await Iu(),Z({workers:Er()})}),v.command("worker show <id>","show one local Soul worker").action(async(D)=>{await gD(),Z({worker:PD(D)})}),v.command("worker select <id>","select default local Soul worker").action(Qq),v.command("template list","list capability templates").option("--soul <id>","Soul id").action(async(D)=>{let u=await gD(),r=lD(u).listCapabilityTemplates(D.soul);Z({templates:r})}),v.command("workspace create","create a worker workspace").option("--name <text>","workspace name").option("--worker <id>","worker id").action(Lq),v.command("workspace list","list worker workspaces").option("--worker <id>","worker id").action(qq),v.command("workspace show <id>","show one workspace").action(async(D)=>{await gD(),Z({workspace:pD(D)})}),v.command("session start","create a workspace session and first turn").option("--workspace <id>","workspace id").option("--skill <id>","capability template id").option("--title <text>","session title").option("--context <text>","session context").option("--input <text>","turn input").option("--worker <id>","worker id").action(bq),v.command("session list","list sessions").option("--workspace <id>","workspace id").action(jq),v.command("session show <id>","show one session").action(Tq),v.command("turn send","send a turn to an existing session").option("--session <id>","session id").option("--input <text>","turn input").option("--worker <id>","worker id").action(zq),v.command("files list","list workspace files").option("--workspace <id>","workspace id").action(vq),v.command("files show <path>","print workspace file").option("--workspace <id>","workspace id").option("--worker <id>","worker id").action(sq),v.command("artifacts list","list artifacts").option("--workspace <id>","workspace id").action(oq),v.command("artifacts show <id>","show one artifact").action(async(D)=>{await Iu(),Z({artifact:xr(D)})}),v.command("artifacts open <id>","open one artifact").option("--worker <id>","worker id").action(Zq),v.command("review list","list reviews").option("--workspace <id>","workspace id").action(dq),v.command("review show <id>","show one review").action(async(D)=>{await Iu(),Z({review:H1(D)})}),v.command("lessons list","list lessons").option("--workspace <id>","workspace id").action(async(D)=>{await Iu(),Z({lessons:f2(D.workspace)})}),v.command("lessons propose","propose a lesson").option("--statement <text>","lesson statement").option("--review <id>","source review id").option("--workspace <id>","workspace id").action(yq),v.command("lessons accept <id>","accept a lesson").action(async(D)=>{await Iu(),Z({lesson:n1(D,"accepted")})}),v.command("lessons reject <id>","reject a lesson").action(async(D)=>{await Iu(),Z({lesson:n1(D,"rejected")})}),v.command("settings list","list host daemon settings").action(async()=>{await gD(),Z({settings:pr()})}),v.command("engine select <engine>","set engine hint").action(async(D)=>{await gD(),Z({setting:k0("engine.default",{engine:D})})}),v.command("open","open local daemon Web app").option("--port <n>","web port",{type:[Number]}).action((D)=>{let r=`http://127.0.0.1:${c2(D.port)??Zu().PORT}`;Bun.spawn(["open",r]),Z({opened:r})}),v.command("commands","show command index").action(()=>{a.stdout.write(`${Nb()}
1971
- `)})}function Nb(){return["aiworker command index","init","dev","update|upgrade","daemon start|foreground|status|stop|logs|check","app list|show|install|enable|disable|doctor|permissions|bootstrap|create|validate|smoke","soul list","worker create|list|show|select","template list","workspace create|list|show","session start|list|show","turn send","files list|show","artifacts list|show|open","review list|show","lessons list|propose|accept|reject","settings list","engine select","open"].join(`
1972
- `)}hb();v.help();v.version(Pu.version);function Qb(D,u=v.commands.map((r)=>r.name)){let r=new Set(u.filter((f)=>f.includes(" "))),A=Math.max(1,...[...r].map((f)=>f.split(" ").length));for(let f=A;f>=2;f--){let w=D.slice(2,2+f).join(" ");if(r.has(w)){let F=D.slice();return F.splice(2,f,w),F}}return D}async function Lb(D=a.argv){try{a.exitCode=0,v.unsetMatchedCommand();let u=v.parse(Qb(D),{run:!1});if(v.options.help===!0||v.options.version===!0)return 0;if(!v.matchedCommand&&u.args[0])throw Error(`Unknown command: ${u.args[0]}`);await v.runMatchedCommand();let r=typeof a.exitCode==="number"?a.exitCode:0;return a.exitCode=0,r}catch(u){return vr.error(u instanceof Error?u.message:String(u)),a.exitCode=0,1}finally{u2()}}if(import.meta.main)a.exit(await Lb(a.argv));export{Lb as runCli,Bq as resolveCliWorkerWebStaticDir,RC as resolveCliOfficialAppsRoot,Cq as resolveCliLocalPaths,Gq as resolveCliDefaultHomeDir,Qb as preprocessArgv,Mq as downloadAndReplaceGitHubBundle,Db as convergeHostAfterCliUpgrade};
1977
+ `}function Ds(D){return[`# ${hu(D)} Brief Prompt`,"","Create a concise, source-backed business brief.","","- Cite evidence references provided by the Host or connector broker.","- Mark missing facts explicitly.","- Separate summary, risks, and next actions.",""].join(`
1978
+ `)}function kG(D){return[`# ${hu(D)} Brief Review`,"","- Evidence is cited and scoped to the workspace.","- Missing facts are explicit.","- Risks and next actions are separated.","- Memory candidates require human review before promotion.",""].join(`
1979
+ `)}function us(D){return[`# ${hu(D)} Soul Pack`,"","This pack describes the starter domain stance for the generated Soul App.","","- Keep work inside the app workspace.","- Produce reviewable artifacts, not generic chat output.","- Use brokered connectors and scoped storage only.",""].join(`
1980
+ `)}function iD(D,u){hG(h.dirname(D),{recursive:!0}),I3(D,u,{flag:"wx"})}function jG(D){let u=rs(D);if(!u)return{appId:null,assetIssues:[],checkedAssets:[],manifestIssues:[{code:"missing_manifest",message:"Soul App manifest not found. Pass a manifest path or a directory containing soul-app.manifest.json.",severity:"error"}],manifestPath:null,privateImportIssues:[],rootDir:null,status:"fail",version:null,webStorageIssues:[]};let r=B1(t2(u.manifestPath,"utf8"),s7()),A=r.status==="ok"?[]:r.issues,f=r.status==="ok"?r.manifest:void 0,w=f?As(u.rootDir,f):{checkedAssets:[],issues:[]},F=Fs(u.rootDir),E=ws(u.rootDir),$=f&&A.every((g)=>g.severity!=="error")&&w.issues.every((g)=>g.severity!=="error")&&F.length===0&&E.length===0?"pass":"fail";return{appId:f?.id??null,assetIssues:w.issues,checkedAssets:w.checkedAssets,manifest:f,manifestIssues:A,manifestPath:u.manifestPath,privateImportIssues:F,rootDir:u.rootDir,status:$,version:f?.version??null,webStorageIssues:E}}function TG(D){return{appId:D.appId,assetIssues:D.assetIssues,checkedAssets:D.checkedAssets,manifestIssues:D.manifestIssues,manifestPath:D.manifestPath,privateImportIssues:D.privateImportIssues,rootDir:D.rootDir,status:D.status,version:D.version,webStorageIssues:D.webStorageIssues}}function rs(D){let u=h.resolve(D);if(!cD(u))return null;let r=c1(u),A=r.isDirectory()?h.join(u,"soul-app.manifest.json"):u;if(!cD(A))return null;return{manifestPath:A,rootDir:r.isDirectory()?u:h.dirname(A)}}function As(D,u){let r=fs(u),A=[],f=[];for(let w of r){let F=h.resolve(D,w.path);if(A.push(w.path),!cD(F)){f.push({code:"missing_asset",message:`Missing ${w.kind} asset: ${w.path}`,path:w.path,severity:"error"});continue}if(w.kind==="artifact-schema"){let E=t2(F,"utf8");try{JSON.parse(E)}catch($){f.push({code:"invalid_artifact_schema",message:`Artifact schema is not valid JSON: ${$ instanceof Error?$.message:String($)}`,path:w.path,severity:"error"})}}if(w.sha256){let E=vG(t2(F,"utf8"));if(E!==w.sha256)f.push({code:"asset_hash_mismatch",message:`${w.kind} SHA-256 mismatch for ${w.path}: expected ${w.sha256}, got ${E}`,path:w.path,severity:"error"})}}return{checkedAssets:[...new Set(A)].sort(),issues:f}}function vG(D){return KG("sha256").update(D).digest("hex")}function fs(D){let u=[];if(u.push({kind:"engine-assets-workspace",path:D.engineAssets.workspace.source}),D.engineAssets.skills)u.push({kind:"engine-assets-skills",path:D.engineAssets.skills.source});for(let r of D.engineAssets.mcpClients??[])u.push({kind:"engine-assets-mcp-client",path:r.source});for(let r of D.artifactTypes){if(u.push({kind:"artifact-schema",path:r.schemaRef,sha256:r.schemaSha256}),r.previewRef)u.push({kind:"artifact-preview",path:r.previewRef});if(r.reviewPolicyRef)u.push({kind:"review-policy",path:r.reviewPolicyRef})}for(let r of D.capabilities)if(u.push({kind:"capability-prompt",path:r.promptRef}),r.reviewRubricRef)u.push({kind:"capability-review",path:r.reviewRubricRef});for(let r of D.pack.refs)if(r.source!=="package")u.push({kind:"soul-pack",path:r.ref});for(let r of D.storage.migrations)u.push({kind:"storage-migration",path:r.path,sha256:r.sha256});for(let r of[...Object.values(D.exports),D.api.entry,D.modes.hostMounted.entry,D.modes.standalone.entry,...D.ui.routes.map((A)=>A.entry),...D.ui.panels.map((A)=>A.entry),...D.ui.artifactPreviews.map((A)=>A.entry),...D.ui.reviewPanels.map((A)=>A.entry),...(D.ui.workspaceWidgets??[]).map((A)=>A.entry)])if(r)u.push({kind:"entry",path:r});return u.filter((r,A,f)=>f.findIndex((w)=>w.kind===r.kind&&w.path===r.path)===A)}function Fs(D){let u=[];for(let r of ZG(D))for(let A of T7(r)){let f=t2(A,"utf8");for(let w of gs(f)){if(!Ss(D,w))continue;u.push({file:h.relative(D,A),importPath:w,message:"Soul Apps must use @zonease/aiworker-soul-app-sdk instead of Host private packages or sibling Soul Apps."})}}return u}function ws(D){let u=[];for(let r of ZG(D))for(let A of T7(r)){if(Es(A))continue;let f=t2(A,"utf8");for(let w of $s(f))u.push({file:h.relative(D,A),message:sb,symbol:w})}return u}function ZG(D){return["host-adapter","product","src"].map((u)=>h.join(D,u)).filter((u)=>cD(u))}function $s(D){let u=[],r=/\b(?:window\.)?(?:localStorage|sessionStorage)\.clear\s*\(/g;for(let f of D.matchAll(r))if(f.index!==void 0)u.push({index:f.index,symbol:f[0].replace(/\s*\($/,"")});let A=/\b(?:window\.)?(?:localStorage|sessionStorage)\b/g;for(let f of D.matchAll(A)){if(f.index===void 0)continue;let w=f[0];if(D.slice(f.index+w.length).match(/^\s*\.clear\s*\(/))continue;u.push({index:f.index,symbol:w})}return u.sort((f,w)=>f.index-w.index).filter((f,w,F)=>F.findIndex((E)=>E.index===f.index&&E.symbol===f.symbol)===w).map((f)=>f.symbol)}function Es(D){return/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(D)}function T7(D){let u=[];for(let r of b7(D,{withFileTypes:!0})){if(r.name==="node_modules"||r.name==="dist")continue;let A=h.join(D,r.name);if(r.isDirectory()){u.push(...T7(A));continue}if(/\.[cm]?[jt]sx?$/.test(r.name))u.push(A)}return u}function gs(D){let u=[],r=[/\bfrom\s*['"]([^'"]+)['"]/g,/^\s*import\s*['"]([^'"]+)['"]/gm,/\b(?:import|require)\(\s*['"]([^'"]+)['"]\s*\)/g];for(let A of r)for(let f of D.matchAll(A)){let w=f[1];if(w)u.push(w)}return[...new Set(u)]}function Ss(D,u){if(qb.some((r)=>u===r||u.startsWith(`${r}/`)))return!0;if(_s(D,u))return!0;return["apps/api","apps/cli","apps/web","packages/core","packages/fs-layout","packages/shared","packages/storage-sqlite"].some((r)=>u.includes(r))}function _s(D,u){let r=h.basename(D),A=`@zonease/${r}`;if(bb.some((w)=>w!==A&&(u===w||u.startsWith(`${w}/`))))return!0;if(!u.includes("apps/aiworker-"))return!1;return!u.replaceAll("\\\\","/").includes(`apps/${r}/`)}function hu(D){return D.split("-").map((u)=>u?`${u[0].toUpperCase()}${u.slice(1)}`:"").join(" ")}function k3(D){return D.replace(/[&<>"']/g,(u)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[u]??u)}function Rs(){T.command("init","initialize host-local AIWorker home and Soul workers").action(aq),T.command("dev","run local daemon and hosted Worker Web in foreground").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>PG({host:D.host,port:c2(D.port)})),T.command("doctor","inspect host-local daemon readiness").action(eq),T.command("update","check or apply an AIWorker CLI update").option("--check","check for updates without changing files").option("--dry-run","print planned update actions without applying them").option("--yes","confirm update application").option("--target <version>","explicit target version").option("--channel <channel>","release channel: stable or preview").option("--pre","use preview release channel").action((D)=>MG("update",D)),T.command("upgrade","alias for aiworker update").option("--check","check for updates without changing files").option("--dry-run","print planned update actions without applying them").option("--yes","confirm update application").option("--target <version>","explicit target version").option("--channel <channel>","release channel: stable or preview").option("--pre","use preview release channel").action((D)=>MG("upgrade",D)),T.command("daemon start","start local daemon in background").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>Fb({host:D.host,port:c2(D.port)})),T.command("daemon foreground","run local daemon in foreground").option("--host <host>","bind host").option("--port <n>","port",{type:[Number]}).action((D)=>PG({host:D.host,port:c2(D.port)})),T.command("daemon status","show local daemon status").action(()=>Z(V3())),T.command("daemon stop","stop local daemon").action(wb),T.command("daemon logs","show local daemon logs").option("--tail <n>","line count",{type:[Number]}).action((D)=>Eb({tail:c2(D.tail)})),T.command("daemon check","check local daemon health").option("--host <host>","host").option("--port <n>","port",{type:[Number]}).action((D)=>$b({host:D.host,port:c2(D.port)})),T.command("app list","list installed Host Soul Apps").action(Yb),T.command("app show <id>","show one installed Host Soul App").action(Mb),T.command("app install <manifest>","install a local Soul App manifest").action(Ob),T.command("app enable <id>","enable an installed Soul App").action(Pb),T.command("app disable <id>","disable an installed Soul App").action(kb),T.command("app doctor <id>","run static Soul App healthcheck").action(Ib),T.command("app permissions <id>","show declared Soul App permissions").action(Vb),T.command("app bootstrap <scope>","install and enable first-party Soul Apps by shortcut scope").action(Kb),T.command("app create <id>","scaffold a minimal Soul App").option("--dir <path>","target directory").action(Nb),T.command("app validate <path>","validate a Soul App manifest and app boundary").action(Qb),T.command("app smoke <path>","run standalone and Host-mounted Soul App smoke checks").action(Lb),T.command("soul list","list installed app-projected vertical Souls").action(async()=>{let D=await SD();Z({souls:tD(D).listSouls()})}),T.command("worker create","create a local Soul worker").option("--id <id>","worker id").option("--name <text>","worker name").option("--soul <id>","Soul id").action(gb),T.command("worker list","list local Soul workers").action(async()=>{await Vu(),Z({workers:gr()})}),T.command("worker show <id>","show one local Soul worker").action(async(D)=>{await SD(),Z({worker:PD(D)})}),T.command("worker select <id>","select default local Soul worker").action(Sb),T.command("template list","list capability templates").option("--soul <id>","Soul id").action(async(D)=>{let u=await SD(),r=tD(u).listCapabilityTemplates(D.soul);Z({templates:r})}),T.command("workspace create","create a worker workspace").option("--name <text>","workspace name").option("--worker <id>","worker id").action(_b),T.command("workspace list","list worker workspaces").option("--worker <id>","worker id").action(Rb),T.command("workspace show <id>","show one workspace").action(async(D)=>{await SD(),Z({workspace:Du(D)})}),T.command("session start","create a workspace session and first turn").option("--workspace <id>","workspace id").option("--skill <id>","capability template id").option("--title <text>","session title").option("--context <text>","session context").option("--input <text>","turn input").option("--worker <id>","worker id").action(nb),T.command("session list","list sessions").option("--workspace <id>","workspace id").action(Wb),T.command("session show <id>","show one session").action(Jb),T.command("turn send","send a turn to an existing session").option("--session <id>","session id").option("--input <text>","turn input").option("--worker <id>","worker id").action(Bb),T.command("files list","list workspace files").option("--workspace <id>","workspace id").action(Gb),T.command("files show <path>","print workspace file").option("--workspace <id>","workspace id").option("--worker <id>","worker id").action(Cb),T.command("artifacts list","list artifacts").option("--workspace <id>","workspace id").action(Xb),T.command("artifacts show <id>","show one artifact").action(async(D)=>{await Vu(),Z({artifact:pr(D)})}),T.command("artifacts open <id>","open one artifact").option("--worker <id>","worker id").action(Hb),T.command("review list","list reviews").option("--workspace <id>","workspace id").action(ib),T.command("review show <id>","show one review").action(async(D)=>{await Vu(),Z({review:CA(D)})}),T.command("lessons list","list lessons").option("--workspace <id>","workspace id").action(async(D)=>{await Vu(),Z({lessons:F2(D.workspace)})}),T.command("lessons propose","propose a lesson").option("--statement <text>","lesson statement").option("--review <id>","source review id").option("--workspace <id>","workspace id").action(Ub),T.command("lessons accept <id>","accept a lesson").action(async(D)=>{await Vu(),Z({lesson:HA(D,"accepted")})}),T.command("lessons reject <id>","reject a lesson").action(async(D)=>{await Vu(),Z({lesson:HA(D,"rejected")})}),T.command("settings list","list host daemon settings").action(async()=>{await SD(),Z({settings:mr()})}),T.command("engine select <engine>","set engine hint").action(async(D)=>{await SD(),Z({setting:k0("engine.default",{engine:D})})}),T.command("open","open local daemon Web app").option("--port <n>","web port",{type:[Number]}).action((D)=>{let r=`http://127.0.0.1:${c2(D.port)??du().PORT}`;Bun.spawn(["open",r]),Z({opened:r})}),T.command("commands","show command index").action(()=>{a.stdout.write(`${ns()}
1981
+ `)})}function ns(){return["aiworker command index","init","dev","update|upgrade","daemon start|foreground|status|stop|logs|check","app list|show|install|enable|disable|doctor|permissions|bootstrap|create|validate|smoke","soul list","worker create|list|show|select","template list","workspace create|list|show","session start|list|show","turn send","files list|show","artifacts list|show|open","review list|show","lessons list|propose|accept|reject","settings list","engine select","open"].join(`
1982
+ `)}Rs();T.help();T.version(Pu.version);function Bs(D,u=T.commands.map((r)=>r.name)){let r=new Set(u.filter((f)=>f.includes(" "))),A=Math.max(1,...[...r].map((f)=>f.split(" ").length));for(let f=A;f>=2;f--){let w=D.slice(2,2+f).join(" ");if(r.has(w)){let F=D.slice();return F.splice(2,f,w),F}}return D}async function Ws(D=a.argv){try{a.exitCode=0,T.unsetMatchedCommand();let u=T.parse(Bs(D),{run:!1});if(T.options.help===!0||T.options.version===!0)return 0;if(!T.matchedCommand&&u.args[0])throw Error(`Unknown command: ${u.args[0]}`);await T.runMatchedCommand();let r=typeof a.exitCode==="number"?a.exitCode:0;return a.exitCode=0,r}catch(u){return vr.error(u instanceof Error?u.message:String(u)),a.exitCode=0,1}finally{r2()}}if(import.meta.main)a.exit(await Ws(a.argv));export{Ws as runCli,dq as resolveCliWorkerWebStaticDir,QG as resolveCliOfficialAppsRoot,tq as resolveCliLocalPaths,cq as resolveCliDefaultHomeDir,Bs as preprocessArgv,Db as downloadAndReplaceGitHubBundle,hb as convergeHostAfterCliUpgrade};