fimo 0.21.0-staging.3 → 0.21.0-staging.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
39
39
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process9.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process9.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path52.basename(filename,path52.extname(filename)),this}executableDir(path53){return path53===void 0?this._executableDir:(this._executableDir=path53,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process9.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
41
41
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
42
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium","Pro"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});import{z as z5}from"zod";var MB,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z5.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z5.object({renderId:z5.uuid(),filename:z5.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z5.url()}),AttachmentModelRenderSuccessSchema=z5.object({status:z5.literal("succeeded"),views:z5.tuple([z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z5.url()})]),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative(),diagnostics:z5.unknown().optional()}),AttachmentModelRenderFailureSchema=z5.object({status:z5.literal("failed"),error:z5.literal("render_failed"),message:z5.string(),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative()}),AttachmentModelRenderResponseSchema=z5.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z5.object({browserElapsedMs:z5.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z6}from"zod";var AssetReadRequestSchema,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema=z6.object({cursor:z6.string().optional(),query:z6.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z6.object({url:z6.url(),mediaType:z6.string(),filename:z6.string()}),AssetReadBaseSchema=z6.object({assetId:z6.uuid(),filename:z6.string(),mediaType:z6.string(),representation:z6.enum(["text","table","document","archive","image","transcript","video","model"]),content:z6.string(),derivedFiles:z6.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z6.literal("page"),start:z6.number().int().nonnegative(),end:z6.number().int().nonnegative(),total:z6.number().int().nonnegative(),nextCursor:z6.string().nullable(),complete:z6.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z6.literal("query"),query:z6.string(),source:z6.enum(["original-file","canonical-text","derived-files"]),truncated:z6.boolean()}),AssetReadResultSchema=z6.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z7}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z7.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z8}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});import{z as z9}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z9.object({projectId:z9.uuid(),userId:z9.string().min(1)}),NotificationEventSchema=z9.discriminatedUnion("type",[z9.object({type:z9.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path52){let conditionPath=[...path52,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path52)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","env","project","day"]),OpsAgentHealthInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),env:z13.string().trim().min(1).max(64).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z13.object({path:OpsProjectFilePathSchema,content:z13.string().max(256*1024),overwrite:z13.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z13.string().trim().length(64),consentReference:z13.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z13.intersection(OpsProjectOperationPlanInputSchema,z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z14}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z14.object({kind:z14.literal("say"),label:z14.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z14.string().min(1).max(240).optional(),message:z14.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z14.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),BlockBaseSchema=z14.object({fallback:z14.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z14.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z14.literal("choices"),text:z14.string().max(500).optional(),actions:z14.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z14.discriminatedUnion("kind",[z14.object({kind:z14.literal("entry"),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("asset"),assetId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("url"),url:z14.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z14.literal("table"),columns:z14.array(z14.object({label:z14.string().min(1).max(24)})).min(2).max(4),rows:z14.array(z14.object({cells:z14.array(z14.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z14.literal("cards"),layout:z14.enum(["rail","stack"]).optional(),items:z14.array(z14.object({title:z14.string().min(1).max(60),subtitle:z14.string().min(1).max(120).optional(),imageUrl:z14.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z14.literal("entry"),label:z14.string().min(1).max(80),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120),path:z14.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z14.literal("assets"),items:z14.array(z14.object({url:z14.url({protocol:/^https$/}).max(2e3),alt:z14.string().min(1).max(120),label:z14.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z14.literal("callout"),title:z14.string().min(1).max(80),text:z14.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z14.literal("stat"),items:z14.array(z14.object({label:z14.string().min(1).max(24),value:z14.string().min(1).max(16),delta:z14.string().min(1).max(12).optional(),tone:z14.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z14.literal("chart"),unit:z14.string().min(1).max(12).optional(),points:z14.array(z14.object({label:z14.string().min(1).max(12),value:z14.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z14.literal("text"),placeholder:z14.string().min(1).max(120).optional(),multiline:z14.boolean().optional()}).strict(),ChatFormStepIdSchema=z14.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z14.object({id:ChatFormStepIdSchema,token:z14.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z14.string().trim().min(1).max(60),reason:z14.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z14.literal("capabilities"),items:z14.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z14.object({id:ChatFormStepIdSchema.optional(),question:z14.string().min(1).max(500),header:z14.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z14.boolean(),recommended:z14.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&!step.multiSelect&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}),FormBlockSchema=BlockBaseSchema.extend({type:z14.literal("form"),steps:z14.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z14.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z14.object({stepId:ChatFormStepIdSchema.optional(),header:z14.string().min(1).max(25),question:z14.string().min(1).max(500),answer:z14.string().min(1),selectedLabels:z14.array(z14.string().min(1).max(120)).max(8),freeText:z14.string(),skipped:z14.boolean()}),ChatFormAnswerMetadataSchema=z14.object({toolCallId:z14.string().max(255).optional(),shortTitle:z14.string().max(80).optional(),questions:z14.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z14.string().min(1).max(255)})}});import{z as z15}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z15.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z15.object({dev:z15.string().trim().min(1).optional(),build:z15.string().trim().min(1).optional(),install:z15.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z15.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z15.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z15.object({type:z15.enum(["header","cookie","query","host"]),key:z15.string().min(1).optional(),value:z15.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z15.array(FimoHostingConditionSchema).min(1).optional(),missing:z15.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),permanent:z15.boolean().optional(),statusCode:z15.union([z15.literal(301),z15.literal(302),z15.literal(307),z15.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z15.object({source:z15.string().min(1),headers:z15.array(z15.object({key:z15.string().min(1),value:z15.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z15.object({rewrites:z15.array(FimoHostingRewriteSchema).optional(),redirects:z15.array(FimoHostingRedirectSchema).optional(),headers:z15.array(FimoHostingHeaderSchema).optional(),cleanUrls:z15.boolean().optional(),trailingSlash:z15.boolean().optional()}).strict(),FimoAppConfigSchema=z15.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z16}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z16.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),previewEnabled:z16.boolean().default(!0),enabledChatModels:z16.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({versionId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),kind:z16.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z16.object({versionCount:z16.number().int().nonnegative(),snapshotBytes:z16.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z16.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z16.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional(),warning:z16.string().optional(),durationMs:z16.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z16.object({label:z16.string().trim().min(1).max(120).optional(),notes:z16.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z16.boolean(),publicationId:z16.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z17.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z17.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z17.object({id:z17.union([z17.literal(PREVIEW_ENVIRONMENT_KEY),z17.uuid()]),name:z17.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z18.object({projectId:z18.uuid(),name:z18.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z18.literal("production"),sourceBranch:EnvSchema,isPublished:z18.boolean(),url:z18.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PREVIEW_ENVIRONMENT_KEY),kind:z18.literal("preview"),matchedBranchCount:z18.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z18.literal("custom"),matchedBranchCount:z18.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z18.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z18.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z18.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z18.object({deletedId:z18.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z19}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z19.object({kind:z19.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z19.object({kind:z19.enum(["variable","secret"]),value:z19.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z19.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z19.object({kind:z19.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),key:z19.string(),kind:z19.literal("secret"),exposure:z19.literal("private"),environment:EnvironmentKeySchema,maskedValue:z19.string().optional(),createdAt:z19.date().transform(value=>value.toISOString()),updatedAt:z19.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z19.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z20}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z20.object({success:z20.literal(!0),downloadUrl:z20.string(),expiresAt:z20.string(),fileSize:z20.number(),duration:z20.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z20.object({success:z20.literal(!0),projectId:z20.string(),projectName:z20.string(),displayName:z20.string(),projectUrl:z20.string(),duration:z20.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z20.object({contentTypes:z20.number(),entries:z20.number(),assets:z20.number(),translations:z20.number(),forms:z20.number(),codeFiles:z20.number(),assetFiles:z20.number()}),ImportPreviewSurfaceDTOSchema=z20.object({name:z20.string(),included:z20.boolean(),count:z20.number().optional(),note:z20.string().optional()}),ImportPreviewDTOSchema=z20.object({projectName:z20.string(),displayName:z20.string().nullable(),category:z20.string().nullable(),exportedAt:z20.string(),version:z20.string(),envScope:z20.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z20.array(ImportPreviewSurfaceDTOSchema),fileSize:z20.number(),fileName:z20.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z20.object({success:z20.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z21}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z21.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z21.object({type:z21.literal("manual")}),ScheduleTriggerSchema=z21.object({type:z21.literal("schedule"),cron:z21.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z21.string().optional()}),WebhookTriggerSchema=z21.object({type:z21.literal("webhook"),path:z21.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z21.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z22}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z22.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z22.object({token:z22.string().min(1),risk:CapabilityRiskTierSchema,description:z22.string()}),AgentSubAgentSummarySchema=z22.object({name:z22.string().min(1),grant:z22.enum(["inherit","explicit"]),effectiveCaps:z22.array(z22.string().min(1))}),AgentInstallSummaryDTOSchema=z22.object({agentName:z22.string().min(1),env:z22.string().min(1),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z22.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z22.array(CapabilitySummaryEntrySchema),criticalCapabilities:z22.array(CapabilitySummaryEntrySchema),subAgents:z22.array(AgentSubAgentSummarySchema),declaresDelegate:z22.boolean(),cycle:z22.array(z22.string()).nullable(),missingSubAgents:z22.array(z22.string()),warnings:z22.array(z22.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z23}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z23.object({kind:TriggerKindSchema,summary:z23.string()}),AgentListItemTriggerStateSchema=z23.object({triggerIndex:z23.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z23.boolean(),wired:z23.boolean(),syncError:z23.string().nullable()}),AgentListItemDTOSchema=z23.object({name:z23.string().min(1),description:z23.string().nullable(),goalFirstLine:z23.string().nullable(),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),triggers:z23.array(AgentListItemTriggerSchema),triggerStates:z23.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z23.array(AgentListItemDTOSchema))}});import{z as z24}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z24.object({args:z24.unknown().optional(),requestId:z24.string().min(1).max(128).optional()}),DispatchSkippedSchema=z24.object({skipped:z24.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z24.object({sessionId:z24.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z24.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z25}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z25.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z25.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z25.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z25.object({verb:SurfaceDeltaVerbSchema,key:z25.string(),detail:z25.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z25.record(z25.string(),z25.unknown()).optional()}),PerSurfaceDeltaSchema=z25.object({surface:SurfaceNameSchema,status:z25.enum(["ok","timed_out","failed","unchanged"]),durationMs:z25.number().int().nonnegative().optional(),changedCount:z25.number().int().nonnegative(),conflictCount:z25.number().int().nonnegative(),items:z25.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z25.boolean().optional(),error:z25.string().optional()}),CrossSurfaceFindingSchema=z25.object({id:z25.string(),kind:z25.string(),description:z25.string(),severity:z25.enum(["warning","error"]),source:z25.object({surface:SurfaceNameSchema,key:z25.string()}),target:z25.object({surface:SurfaceNameSchema,key:z25.string()}),actions:z25.array(z25.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z25.object({env:EnvSchema,vs:EnvSchema,syncState:z25.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),agents:z25.array(z25.object({id:z25.string(),name:z25.string(),status:z25.enum(["active","paused","failed"]),lastRunAt:z25.coerce.date().nullable()})).optional(),crossSurface:z25.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z25.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),crossSurface:z25.array(CrossSurfaceFindingSchema).optional(),fingerprint:z25.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z25.object({path:z25.string(),state:z25.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z25.string(),additions:z25.number().int().nonnegative(),deletions:z25.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z25.object({oid:z25.string().optional(),content:z25.string().optional(),truncated:z25.boolean(),binary:z25.boolean()}),CodeConflictDetailSchema=z25.object({path:z25.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z25.string(),targetTipSha:z25.string(),mergeBaseSha:z25.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z25.object({id:z25.string(),slug:z25.string(),contentType:z25.string(),data:z25.record(z25.string(),z25.unknown()),updatedAt:z25.coerce.date()}),ContentRowDiffSchema=z25.object({collection:z25.string(),rowId:z25.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z25.object({name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),fields:z25.record(z25.string(),z25.unknown())}),SchemaTypeDiffSchema=z25.object({typeName:z25.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z25.object({id:z25.string(),name:z25.string(),type:z25.enum(["file","folder"]),mimeType:z25.string().nullable(),storageKey:z25.string().nullable(),url:z25.string().nullable(),fileSize:z25.number().nullable(),width:z25.number().nullable(),height:z25.number().nullable(),altText:z25.string().nullable(),caption:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),AssetDiffSchema=z25.object({assetId:z25.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z25.object({locale:z25.string(),key:z25.string(),parent:z25.string().nullable(),child:z25.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z25.object({formName:z25.string(),label:z25.string().nullable(),schemaFingerprint:z25.string(),fields:z25.record(z25.string(),z25.unknown()),settings:z25.record(z25.string(),z25.unknown()).optional()}),FormSchemaDiffSchema=z25.object({formName:z25.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z25.enum(CONFLICT_KINDS),ConflictSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),kind:ConflictKindSchema.optional(),description:z25.string(),parentValue:z25.unknown().optional(),childValue:z25.unknown().optional(),conflictingFields:z25.array(z25.string()).optional(),code:z25.object({path:z25.string(),unresolvable:z25.boolean().optional(),reason:z25.string().optional()}).optional()}),FieldPickSchema=z25.object({field:z25.string(),choice:z25.enum(["parent","child","pick","ai-pick"]),pickedValue:z25.unknown().optional(),aiSessionId:z25.string().optional()}),ConflictResolutionSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),choice:z25.enum(["parent","child","pick"]),pickedValue:z25.unknown().optional(),fieldPicks:z25.array(FieldPickSchema).optional()}),MergeResultSchema=z25.object({ok:z25.boolean(),mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z25.array(z25.object({surface:SurfaceNameSchema,count:z25.number().int().nonnegative()})),conflicts:z25.array(ConflictSchema).optional(),summary:z25.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z25.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z25.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z25.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z25.boolean().optional()}),ResolvedStrategySchema=z25.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z25.boolean()}),MergeRequestSchema=z25.object({from:EnvSchema,allowDirectMerge:z25.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z25.object({mergeId:z25.string().uuid(),streamUrl:z25.string(),strategy:ResolvedStrategySchema,acceptedAt:z25.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z25.object({mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z25.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z25.array(ConflictSchema),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedBy:z25.string().nullable(),lastEditedAt:z25.coerce.date().nullable(),initiator:z25.object({userId:z25.string().nullable(),role:z25.string().nullable(),agentName:z25.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z25.object({resolutions:z25.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z25.object({mergeId:z25.string().uuid(),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedAt:z25.coerce.date(),lastEditedBy:z25.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z25.object({mergeId:z25.string().uuid(),resolutions:z25.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z25.object({mergeId:z25.string().uuid()}),PublishReleaseRequestSchema=z25.object({version:z25.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z25.string().max(2e4).optional()}),PublishReleaseResultSchema=z25.object({releaseTag:z25.string(),sha:z25.string(),publishedAt:z25.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z26}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z26.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z26.object({cpuMs:z26.number().nonnegative().default(0),netBytes:z26.number().nonnegative().default(0),walltimeMs:z26.number().nonnegative().default(0),llmTokensIn:z26.number().nonnegative().optional(),llmTokensOut:z26.number().nonnegative().optional(),stepCount:z26.number().int().nonnegative().optional(),toolCallCounts:z26.record(z26.string().min(1).max(120),z26.number().int().nonnegative()).optional(),finishAction:z26.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z26.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z26.object({capturedAt:z26.coerce.date(),fingerprint:z26.string().min(1).max(256),counts:z26.object({code:z26.number().int().nonnegative(),content:z26.number().int().nonnegative(),schemas:z26.number().int().nonnegative(),labels:z26.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z26.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z26.object({diff:DiffReportSchema,code:z26.array(CodeFileDiffSchema.extend({raw:z26.string().max(24576)})).max(200),schemas:z26.array(SchemaTypeDiffSchema).max(200),content:z26.array(z26.object({key:z26.string().min(1).max(512),collection:z26.string().min(1).max(256),slug:z26.string().max(512).optional(),verb:z26.enum(["added","modified","deleted"]),fields:z26.array(z26.object({name:z26.string().min(1).max(256),before:z26.unknown().optional(),after:z26.unknown().optional()})).max(20)})).max(200),labels:z26.array(z26.object({key:z26.string().min(1).max(512),locale:z26.string().min(1).max(64).optional(),before:z26.unknown().nullable(),after:z26.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:EnvSchema,agentName:z26.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z26.unknown().optional(),capabilities:z26.array(z26.string()).optional(),dataSources:z26.array(z26.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z26.string().nullable(),startedAt:z26.coerce.date().nullable(),finishedAt:z26.coerce.date().nullable(),cancelledAt:z26.coerce.date().nullable(),costUsd:z26.number().nonnegative(),costCeilingUsd:z26.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z26.boolean(),lastCheckpointId:z26.uuid().nullable(),branchEnvId:z26.uuid().nullable(),parentSessionId:z26.uuid().nullable(),terminalReason:z26.string().nullable(),errorMessage:z26.string().nullable(),report:z26.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z26.object({id:z26.uuid(),sessionId:z26.uuid(),checkpointIdx:z26.number().int().nonnegative(),payloadRef:z26.string(),payloadSizeBytes:z26.number().int().nonnegative(),checksum:z26.string().length(64),createdAt:z26.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z26.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z26.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z26.object({session:AgentSessionDTOSchema,checkpoints:z26.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z26.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z26.object({reason:z26.string().min(1).max(120).optional()})}});import{z as z27}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z27.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z27.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z27.object({id:z27.uuid(),envId:z27.uuid(),sessionId:z27.uuid().nullable(),skillName:z27.string().min(1),classification:AgentBranchClassificationSchema,rationale:z27.string().nullable(),summary:z27.string().nullable(),surfaceDeltas:z27.record(z27.string(),z27.unknown()),createdAt:z27.coerce.date(),decidedAt:z27.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z27.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z27.object({path:z27.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z27.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z27.object({code:z27.literal("merge_conflict"),message:z27.string(),conflicts:z27.record(z27.string(),z27.number().int().nonnegative())})}});import{z as z28}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z28.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z28.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z28.object({description:z28.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z28.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),threadId:z28.uuid(),invocationId:z28.uuid(),agentKey:z28.string().min(1).max(120),anchorEnv:z28.string().min(1).max(64),retainedEnv:z28.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z28.string().min(1).nullable(),continuationInvocationId:z28.uuid().nullable(),askedAt:z28.coerce.date(),expiresAt:z28.coerce.date(),closedAt:z28.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z28.object({questionId:z28.uuid(),invocationId:z28.uuid(),askedAt:z28.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z28.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z28.object({question:AgentQuestionSchema,continuationInvocationId:z28.uuid(),deduped:z28.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z29}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z29.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z29.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z29.enum(["secret_text"]),IntegrationCredentialUsageSchema=z29.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z29.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z29.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z29.object({mode:IntegrationAuthModeSchema,label:z29.string().min(1),description:z29.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z29.object({id:z29.string().min(1),label:z29.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z29.boolean()}),IntegrationToolDefinitionDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),description:z29.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z29.object({title:z29.string().min(1),description:z29.string().min(1),command:z29.string().min(1).optional()}),IntegrationInfoDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z29.array(IntegrationAuthModeDTOSchema),credentials:z29.array(IntegrationCredentialDefinitionDTOSchema),tools:z29.array(IntegrationToolDefinitionDTOSchema),recipes:z29.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),installed:z29.boolean(),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z29.string().nullable(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),connectionStatus:z29.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),installedAt:z29.coerce.date().nullable(),updatedAt:z29.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z29.string(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z29.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z29.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z29.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z29.object({value:z29.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z29.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z29.object({id:z29.uuid(),organizationId:z29.string().min(1),integrationKey:z29.string().min(1),alias:z29.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z29.string().min(1),externalAccountName:z29.string().nullable(),externalBotUserId:z29.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z29.array(z29.string()),connectedAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z29.object({alias:z29.string().min(1).max(120).optional(),token:z29.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z29.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),alias:z29.string().min(1).max(120),token:z29.string().min(1)}),z29.object({mode:z29.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z29.object({integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),integrationKey:z29.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z29.object({mode:z29.literal("oauth"),integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),BindProjectChannelRequestSchema=z29.object({ref:z29.string().min(1),connectionAlias:z29.string().min(1).optional(),agentName:z29.string().min(1).max(160).nullable().optional(),force:z29.boolean().optional()}),ListProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1)}),SearchProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1),connectionAlias:z29.string().min(1),query:z29.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),connectionId:z29.uuid(),externalWorkspaceId:z29.string().min(1),externalChannelId:z29.string().min(1),externalChannelName:z29.string().nullable(),agentName:z29.string().nullable(),enabled:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z29.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z29.object({id:z29.string().min(1),name:z29.string().min(1),visibility:z29.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z29.string().min(1).nullable(),canMove:z29.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z29.object({markdown:z29.boolean().optional(),summary:z29.boolean().optional(),links:z29.boolean().optional(),branding:z29.boolean().optional(),images:z29.boolean().optional(),html:z29.union([z29.literal("cleaned"),z29.literal("raw"),z29.boolean()]).optional(),json:z29.union([z29.boolean(),z29.object({prompt:z29.string().min(1).max(1e4),schema:z29.record(z29.string(),z29.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z29.object({url:z29.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z29.object({query:z29.string().min(1),maxResults:z29.number().int().positive().max(20).optional(),sources:z29.array(z29.enum(["web","news","images"])).min(1).max(3).optional(),categories:z29.array(z29.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z29.enum(["hour","day","week","month","year"]).optional(),location:z29.string().min(1).max(160).optional(),country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(100).optional(),types:z29.array(z29.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),sources:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),passages:z29.number().int().min(1).max(5).optional(),skills:z29.literal("only").optional(),language:z29.string().min(1).optional(),topic:z29.string().min(1).optional(),license:z29.string().min(1).optional(),minStars:z29.number().int().min(0).optional(),maxStars:z29.number().int().min(0).optional(),archived:z29.boolean().optional(),fork:z29.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(500).optional(),authors:z29.array(z29.string().min(1)).min(1).optional(),categories:z29.array(z29.string().min(1)).min(1).optional(),from:z29.iso.date().optional(),to:z29.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),query:z29.string().min(1).max(500).optional(),maxPassages:z29.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),intent:z29.string().min(1).max(500),mode:z29.enum(["similar","citers","references"]).optional(),maxResults:z29.number().int().min(1).max(500).optional(),rerank:z29.boolean().optional(),anchors:z29.array(z29.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z29.object({url:z29.string().url(),search:z29.string().min(1).optional(),limit:z29.number().int().positive().max(200).optional(),includeSubdomains:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z29.object({url:z29.string().url(),limit:z29.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z29.object({text:z29.string().min(1).max(200).optional(),cron:z29.string().min(1).max(120).optional(),timezone:z29.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z29.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z29.union([z29.object({type:z29.enum(["scrape","crawl"]).default("scrape"),urls:z29.array(z29.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z29.object({type:z29.literal("search"),queries:z29.array(z29.string().min(1).max(256)).min(1).max(12),searchWindow:z29.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z29.number().int().min(1).max(50).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z29.object({name:z29.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),notification:z29.object({email:z29.object({enabled:z29.boolean().default(!0),recipients:z29.array(z29.string().email()).min(1).max(20),includeDiffs:z29.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z29.object({monitorId:z29.string().uuid(),name:z29.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),status:z29.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z29.object({monitorId:z29.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z29.string().uuid()}),RunProjectIntegrationToolRequestSchema=z29.object({tool:z29.string().min(1),input:z29.record(z29.string(),z29.unknown()),connectionAlias:z29.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z29.object({provider:z29.string().min(1),providerCredits:z29.number().nonnegative().optional(),providerCostUsd:z29.number().nonnegative().optional(),requests:z29.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z29.object({credits:z29.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),json:z29.unknown().optional(),branding:z29.record(z29.string(),z29.unknown()).optional(),warning:z29.string().optional()}),FirecrawlSearchToolOutputSchema=z29.object({query:z29.string(),provider:z29.literal("firecrawl"),warning:z29.string().optional(),results:z29.array(z29.object({title:z29.string(),url:z29.string(),snippet:z29.string().optional(),content:z29.string().optional(),score:z29.number().optional(),publishedAt:z29.string().optional()}))}),FirecrawlResearchPaperSchema=z29.object({paperId:z29.string(),primaryId:z29.string().optional(),ids:z29.record(z29.string(),z29.array(z29.string())).optional(),title:z29.string().optional(),abstract:z29.string().optional(),score:z29.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z29.object({text:z29.string(),score:z29.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(z29.object({id:z29.string(),type:z29.string().min(1).optional(),url:z29.string(),title:z29.string().optional(),passages:z29.array(z29.object({text:z29.string()}).passthrough())}).passthrough()),coverage:z29.record(z29.string(),z29.string()).optional(),reranked:z29.boolean().optional(),repos:z29.array(z29.record(z29.string(),z29.unknown())).optional(),sources:z29.array(z29.record(z29.string(),z29.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),paper:z29.record(z29.string(),z29.unknown()),paperId:z29.string().optional(),query:z29.string().optional(),passages:z29.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema),poolSize:z29.number().int().nonnegative(),truncated:z29.boolean(),note:z29.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),count:z29.number(),links:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),description:z29.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),total:z29.number(),pages:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),warning:z29.string().optional()})),warning:z29.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z29.object({cron:z29.string().optional(),text:z29.string().optional(),timezone:z29.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z29.object({id:z29.string().optional(),type:z29.enum(["scrape","crawl","search"]).optional(),urls:z29.array(z29.string()).optional(),queries:z29.array(z29.string()).optional(),searchWindow:z29.string().optional(),maxResults:z29.number().optional(),includeDomains:z29.array(z29.string()).optional(),excludeDomains:z29.array(z29.string()).optional(),scrapeOptions:z29.record(z29.string(),z29.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z29.object({id:z29.string(),name:z29.string(),status:z29.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z29.string().nullable().optional(),lastRunAt:z29.string().nullable().optional(),currentCheckId:z29.string().nullable().optional(),targets:z29.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z29.string().nullable().optional(),judgeEnabled:z29.boolean().optional(),estimatedCreditsPerMonth:z29.number().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z29.object({id:z29.string(),monitorId:z29.string(),scheduledFor:z29.string().nullable().optional(),startedAt:z29.string().nullable().optional(),finishedAt:z29.string().nullable().optional(),estimatedCredits:z29.number().optional(),reservedCredits:z29.number().optional(),actualCredits:z29.number().optional(),billingStatus:z29.string().nullable().optional(),summary:z29.object({totalPages:z29.number().optional(),same:z29.number().optional(),changed:z29.number().optional(),new:z29.number().optional(),removed:z29.number().optional(),error:z29.number().optional()}).passthrough().optional(),error:z29.string().nullable().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitors:z29.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),deleted:z29.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),checks:z29.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),check:FirecrawlMonitorCheckOutputSchema,next:z29.string().optional()}),FirecrawlToolKeySchema=z29.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z29.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),tool:z29.string().min(1),connectionAlias:z29.string().min(1).nullable().optional(),output:z29.record(z29.string(),z29.unknown()),executedAt:z29.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z29.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z29.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z29.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z29.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z29.array(ProjectChannelCandidateDTOSchema))}});import{z as z30}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z30.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z30.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z30.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z30.object({userId:z30.string().min(1),name:z30.string(),email:z30.string().min(1),subscribed:z30.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z30.object({maxSubscribers:z30.number().int().positive(),subscriberCount:z30.number().int().nonnegative(),effectiveRecipientCount:z30.number().int().nonnegative(),currentUserSubscribed:z30.boolean(),candidates:z30.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z30.object({userIds:z30.array(z30.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z30.object({topic:UserManagedNotificationTopicSchema,enabled:z30.boolean(),source:z30.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z30.object({topics:z30.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z30.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z30.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z30.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z30.string().nullable(),maskedEmail:z30.string().min(1),applied:z30.boolean(),expiresAt:z30.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z30.object({scheduleId:z30.string().min(1),scheduleName:z30.string(),projectId:z30.string().min(1),projectName:z30.string(),env:z30.string().min(1)}),FollowedSchedulesSchema=z30.object({schedules:z30.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z31}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z31.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z31.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z31.uuid(),env:z31.string().min(1),name:z31.string().min(1),cron:z31.string().min(1),command:z31.string().min(1),secretKeys:z31.array(z31.string().min(1)),enabled:z31.boolean(),lastRunAt:z31.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z31.string().nullable(),overPolicyReasons:z31.array(z31.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120),cron:z31.string().min(1).max(120),command:z31.string().min(1).max(500),secretKeys:z31.array(ProjectSecretKeySchema).default([]),enabled:z31.boolean().optional()}),UpdateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120).optional(),cron:z31.string().min(1).max(120).optional(),command:z31.string().min(1).max(500).optional(),secretKeys:z31.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z31.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z31.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z31.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z31.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z31.object({maxRuns:z31.number().int().positive(),retentionDays:z31.number().int().positive().nullable(),outputRetentionDays:z31.number().int().positive(),maxOutputBytes:z31.number().int().positive()}),SchedulePolicyStateSchema=z31.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z31.object({code:z31.enum(["Free","Premium","Pro"]),source:z31.enum(["cached_subscription","free_fallback"]),activeSchedules:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),concurrency:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),compute:z31.object({settledMs:z31.number().int().nonnegative(),reservedMs:z31.number().int().nonnegative(),includedMs:z31.number().int().positive(),remainingMs:z31.number().int().nonnegative(),resetsAt:z31.coerce.date()}),upgrade:z31.object({code:z31.literal("Premium"),activeSchedulesLimit:z31.number().int().positive(),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),maxConcurrentRuns:z31.number().int().positive(),computeIncludedMs:z31.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z31.array(z31.string())}),ProjectScheduleUsageSchema=z31.object({runCount:z31.number().int().nonnegative(),runsWithOutput:z31.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z31.object({id:z31.uuid(),scheduleId:z31.uuid(),projectId:z31.uuid(),env:z31.string().min(1),scheduleName:z31.string().min(1),command:z31.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z31.object({id:z31.string().min(1),name:z31.string().min(1)}).nullable(),queuedAt:z31.coerce.date(),startedAt:z31.coerce.date().nullable(),finishedAt:z31.coerce.date().nullable(),exitCode:z31.number().int().nullable(),errorCode:z31.string().nullable(),error:z31.string().nullable(),outputBytes:z31.number().int().nonnegative(),outputTruncated:z31.boolean(),outputExpiresAt:z31.coerce.date().nullable(),metadataExpiresAt:z31.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z31.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z31.coerce.date().nullable(),items:z31.array(z31.object({key:z31.string().min(1),updatedAt:z31.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z31.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z31.object({trigger:z31.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z31.object({limit:z31.coerce.number().int().min(1).max(100).default(25),cursor:z31.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z31.object({items:z31.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z31.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z31.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z31.object({items:z31.array(ProjectScheduleRunDTOSchema),nextCursor:z31.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z32}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z32.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z32.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z32.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("user"),userId:z32.string().min(1)}).strict(),z32.object({kind:z32.literal("agent"),agentKey:z32.string().min(1).max(120),agentId:z32.uuid().optional()}).strict(),z32.object({kind:z32.literal("system")}).strict()]),NotificationSummarySchema=z32.string().trim().min(1).max(1200),NotificationRunOutcomeSchema=z32.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z32.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z32.discriminatedUnion("topic",[z32.object({topic:z32.literal("agent_question"),questionId:z32.uuid(),title:z32.string().trim().min(1).max(80),description:z32.string().trim().min(1).max(240)}).strict(),z32.object({topic:z32.literal("agent_run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().optional(),proposalId:z32.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().optional(),summary:NotificationSummarySchema.optional()}).strict()]),NotificationEnvelopeSchema=z32.object({id:z32.uuid(),projectId:z32.uuid(),sourceKey:z32.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z32.literal(1),payload:NotificationPayloadSchema,createdAt:z32.coerce.date()}),NotificationRecipientStateSchema=z32.object({id:z32.uuid(),notificationId:z32.uuid(),projectId:z32.uuid(),userId:z32.string().min(1),readAt:z32.coerce.date().nullable(),archivedAt:z32.coerce.date().nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationDeliveryStateSchema=z32.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z32.object({id:z32.uuid(),notificationRecipientId:z32.uuid(),projectId:z32.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z32.number().int().nonnegative(),nextAttemptAt:z32.coerce.date().nullable(),lastAttemptAt:z32.coerce.date().nullable(),sentAt:z32.coerce.date().nullable(),failureCode:z32.string().max(80).nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationPreferenceSchema=z32.object({topic:WorkNotificationTopicSchema,channel:z32.literal("email"),enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z32.object({topics:z32.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("question"),questionId:z32.uuid()}).strict(),z32.object({kind:z32.literal("run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z32.object({kind:z32.literal("retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().nullable(),proposalId:z32.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z32.object({kind:z32.literal("merge_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().nullable()}).strict()]),NotificationViewSchema=z32.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z32.object({items:z32.array(NotificationViewSchema),nextCursor:z32.string().nullable(),unreadCount:z32.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z32.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z32.string().min(1).max(120).optional(),sourceKey:z32.string().min(1).max(255).optional(),unread:z32.stringbool().optional(),archived:z32.stringbool().optional(),limit:z32.coerce.number().int().min(1).max(100).optional(),cursor:z32.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z32.object({recipient:NotificationRecipientStateSchema,unreadCount:z32.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z32.object({read:z32.boolean().optional(),archived:z32.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z33}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z33.object({id:z33.uuid(),occurredAt:z33.coerce.date(),projectId:z33.uuid().nullable(),env:z33.string().nullable(),actor:z33.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z33.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z33.unknown().optional(),ipAddress:z33.string().nullable().optional(),userAgent:z33.string().nullable().optional(),error:z33.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z33.object({rows:z33.array(AuditLogRowDTOSchema),nextCursor:z33.string().nullable()})),AuditLogQuerySchema=z33.object({env:z33.string().optional(),action:AuditActionSchema.optional(),actor:z33.string().optional(),from:z33.coerce.date().optional(),to:z33.coerce.date().optional(),limit:z33.coerce.number().int().min(1).max(200).optional(),cursor:z33.string().optional()})}});import{z as z34}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z34.object({surface:SurfaceNameSchema,key:z34.string(),label:z34.string()}),InlineSchema=z34.object({text:z34.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z34.discriminatedUnion("type",[z34.object({type:z34.literal("paragraph"),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("preview"),ref:DiffRefSchema,caption:z34.string().optional()}),z34.object({type:z34.literal("code"),code:z34.string(),lang:z34.string().optional(),caption:z34.string().optional()}),z34.object({type:z34.literal("risk"),level:z34.enum(["warning","error"]),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("list"),items:z34.array(z34.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z34.object({headline:z34.string(),blocks:z34.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z34.object({summary:EnvDiffSummarySchema,fingerprint:z34.string(),generatedAt:z34.coerce.date(),cached:z34.boolean().optional(),credits:z34.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z35}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z35.object({date:z35.string(),visitors:z35.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z35.object({key:z35.string(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z35.object({path:z35.string(),pageName:z35.string().nullable().optional(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z35.object({preset:z35.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z35.string(),requestedTo:z35.string(),effectiveFrom:z35.string(),effectiveTo:z35.string(),isRetentionLimited:z35.boolean(),groupBy:z35.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z35.object({date:z35.string(),content:z35.string(),updatedAt:z35.string(),updatedByUserId:z35.string()}),ProjectPageviewAnalyticsDTOSchema=z35.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative(),bounceRate:z35.number().min(0).max(100),viewsPerVisit:z35.number().nonnegative(),averageVisitDurationSeconds:z35.number().nonnegative(),visitorsSeries:z35.array(ProjectDailyVisitorsDTOSchema),topPages:z35.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z35.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z36}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z36.object({id:z36.string(),email:z36.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z36.coerce.date(),createdAt:z36.coerce.date(),inviterUserId:z36.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z36.object({id:z36.string(),token:z36.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z36.object({success:z36.boolean(),projectId:z36.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z37}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z37.object({id:z37.string(),name:z37.string(),image:z37.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z37.object({count:z37.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z37.object({counts:z37.object({signed_up:z37.int(),activated:z37.int()}),credits:z37.object({total:z37.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z37.email(),emailVerified:z37.boolean(),createdAt:z37.coerce.date(),updatedAt:z37.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z38}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z38.object({id:z38.string(),principalType:ProjectPrincipalTypeSchema,principalId:z38.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z38.coerce.date(),expiresAt:z38.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z38.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z38.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z38.record(z38.string(),z38.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z38.object({access:z38.array(ProjectAccessItemDTOSchema),invites:z38.array(ProjectInviteDTOSchema),organization:z38.object({name:z38.string().nullable(),logo:z38.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),projectId:z38.uuid()}))}});import{z as z39}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z39.object({publicationStatus:PublicationStatusSchema,appUrl:z39.string().nullable(),lastPublishedAt:z39.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z40}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z40.object({url:z40.url(),expiresAt:z40.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema})}});import{z as z41}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z41.string(),slug:z41.string().nullable(),logo:z41.string().nullable(),metadata:z41.record(z41.string(),z41.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z41.object({id:z41.string(),name:z41.string(),email:z41.email(),image:z41.string().nullable()}),OrganizationMemberDTOSchema=z41.object({id:z41.string(),userId:z41.string(),organizationId:z41.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z41.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z42}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z42.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z42.object({reason:CancellationReasonCodeSchema,details:z42.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z42.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z42.object({offerVersion:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),renewsOn:z42.string()}),PlanMigrationPreviewDTOSchema=z42.object({currency:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),startsAt:z42.string(),renewsAt:z42.string(),nextRenewalAmount:z42.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z42.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z42.object({id:z42.string(),organizationId:z42.string(),legacySubscriptionId:z42.string(),offeredPlanCode:z42.string(),offeredPlanName:z42.string(),offeredPriceAmount:z42.number(),offeredCurrency:z42.string(),offerVersion:z42.string(),state:PlanMigrationStateSchema,checkoutToken:z42.string().nullable(),deadlineAt:z42.string(),transitions:z42.array(z42.object({event:z42.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z42.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z42.object({included:z42.number().optional(),unitPrice:z42.number().optional(),dailyCap:z42.number().nullable().optional()}),EntitlementsDTOSchema=z42.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z42.object({retentionDays:z42.number().int().positive(),canUseExtendedDateRanges:z42.boolean()}).optional(),history:z42.object({retentionDays:z42.number().int().positive()}).optional(),members:z42.object({canInvite:z42.boolean(),maxMembers:z42.number().int().positive().nullable()}).optional(),domains:z42.object({canUseCustomDomains:z42.boolean(),maxDomains:z42.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z42.object({id:z42.string(),external_id:z42.string(),customerId:z42.string(),planId:z42.string(),planCode:z42.union([TemplateCodeSchema,z42.literal("Unknown")]),currentPeriod:z42.object({start:z42.string(),end:z42.string().nullable()}),cancelAt:z42.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z42.string(),nextPaymentAt:z42.string().nullable(),baseAmount:z42.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z42.object({totalCap:z42.number(),dailyCap:z42.number(),usedTotal:z42.number()}),CreditBalanceDTOSchema=z42.object({total:z42.number(),base:z42.number(),dailyBase:z42.number(),purchases:z42.number(),awards:z42.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z42.object({total:z42.number(),nearLimit:z42.boolean(),canChat:z42.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z42.object({dailyFreeAvailable:z42.number(),monthlyAvailable:z42.number(),purchasedAvailable:z42.number(),awardedAvailable:z42.number()}),ProjectDailyCreditAllowanceDTOSchema=z42.object({periodCap:z42.number(),dailyGrant:z42.number(),usedThisPeriod:z42.number(),remainingThisPeriod:z42.number()}),ProjectCreditBalanceDTOSchema=z42.object({projectId:z42.uuid(),organizationId:z42.string(),balance:z42.object({totalAvailable:z42.number(),nearLimit:z42.boolean(),canUseAi:z42.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z42.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z42.enum(["ok","near_limit","exhausted","unavailable"]),AgentRuntimeUsageDTOSchema=z42.object({planCode:z42.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z42.object({source:z42.enum(["cached_subscription","free_fallback"]),settledMs:z42.number().int().nonnegative(),reservedMs:z42.number().int().nonnegative(),includedMs:z42.number().int().positive(),remainingMs:z42.number().int().nonnegative(),resetsAt:z42.coerce.date()}).nullable()}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().nonnegative(),refillAmountUsd:z42.number().nonnegative()}),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().nonnegative().nullable(),refillAmountUsd:z42.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().min(.01).multipleOf(.01),refillAmountUsd:z42.number().min(.01).multipleOf(.01)}).strict(),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z42.object({invoiceId:z42.string(),newBalance:z42.int(),creditCount:z42.int(),amountUsd:z42.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z42.object({url:z42.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z43}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z43.object({brand:z43.string(),last4:z43.string(),exp:z43.string(),isDefault:z43.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z44}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z44.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z44.object({type:z44.literal("renameField"),contentType:z44.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z44.object({enabled:z44.boolean()}).strict(),ContentTypeDTOSchema=z44.object({id:z44.string(),name:z44.string(),label:z44.string(),isSingleton:z44.boolean(),i18n:ContentTypeI18nSchema,fields:z44.record(z44.string(),FieldDefinitionSchema),createdAt:z44.string(),updatedAt:z44.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z44.object({contentTypes:z44.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z44.object({id:z44.string(),entryId:z44.string(),documentId:z44.string(),slug:z44.string(),locale:z44.string().optional(),createdAt:z44.string(),updatedAt:z44.string(),__fimo:z44.object({contentType:z44.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({limit:z44.number(),offset:z44.number(),total:z44.number(),hasMore:z44.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z44.object({contentType:z44.string(),count:z44.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z44.object({counts:z44.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z44.object({count:z44.number().int().nonnegative(),sourceLocale:z44.string(),targetLocale:z44.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z44.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z44.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z44.union([z44.string(),z44.number(),z44.boolean(),z44.null()]),entryWhereOperatorSchema=z44.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z44.array(entryWhereScalarSchema).optional(),$nin:z44.array(entryWhereScalarSchema).optional(),$contains:z44.string().optional(),$startsWith:z44.string().optional(),$null:z44.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z44.object({data:z44.record(z44.string(),z44.unknown()),locale:z44.string().min(1).optional(),documentId:z44.uuid().optional()}),entryIdsSchema=z44.array(z44.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z44.object({sql:z44.string().min(1)}),BulkCreateEntriesRequestSchema=z44.object({entries:z44.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z44.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z44.object({updates:z44.array(z44.object({id:z44.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,locale:z44.string().min(1).optional()}),z44.object({where:EntryWhereSchema,locale:z44.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z44.object({data:z44.array(z44.record(z44.string(),z44.unknown())),meta:z44.object({rowCount:z44.number().int().nonnegative(),truncated:z44.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({created:z44.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({updated:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({deleted:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z45}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z45.object({index:z45.number().int().nonnegative(),contentType:z45.string(),field:z45.string(),value:z45.string(),against:z45.enum(["stored","batch"]),ownerDocumentId:z45.uuid().optional(),ownerIndex:z45.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z45.object({code:z45.literal("unique_conflict"),message:z45.string(),conflicts:z45.array(UniqueConflictSchema),truncated:z45.boolean().optional()})}});import{z as z46}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z46.object({kind:z46.literal("unique_conflict"),contentType:z46.string(),field:z46.string(),value:z46.string(),documentCount:z46.number().int().positive(),documentIds:z46.array(z46.uuid()),documentIdsTruncated:z46.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z46.object({code:z46.literal("schema_transition_rejected"),message:z46.string(),issues:z46.array(SchemaTransitionIssueSchema),truncated:z46.boolean().optional()})}});import{z as z47}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z47.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z47.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z47.object({field:CmsFieldNameSchema,direction:z47.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z47.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z47.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z47.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z47.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z47.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z48}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema))}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z51.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z51.object({items:z51.array(ProjectMessagePublicDTOSchema),nextCursor:z51.string().nullable()}),ChatLiveTurnDTOSchema=z51.object({invocationId:z51.string(),step:z51.enum(["preparing","working","compacting","merging"]),startedAt:z51.string()}),ChatLiveTurnStateDTOSchema=z51.object({threadId:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z51.object({id:z51.string(),role:z51.enum(["user","assistant"]),parts:z51.array(z51.unknown()),metadata:z51.record(z51.string(),z51.unknown()).nullable(),versionId:z51.string().nullable().optional(),createdAt:z51.date().transform(value=>value.toISOString()),providerMessageId:z51.string().nullable().optional(),invocationId:z51.string().nullable().optional(),invocationStatus:z51.string().nullable().optional(),invocationTerminalReason:z51.string().nullable().optional()}),ChatAttentionDTOSchema=z51.object({type:z51.literal("merge_conflict"),merge:z51.object({mergeId:z51.string().uuid(),projectId:z51.string(),fromEnv:z51.string(),toEnv:z51.string()}),publishAfterMerge:z51.boolean()}),ChatThreadMessagesPageDTOSchema=z51.object({threadId:z51.string().nullable(),title:z51.string().nullable(),messages:z51.array(ChatThreadMessageDTOSchema),nextCursor:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z51.object({kind:z51.literal("replay"),threadId:z51.string(),userMessageId:z51.string()}),ChatQueuedOutcomeDTOSchema=z51.object({kind:z51.literal("queued"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string()}),ChatBusyOutcomeDTOSchema=z51.object({kind:z51.literal("busy"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string().optional()}),ChatRefusedOutcomeDTOSchema=z51.object({kind:z51.literal("refused"),threadId:z51.string(),userMessageId:z51.string(),refusedInvocationId:z51.string(),terminalReason:z51.string()}),ChatNonStreamingOutcomeDTOSchema=z51.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z51.object({success:z51.boolean(),deletedCount:z51.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z51.object({code:z51.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z51.string()})}});import{z as z52}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z52.object({url:z52.string().url(),key:z52.string(),size:z52.number(),contentType:z52.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z53}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z53.object({canAccess:z53.boolean(),permissions:z53.record(z53.string(),z53.boolean()),role:z53.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z54}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z54.string().trim().default(""),sort:z54.enum(["recent","name","relevance"]).default("recent"),category:z54.string().optional()})}});import{z as z55}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z55.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z55.enum(["fimo","external"]),PaymentStatusSchema=z55.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z55.object({id:z55.string().uuid(),domain:z55.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z55.boolean(),price:z55.number().int().nullable(),renewalPrice:z55.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z55.string().nullable(),failureReason:z55.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z55.object({domain:z55.string(),available:z55.boolean(),premium:z55.boolean(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),purchaseType:z55.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z55.object({domain:z55.string(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),premium:z55.boolean(),allowedYears:z55.array(z55.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z55.object({firstName:z55.string().max(100),lastName:z55.string().max(100),companyName:z55.string().max(100).optional(),address1:z55.string().max(255),address2:z55.string().max(255).optional(),city:z55.string().max(100),state:z55.string().max(100),zip:z55.string().max(20),country:z55.string().max(2),phone:z55.string().max(30),email:z55.union([z55.string().email().max(255),z55.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z55.object({firstName:z55.string().min(1).max(100),lastName:z55.string().min(1).max(100),companyName:z55.string().max(100).optional(),address1:z55.string().min(1).max(255),address2:z55.string().max(255).optional(),city:z55.string().min(1).max(100),state:z55.string().min(1).max(100),zip:z55.string().min(1).max(20),country:z55.string().min(1).max(2),phone:z55.string().min(1).max(30),email:z55.string().email().max(255)}),SearchDomainsRequestSchema=z55.object({keyword:z55.string().min(1).max(100),tldFilter:z55.array(z55.string()).optional()}),CheckAvailabilityRequestSchema=z55.object({domains:z55.array(z55.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z55.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z55.object({domain:DomainNameSchema,years:z55.number().int().min(1).max(10).optional().default(3),autoRenew:z55.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z55.object({autoRenew:z55.boolean().optional()}),RenewDomainRequestSchema=z55.object({years:z55.number().int().min(1).max(10).optional().default(1),autoRenew:z55.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z55.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z55.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z55.object({verified:z55.boolean(),email:z55.string().nullable(),verifyBy:z55.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z56}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z56.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z56.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z56.object({txtName:z56.string().nullable().optional(),txtValue:z56.string().nullable().optional(),httpUrl:z56.string().nullable().optional(),httpBody:z56.string().nullable().optional(),cname:z56.string().nullable().optional(),cnameTarget:z56.string().nullable().optional()}),SSLValidationErrorSchema=z56.object({message:z56.string()}),OwnershipVerificationSchema=z56.object({type:z56.string(),name:z56.string(),value:z56.string()}),ProjectDomainSSLDTOSchema=z56.object({status:z56.string(),method:z56.string().nullable(),type:z56.string().nullable(),validationRecords:z56.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z56.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z56.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z56.enum(["subdomain","apex"]),RedirectConfigSchema=z56.object({type:z56.literal("apex_to_www"),linkedDomainId:z56.string()}).nullable().optional(),ProjectDomainDTOSchema=z56.object({id:z56.string(),hostname:z56.string(),status:z56.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z56.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z56.string(),scdCnameTarget:z56.string().optional(),apexTargets:z56.array(z56.string()),dnsAutoConfigured:z56.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z56.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z56.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z56.object({hostname:z56.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z56.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z56.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z56.object({available:z56.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),hostname:z56.string()}))}});import{z as z57}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z57.object({slug:z57.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z57.object({subdomain:z57.string(),subdomainUpdatedAt:z57.coerce.date()})),SubdomainSuggestionsQuerySchema=z57.object({base:z57.string().max(100).optional(),max:z57.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z57.object({suggestions:z57.array(z57.string())}))}});import{z as z58}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z58.object({translated:z58.number().int().nonnegative(),total:z58.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z58.object({locale:z58.string(),isDefault:z58.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z58.object({defaultLocale:z58.string(),locales:z58.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z58.object({locale:z58.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z58.object({locale:z58.string().min(1).max(40)}),ProjectLocaleMutationSchema=z58.object({locale:z58.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z58.object({locale:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z59}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z59.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z59.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z59.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z59.number(),credits:z59.number().optional(),billingMode:z59.enum(["fimo-credits","provider-account"]).optional(),confidence:z59.enum(["exact","estimated","metered"]),basis:z59.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z60}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z60.object({options:z60.record(z60.string(),z60.unknown()),name:z60.string().optional(),parentId:z60.string().nullable().optional(),altText:z60.string().optional(),caption:z60.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z60.string().min(1).optional(),model:z60.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z60.object({jobId:z60.string(),status:z60.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z60.string().nullable().optional(),credits:z60.number().optional(),costUsd:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z60.object({error:z60.string(),code:z60.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z60.array(GenerationTaskIdSchema).optional(),availableModels:z60.array(z60.string()).optional(),issues:z60.array(z60.unknown()).optional()})}});import{z as z61}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z61.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z61.object({name:z61.string(),key:z61.string(),description:z61.string(),type:FlagTypeSchema,required:z61.boolean(),defaultValue:z61.unknown().optional(),enumValues:z61.array(z61.string()).optional(),isArray:z61.boolean()}),AssetModelPriceSchema=z61.object({unitPrice:z61.number(),unit:z61.string(),confidence:z61.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z61.object({id:z61.string(),shortName:z61.string(),provider:z61.string(),source:z61.string(),modality:z61.enum(["image","video","audio"]),tags:z61.array(z61.string()),displayName:z61.string(),description:z61.string(),flags:z61.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z61.object({model:z61.string(),costUsd:z61.number(),credits:z61.number(),billingMode:z61.enum(["fimo-credits","provider-account"]),confidence:z61.enum(["exact","estimated","metered"]),basis:z61.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z62}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z62.object({tourId:z62.string(),version:z62.string(),status:z62.string(),completedAt:z62.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z62.array(UserTourDTOSchema))}});import{z as z63}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z63.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z63.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z63.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z63.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z63.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z63.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z63.enum(["user","agent","system"]),SupportReportTagSchema=z63.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z63.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z63.object({organization:z63.object({id:z63.string().trim().min(1).max(255),name:z63.string().trim().max(240).optional()}),project:z63.object({id:z63.uuid(),name:z63.string().trim().max(240).optional(),createdAt:z63.coerce.date().optional()}).optional(),environment:z63.string().trim().max(255).optional(),clientVersion:z63.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z63.string().trim().max(200).optional(),limit:z63.coerce.number().int().min(1).max(100).default(50),offset:z63.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z63.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z63.uuid().nullable().optional(),note:z63.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z63.object({kind:SupportReportLinkKindSchema,label:z63.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z63.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z63.object({kind:SupportReportActorKindSchema,id:z63.string().nullable(),name:z63.string().nullable()}),SupportReportLinkDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportLinkKindSchema,label:z63.string(),url:SupportReportHttpUrlSchema,externalId:z63.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportEventKindSchema,body:z63.string().nullable(),metadata:z63.record(z63.string(),z63.unknown()),actor:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z63.object({id:z63.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z63.array(z63.string()),source:SupportReportSourceSchema,message:z63.string(),reporter:z63.object({id:z63.string().nullable(),name:z63.string().nullable(),email:z63.string().nullable()}),organization:z63.object({id:z63.string().nullable(),name:z63.string()}),project:z63.object({id:z63.uuid().nullable(),name:z63.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z63.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z63.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z63.string().nullable(),deliveredAt:z63.coerce.date().nullable()}).nullable(),duplicateOfReportId:z63.uuid().nullable(),resolvedAt:z63.coerce.date().nullable(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z63.string().nullable(),clientVersion:z63.string().nullable(),links:z63.array(SupportReportLinkDTOSchema),events:z63.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z63.object({reports:z63.array(SupportReportSummaryDTOSchema),total:z63.number().int().nonnegative(),statusCounts:z63.object({new:z63.number().int().nonnegative(),in_progress:z63.number().int().nonnegative(),waiting:z63.number().int().nonnegative(),resolved:z63.number().int().nonnegative(),duplicate:z63.number().int().nonnegative(),irrelevant:z63.number().int().nonnegative(),ignored:z63.number().int().nonnegative()}),limit:z63.number().int().positive(),offset:z63.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z63.object({id:z63.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z63.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z64}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z64.iso.datetime({offset:!0}).pipe(z64.coerce.date()),OpsRecentChatInputSchema=z64.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z64.string().trim().min(1).max(255).optional(),limit:z64.coerce.number().int().min(1).max(200).default(100),cursor:z64.string().trim().min(1).max(2e3).optional(),slim:z64.boolean().default(!0),reason:z64.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z64.object({id:z64.string(),threadId:z64.string(),providerMessageId:z64.string().nullable(),invocationId:z64.string().nullable(),env:z64.string().nullable(),role:z64.string(),parts:z64.array(z64.record(z64.string(),z64.unknown())),metadata:z64.object({status:z64.string().optional(),traceUrl:z64.string().optional(),externalFileChanges:z64.array(z64.unknown()).optional()}),stats:z64.object({toolCount:z64.number().int().nonnegative(),failedToolCount:z64.number().int().nonnegative()}),createdAt:z64.iso.datetime({offset:!0}),project:z64.object({id:z64.string(),name:z64.string(),displayName:z64.string().nullable(),organizationId:z64.string().nullable()})}),OpsRecentChatResponseSchema=z64.object({target:z64.object({backendProfile:OpsBackendProfileSchema,projectEnv:z64.string().nullable()}),window:z64.object({from:z64.iso.datetime({offset:!0}),to:z64.iso.datetime({offset:!0})}),messages:z64.object({items:z64.array(OpsRecentChatMessageSchema),nextCursor:z64.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z65}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z65.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z65.literal(!1),reason:z65.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z66}from"zod";function createAgentRunWebhookEventDataSchema(status){return z66.object({run:z66.object({id:z66.string(),agentName:z66.string(),trigger:z66.string(),status:z66.literal(status),startedAt:z66.string().nullable(),finishedAt:z66.string().nullable(),reason:z66.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z66.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z66.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z66.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z66.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z66.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z66.union([z66.literal(0),z66.literal(5),z66.literal(30),z66.literal(60)]),EntryChangedWebhookEventDataSchema=z66.object({reason:WebhookEntryChangeReasonSchema,operationId:z66.string().optional(),batch:z66.object({index:z66.number().int().positive(),total:z66.number().int().positive()}).optional(),changes:z66.array(z66.object({action:WebhookEntryChangeActionSchema,contentType:z66.string(),id:z66.string(),documentId:z66.string(),locale:z66.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z66.object({form:z66.object({id:z66.string(),label:z66.string()}),submission:z66.object({id:z66.string(),data:z66.record(z66.string(),z66.unknown()),submittedAt:z66.string()})}),PublishStartedWebhookEventDataSchema=z66.object({publication:z66.object({status:z66.literal("publishing"),startedAt:z66.string()})}),PublishSucceededWebhookEventDataSchema=z66.object({publication:z66.object({status:z66.literal("published"),url:z66.string(),publishedAt:z66.string(),firstPublish:z66.boolean()})}),PublishFailedWebhookEventDataSchema=z66.object({publication:z66.object({status:z66.literal("failed"),reason:z66.string()})}),PublishUnpublishedWebhookEventDataSchema=z66.object({publication:z66.object({previousUrl:z66.string(),unpublishedAt:z66.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z66.object({review:z66.object({id:z66.string(),runId:z66.string(),agentName:z66.string(),classification:z66.string(),summary:z66.string(),reasons:z66.array(z66.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z66.object({review:z66.object({id:z66.string(),runId:z66.string(),agentName:z66.string(),resolution:z66.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z66.object({report:z66.object({weekStart:z66.string(),weekEnd:z66.string(),pageviews:z66.number(),visitors:z66.number(),previousPageviews:z66.number(),previousVisitors:z66.number()})}),MediaAssetWebhookEventDataSchema=z66.object({id:z66.string().nullable(),name:z66.string().nullable(),type:z66.string(),mimeType:z66.string().nullable(),fileSize:z66.number().nullable()}),MediaUploadedWebhookEventDataSchema=z66.object({asset:MediaAssetWebhookEventDataSchema,operation:z66.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z66.object({asset:MediaAssetWebhookEventDataSchema,operation:z66.enum(["updated","moved","analysis"]),analysis:z66.object({category:z66.string(),status:z66.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z66.object({asset:MediaAssetWebhookEventDataSchema,operation:z66.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z66.object({asset:MediaAssetWebhookEventDataSchema,operation:z66.literal("generated"),generation:z66.object({model:z66.string(),mode:z66.string()})}),MediaProcessingFailedWebhookEventDataSchema=z66.object({asset:MediaAssetWebhookEventDataSchema,operation:z66.enum(["analysis","generation"]),failure:z66.object({code:z66.string()})}),DomainCreatedWebhookEventDataSchema=z66.object({domain:z66.object({id:z66.string(),hostname:z66.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z66.object({domain:z66.object({id:z66.string(),hostname:z66.string()})}),LabelChangedWebhookEventDataSchema=z66.object({changes:z66.array(z66.object({action:z66.enum(["created","updated","deleted"]),key:z66.string(),locale:z66.string(),value:z66.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z66.object({locale:z66.object({code:z66.string(),isDefault:z66.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z66.object({locale:z66.object({code:z66.string(),previousCode:z66.string()})}),LocaleDeletedWebhookEventDataSchema=z66.object({locale:z66.object({code:z66.string(),entriesDeleted:z66.number().int().nonnegative(),labelsDeleted:z66.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z66.object({environment:z66.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z66.object({environment:z66.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z66.object({merge:z66.object({id:z66.string(),from:EnvSchema,to:EnvSchema,applied:z66.array(z66.object({surface:SurfaceNameSchema,count:z66.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z66.object({environment:z66.object({name:EnvSchema}),version:z66.object({versionId:z66.uuid(),name:z66.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z66.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z66.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z66.discriminatedUnion("source",[z66.object({source:z66.literal("literal"),value:z66.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z66.object({source:z66.literal("secret"),key:z66.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z66.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z66.object({name:z66.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z66.object({name:z66.string(),source:z66.enum(["literal","secret"]),secretKey:z66.string().nullable(),secretPrefix:z66.string().nullable(),configured:z66.literal(!0)}),WebhookFilterSchema=z66.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z66.string().min(1).max(255).optional(),agentName:z66.string().min(1).max(120).optional(),mediaType:z66.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z66.string().min(1).max(255).optional(),locale:z66.string().min(1).max(120).optional()}),JsonValueSchema=z66.lazy(()=>z66.union([z66.string(),z66.number(),z66.boolean(),z66.null(),z66.array(JsonValueSchema),z66.record(z66.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z66.object({name:z66.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z66.url(),enabled:z66.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z66.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z66.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z66.object({name:z66.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z66.url().optional(),enabled:z66.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z66.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z66.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z66.object({eventType:WebhookEventTypeSchema.optional(),data:z66.record(z66.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z66.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z66.uuid(),name:z66.string(),eventType:WebhookEventTypeSchema,enabled:z66.boolean(),destination:z66.object({host:z66.string(),maskedUrl:z66.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z66.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z66.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z66.coerce.date().nullable(),deliveryStats24h:z66.object({succeeded:z66.number().int().nonnegative(),failed:z66.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z66.uuid(),projectId:z66.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z66.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z66.number().int().positive(),test:z66.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z66.number().int().nonnegative(),responseStatus:z66.number().int().nullable(),lastErrorCode:z66.string().nullable(),lastErrorMessage:z66.string().nullable(),payloadAvailable:z66.boolean(),destination:z66.object({host:z66.string(),maskedUrl:z66.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z66.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z66.string().nullable(),qstashMessageId:z66.string().nullable(),deliveredAt:z66.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z66.object({items:z66.array(WebhookDeliveryDTOSchema),pagination:z66.object({page:z66.number().int().positive(),limit:z66.number().int().positive(),total:z66.number().int().nonnegative(),totalPages:z66.number().int().positive(),hasMore:z66.boolean()}),stats:z66.object({total:z66.number().int().nonnegative(),succeeded:z66.number().int().nonnegative(),failed:z66.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z66.object({id:z66.uuid(),deliveryId:z66.uuid(),attempt:z66.number().int().positive(),status:z66.enum(["delivering","succeeded","failed"]),responseStatus:z66.number().int().nullable(),durationMs:z66.number().int().nonnegative(),responseExcerpt:z66.string().nullable(),errorCode:z66.string().nullable(),errorMessage:z66.string().nullable(),createdAt:z66.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z66.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z66.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z67}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z67.object({key:z67.literal("fimo-2"),enabled:z67.boolean(),dismissed:z67.boolean().default(!1),interacted:z67.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z68}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z68.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z68.object({total:z68.number(),base:z68.number(),purchases:z68.number(),awards:z68.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z68.object({id:z68.string(),name:z68.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z68.object({type:z68.string(),brand:z68.string().nullable(),last4:z68.string().nullable(),expirationDate:z68.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z68.object({currency:z68.string(),nextPaymentAmount:z68.number().nullable(),nextPaymentAt:z68.string().nullable(),billingInterval:z68.string().nullable(),totalAmount:z68.number().nullable(),discountAmount:z68.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z68.object({id:z68.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z68.string().nullable(),currentPeriodEndsAt:z68.string().nullable(),renewsAt:z68.string().nullable(),cancelAt:z68.string().nullable(),renewAutomatically:z68.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z68.object({type:z68.enum(["low_balance","critical_balance","approaching_limit"]),message:z68.string(),estimatedPromptsRemaining:z68.number().nullable(),avgCostPerPrompt:z68.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z68.object({monthlyCredits:z68.number().nullable(),usedThisPeriod:z68.number(),remainingThisPeriod:z68.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z68.object({organizationId:z68.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z68.string().nullable(),tenureDays:z68.number().int().nonnegative(),capturedAt:z68.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z68.object({hasSubscription:z68.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z68.number().nullable(),alerts:z68.array(CreditAlertDTOSchema),portalUrl:z68.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z68.object({creditCount:z68.number().int().positive(),expiresAt:z68.string().datetime().nullable().optional(),message:z68.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z68.literal("free"),amountCents:z68.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z68.literal("purchase"),amountCents:z68.number().int().positive()}),CreditTopupRequestDTOSchema=z68.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z68.object({success:z68.boolean(),transactionId:z68.string().nullable(),newBalance:z68.number(),creditCount:z68.number(),type:z68.enum(["free","purchase"]),invoiceId:z68.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z69}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z69.object({totalCredits:z69.number(),totalCostUsd:z69.number(),totalMessages:z69.number(),avgCostPerMessage:z69.number(),periodStart:z69.string().nullable(),periodEnd:z69.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z69.object({projectId:z69.string(),projectName:z69.string(),projectDisplayName:z69.string().nullable(),credits:z69.number(),costUsd:z69.number(),messages:z69.number(),percentage:z69.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z69.object({userId:z69.string(),userName:z69.string().nullable(),userEmail:z69.string().email().nullable(),credits:z69.number(),costUsd:z69.number(),messages:z69.number(),percentage:z69.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z69.object({date:z69.string(),credits:z69.number(),costUsd:z69.number(),messages:z69.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z69.object({userId:z69.string(),userName:z69.string().nullable(),userEmail:z69.string().email().nullable(),credits:z69.number(),costUsd:z69.number(),messages:z69.number(),percentage:z69.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z69.object({projectId:z69.string(),projectName:z69.string(),projectDisplayName:z69.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z69.array(UsageByUserForProjectDTOSchema),timeline:z69.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z69.object({summary:UsageSummaryDTOSchema,byProject:z69.array(UsageByProjectDTOSchema),byUser:z69.array(UsageByUserDTOSchema),timeline:z69.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z70}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z70.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z70.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z70.object({startDate:z70.string().optional(),endDate:z70.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z70.coerce.number().int().positive().default(1),limit:z70.coerce.number().int().positive().max(100).default(20),sortBy:z70.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z70.string().optional(),activeOnly:z70.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z70.object({totalCredits:z70.number(),totalCostUsd:z70.number(),totalMessages:z70.number(),avgCostPerMessage:z70.number(),avgCreditsPerMessage:z70.number(),periodStart:z70.string(),periodEnd:z70.string(),creditsChange:z70.number().nullable(),costChange:z70.number().nullable(),messagesChange:z70.number().nullable(),unattributedCredits:z70.number(),unattributedCostUsd:z70.number(),unattributedMessages:z70.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z70.object({date:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z70.object({organizationId:z70.string(),organizationName:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number(),userCount:z70.number(),projectCount:z70.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().nullable(),userImage:z70.string().nullable(),organizationId:z70.string().nullable(),organizationName:z70.string().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number(),projectCount:z70.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),organizationId:z70.string(),organizationName:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number(),userCount:z70.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z70.object({id:z70.string(),name:z70.string(),value:z70.number(),percentage:z70.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z70.object({day:z70.number(),hour:z70.number(),value:z70.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z70.object({summary:UsageOverviewSummaryDTOSchema,timeline:z70.array(UsageTimelinePointDTOSchema),topOrganizations:z70.array(OrganizationUsageRowDTOSchema),topUsers:z70.array(UserUsageRowDTOSchema),topProjects:z70.array(ProjectUsageRowDTOSchema),creditDistribution:z70.array(UsageDistributionItemDTOSchema),userDistribution:z70.array(UsageDistributionItemDTOSchema),heatmap:z70.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z70.object({page:z70.number(),limit:z70.number(),totalItems:z70.number(),totalPages:z70.number(),hasMore:z70.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z70.object({organizations:z70.array(OrganizationUsageRowDTOSchema),top:z70.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z70.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z70.object({users:z70.array(ExtendedUserUsageRowDTOSchema),top:z70.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z70.string(),ownerName:z70.string().nullable(),ownerEmail:z70.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z70.object({projects:z70.array(ExtendedProjectUsageRowDTOSchema),top:z70.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z70.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z70.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z70.object({credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z70.object({id:z70.string(),name:z70.string(),createdAt:z70.string(),memberCount:z70.number(),projectCount:z70.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z70.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z70.object({id:z70.string(),name:z70.string().nullable(),email:z70.string(),image:z70.string().nullable(),createdAt:z70.string(),organizationCount:z70.number(),projectCount:z70.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z70.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z70.object({id:z70.string(),name:z70.string(),displayName:z70.string().nullable(),createdAt:z70.string(),organizationId:z70.string(),organizationName:z70.string(),ownerId:z70.string(),ownerName:z70.string().nullable(),ownerEmail:z70.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z70.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z71}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z71.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z71.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z71.object({command:z71.string().min(1).max(1e4),cwd:z71.string().optional(),projectEnv:EnvSchema.optional(),env:z71.record(z71.string(),z71.string()).optional(),name:z71.string().optional(),waitForCompletion:z71.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z71.object({identifier:z71.string(),status:SandboxProcessStatusSchema,command:z71.string().optional(),startedAt:z71.string().optional(),exitCode:z71.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z71.object({processes:z71.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z71.object({processId:z71.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z71.object({success:z71.boolean(),message:z71.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z72}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path52,message}=issue;return`${Array.isArray(path52)&&path52.length>0?`${path52.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path52,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path52,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers})}async rawRequest(path52,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path52} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path52,opts={}){let qs=lazyFetchQs(opts.against,{path:path52});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
42
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium","Pro"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});import{z as z5}from"zod";var MB,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z5.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z5.object({renderId:z5.uuid(),filename:z5.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z5.url()}),AttachmentModelRenderSuccessSchema=z5.object({status:z5.literal("succeeded"),views:z5.tuple([z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z5.url()})]),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative(),diagnostics:z5.unknown().optional()}),AttachmentModelRenderFailureSchema=z5.object({status:z5.literal("failed"),error:z5.literal("render_failed"),message:z5.string(),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative()}),AttachmentModelRenderResponseSchema=z5.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z5.object({browserElapsedMs:z5.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z6}from"zod";var AssetReadRequestSchema,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema=z6.object({cursor:z6.string().optional(),query:z6.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z6.object({url:z6.url(),mediaType:z6.string(),filename:z6.string()}),AssetReadBaseSchema=z6.object({assetId:z6.uuid(),filename:z6.string(),mediaType:z6.string(),representation:z6.enum(["text","table","document","archive","image","transcript","video","model"]),content:z6.string(),derivedFiles:z6.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z6.literal("page"),start:z6.number().int().nonnegative(),end:z6.number().int().nonnegative(),total:z6.number().int().nonnegative(),nextCursor:z6.string().nullable(),complete:z6.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z6.literal("query"),query:z6.string(),source:z6.enum(["original-file","canonical-text","derived-files"]),truncated:z6.boolean()}),AssetReadResultSchema=z6.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z7}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z7.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z8}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});import{z as z9}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z9.object({projectId:z9.uuid(),userId:z9.string().min(1)}),NotificationEventSchema=z9.discriminatedUnion("type",[z9.object({type:z9.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path52){let conditionPath=[...path52,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path52)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),group:z11.union([z11.string().min(1),z11.array(z11.string().min(1)).min(1)]).optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","env","project","day"]),OpsAgentHealthInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),env:z13.string().trim().min(1).max(64).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z13.object({path:OpsProjectFilePathSchema,content:z13.string().max(256*1024),overwrite:z13.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z13.string().trim().length(64),consentReference:z13.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z13.intersection(OpsProjectOperationPlanInputSchema,z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z14}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z14.object({kind:z14.literal("say"),label:z14.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z14.string().min(1).max(240).optional(),message:z14.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z14.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),BlockBaseSchema=z14.object({fallback:z14.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z14.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z14.literal("choices"),text:z14.string().max(500).optional(),actions:z14.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z14.discriminatedUnion("kind",[z14.object({kind:z14.literal("entry"),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("asset"),assetId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("url"),url:z14.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z14.literal("table"),columns:z14.array(z14.object({label:z14.string().min(1).max(24)})).min(2).max(4),rows:z14.array(z14.object({cells:z14.array(z14.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z14.literal("cards"),layout:z14.enum(["rail","stack"]).optional(),items:z14.array(z14.object({title:z14.string().min(1).max(60),subtitle:z14.string().min(1).max(120).optional(),imageUrl:z14.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z14.literal("entry"),label:z14.string().min(1).max(80),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120),path:z14.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z14.literal("assets"),items:z14.array(z14.object({url:z14.url({protocol:/^https$/}).max(2e3),alt:z14.string().min(1).max(120),label:z14.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z14.literal("callout"),title:z14.string().min(1).max(80),text:z14.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z14.literal("stat"),items:z14.array(z14.object({label:z14.string().min(1).max(24),value:z14.string().min(1).max(16),delta:z14.string().min(1).max(12).optional(),tone:z14.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z14.literal("chart"),unit:z14.string().min(1).max(12).optional(),points:z14.array(z14.object({label:z14.string().min(1).max(12),value:z14.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z14.literal("text"),placeholder:z14.string().min(1).max(120).optional(),multiline:z14.boolean().optional()}).strict(),ChatFormStepIdSchema=z14.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z14.object({id:ChatFormStepIdSchema,token:z14.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z14.string().trim().min(1).max(60),reason:z14.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z14.literal("capabilities"),items:z14.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z14.object({id:ChatFormStepIdSchema.optional(),question:z14.string().min(1).max(500),header:z14.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z14.boolean(),recommended:z14.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&!step.multiSelect&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}),FormBlockSchema=BlockBaseSchema.extend({type:z14.literal("form"),steps:z14.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z14.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z14.object({stepId:ChatFormStepIdSchema.optional(),header:z14.string().min(1).max(25),question:z14.string().min(1).max(500),answer:z14.string().min(1),selectedLabels:z14.array(z14.string().min(1).max(120)).max(8),freeText:z14.string(),skipped:z14.boolean()}),ChatFormAnswerMetadataSchema=z14.object({toolCallId:z14.string().max(255).optional(),shortTitle:z14.string().max(80).optional(),questions:z14.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z14.string().min(1).max(255)})}});import{z as z15}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z15.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z15.object({dev:z15.string().trim().min(1).optional(),build:z15.string().trim().min(1).optional(),install:z15.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z15.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z15.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z15.object({type:z15.enum(["header","cookie","query","host"]),key:z15.string().min(1).optional(),value:z15.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z15.array(FimoHostingConditionSchema).min(1).optional(),missing:z15.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),permanent:z15.boolean().optional(),statusCode:z15.union([z15.literal(301),z15.literal(302),z15.literal(307),z15.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z15.object({source:z15.string().min(1),headers:z15.array(z15.object({key:z15.string().min(1),value:z15.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z15.object({rewrites:z15.array(FimoHostingRewriteSchema).optional(),redirects:z15.array(FimoHostingRedirectSchema).optional(),headers:z15.array(FimoHostingHeaderSchema).optional(),cleanUrls:z15.boolean().optional(),trailingSlash:z15.boolean().optional()}).strict(),FimoAppConfigSchema=z15.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z16}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z16.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),previewEnabled:z16.boolean().default(!0),enabledChatModels:z16.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({versionId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),kind:z16.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z16.object({versionCount:z16.number().int().nonnegative(),snapshotBytes:z16.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z16.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z16.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional(),warning:z16.string().optional(),durationMs:z16.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z16.object({label:z16.string().trim().min(1).max(120).optional(),notes:z16.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z16.boolean(),publicationId:z16.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z17.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z17.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z17.object({id:z17.union([z17.literal(PREVIEW_ENVIRONMENT_KEY),z17.uuid()]),name:z17.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z18.object({projectId:z18.uuid(),name:z18.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z18.literal("production"),sourceBranch:EnvSchema,isPublished:z18.boolean(),url:z18.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PREVIEW_ENVIRONMENT_KEY),kind:z18.literal("preview"),matchedBranchCount:z18.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z18.literal("custom"),matchedBranchCount:z18.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z18.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z18.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z18.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z18.object({deletedId:z18.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z19}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z19.object({kind:z19.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z19.object({kind:z19.enum(["variable","secret"]),value:z19.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z19.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z19.object({kind:z19.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),key:z19.string(),kind:z19.literal("secret"),exposure:z19.literal("private"),environment:EnvironmentKeySchema,maskedValue:z19.string().optional(),createdAt:z19.date().transform(value=>value.toISOString()),updatedAt:z19.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z19.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z20}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z20.object({success:z20.literal(!0),downloadUrl:z20.string(),expiresAt:z20.string(),fileSize:z20.number(),duration:z20.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z20.object({success:z20.literal(!0),projectId:z20.string(),projectName:z20.string(),displayName:z20.string(),projectUrl:z20.string(),duration:z20.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z20.object({contentTypes:z20.number(),entries:z20.number(),assets:z20.number(),translations:z20.number(),forms:z20.number(),codeFiles:z20.number(),assetFiles:z20.number()}),ImportPreviewSurfaceDTOSchema=z20.object({name:z20.string(),included:z20.boolean(),count:z20.number().optional(),note:z20.string().optional()}),ImportPreviewDTOSchema=z20.object({projectName:z20.string(),displayName:z20.string().nullable(),category:z20.string().nullable(),exportedAt:z20.string(),version:z20.string(),envScope:z20.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z20.array(ImportPreviewSurfaceDTOSchema),fileSize:z20.number(),fileName:z20.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z20.object({success:z20.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z21}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z21.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z21.object({type:z21.literal("manual")}),ScheduleTriggerSchema=z21.object({type:z21.literal("schedule"),cron:z21.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z21.string().optional()}),WebhookTriggerSchema=z21.object({type:z21.literal("webhook"),path:z21.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z21.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z22}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z22.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z22.object({token:z22.string().min(1),risk:CapabilityRiskTierSchema,description:z22.string()}),AgentSubAgentSummarySchema=z22.object({name:z22.string().min(1),grant:z22.enum(["inherit","explicit"]),effectiveCaps:z22.array(z22.string().min(1))}),AgentInstallSummaryDTOSchema=z22.object({agentName:z22.string().min(1),env:z22.string().min(1),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z22.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z22.array(CapabilitySummaryEntrySchema),criticalCapabilities:z22.array(CapabilitySummaryEntrySchema),subAgents:z22.array(AgentSubAgentSummarySchema),declaresDelegate:z22.boolean(),cycle:z22.array(z22.string()).nullable(),missingSubAgents:z22.array(z22.string()),warnings:z22.array(z22.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z23}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z23.object({kind:TriggerKindSchema,summary:z23.string()}),AgentListItemTriggerStateSchema=z23.object({triggerIndex:z23.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z23.boolean(),wired:z23.boolean(),syncError:z23.string().nullable()}),AgentListItemDTOSchema=z23.object({name:z23.string().min(1),description:z23.string().nullable(),goalFirstLine:z23.string().nullable(),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),triggers:z23.array(AgentListItemTriggerSchema),triggerStates:z23.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z23.array(AgentListItemDTOSchema))}});import{z as z24}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z24.object({args:z24.unknown().optional(),requestId:z24.string().min(1).max(128).optional()}),DispatchSkippedSchema=z24.object({skipped:z24.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z24.object({sessionId:z24.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z24.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z25}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z25.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z25.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z25.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z25.object({verb:SurfaceDeltaVerbSchema,key:z25.string(),detail:z25.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z25.record(z25.string(),z25.unknown()).optional()}),PerSurfaceDeltaSchema=z25.object({surface:SurfaceNameSchema,status:z25.enum(["ok","timed_out","failed","unchanged"]),durationMs:z25.number().int().nonnegative().optional(),changedCount:z25.number().int().nonnegative(),conflictCount:z25.number().int().nonnegative(),items:z25.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z25.boolean().optional(),error:z25.string().optional()}),CrossSurfaceFindingSchema=z25.object({id:z25.string(),kind:z25.string(),description:z25.string(),severity:z25.enum(["warning","error"]),source:z25.object({surface:SurfaceNameSchema,key:z25.string()}),target:z25.object({surface:SurfaceNameSchema,key:z25.string()}),actions:z25.array(z25.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z25.object({env:EnvSchema,vs:EnvSchema,syncState:z25.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),agents:z25.array(z25.object({id:z25.string(),name:z25.string(),status:z25.enum(["active","paused","failed"]),lastRunAt:z25.coerce.date().nullable()})).optional(),crossSurface:z25.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z25.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),crossSurface:z25.array(CrossSurfaceFindingSchema).optional(),fingerprint:z25.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z25.object({path:z25.string(),state:z25.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z25.string(),additions:z25.number().int().nonnegative(),deletions:z25.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z25.object({oid:z25.string().optional(),content:z25.string().optional(),truncated:z25.boolean(),binary:z25.boolean()}),CodeConflictDetailSchema=z25.object({path:z25.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z25.string(),targetTipSha:z25.string(),mergeBaseSha:z25.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z25.object({id:z25.string(),slug:z25.string(),contentType:z25.string(),data:z25.record(z25.string(),z25.unknown()),updatedAt:z25.coerce.date()}),ContentRowDiffSchema=z25.object({collection:z25.string(),rowId:z25.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z25.object({name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),fields:z25.record(z25.string(),z25.unknown())}),SchemaTypeDiffSchema=z25.object({typeName:z25.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z25.object({id:z25.string(),name:z25.string(),type:z25.enum(["file","folder"]),mimeType:z25.string().nullable(),storageKey:z25.string().nullable(),url:z25.string().nullable(),fileSize:z25.number().nullable(),width:z25.number().nullable(),height:z25.number().nullable(),altText:z25.string().nullable(),caption:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),AssetDiffSchema=z25.object({assetId:z25.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z25.object({locale:z25.string(),key:z25.string(),parent:z25.string().nullable(),child:z25.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z25.object({formName:z25.string(),label:z25.string().nullable(),schemaFingerprint:z25.string(),fields:z25.record(z25.string(),z25.unknown()),settings:z25.record(z25.string(),z25.unknown()).optional()}),FormSchemaDiffSchema=z25.object({formName:z25.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z25.enum(CONFLICT_KINDS),ConflictSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),kind:ConflictKindSchema.optional(),description:z25.string(),parentValue:z25.unknown().optional(),childValue:z25.unknown().optional(),conflictingFields:z25.array(z25.string()).optional(),code:z25.object({path:z25.string(),unresolvable:z25.boolean().optional(),reason:z25.string().optional()}).optional()}),FieldPickSchema=z25.object({field:z25.string(),choice:z25.enum(["parent","child","pick","ai-pick"]),pickedValue:z25.unknown().optional(),aiSessionId:z25.string().optional()}),ConflictResolutionSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),choice:z25.enum(["parent","child","pick"]),pickedValue:z25.unknown().optional(),fieldPicks:z25.array(FieldPickSchema).optional()}),MergeResultSchema=z25.object({ok:z25.boolean(),mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z25.array(z25.object({surface:SurfaceNameSchema,count:z25.number().int().nonnegative()})),conflicts:z25.array(ConflictSchema).optional(),summary:z25.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z25.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z25.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z25.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z25.boolean().optional()}),ResolvedStrategySchema=z25.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z25.boolean()}),MergeRequestSchema=z25.object({from:EnvSchema,allowDirectMerge:z25.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z25.object({mergeId:z25.string().uuid(),streamUrl:z25.string(),strategy:ResolvedStrategySchema,acceptedAt:z25.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z25.object({mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z25.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z25.array(ConflictSchema),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedBy:z25.string().nullable(),lastEditedAt:z25.coerce.date().nullable(),initiator:z25.object({userId:z25.string().nullable(),role:z25.string().nullable(),agentName:z25.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z25.object({resolutions:z25.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z25.object({mergeId:z25.string().uuid(),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedAt:z25.coerce.date(),lastEditedBy:z25.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z25.object({mergeId:z25.string().uuid(),resolutions:z25.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z25.object({mergeId:z25.string().uuid()}),PublishReleaseRequestSchema=z25.object({version:z25.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z25.string().max(2e4).optional()}),PublishReleaseResultSchema=z25.object({releaseTag:z25.string(),sha:z25.string(),publishedAt:z25.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z26}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z26.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z26.object({cpuMs:z26.number().nonnegative().default(0),netBytes:z26.number().nonnegative().default(0),walltimeMs:z26.number().nonnegative().default(0),llmTokensIn:z26.number().nonnegative().optional(),llmTokensOut:z26.number().nonnegative().optional(),stepCount:z26.number().int().nonnegative().optional(),toolCallCounts:z26.record(z26.string().min(1).max(120),z26.number().int().nonnegative()).optional(),finishAction:z26.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z26.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z26.object({capturedAt:z26.coerce.date(),fingerprint:z26.string().min(1).max(256),counts:z26.object({code:z26.number().int().nonnegative(),content:z26.number().int().nonnegative(),schemas:z26.number().int().nonnegative(),labels:z26.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z26.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z26.object({diff:DiffReportSchema,code:z26.array(CodeFileDiffSchema.extend({raw:z26.string().max(24576)})).max(200),schemas:z26.array(SchemaTypeDiffSchema).max(200),content:z26.array(z26.object({key:z26.string().min(1).max(512),collection:z26.string().min(1).max(256),slug:z26.string().max(512).optional(),verb:z26.enum(["added","modified","deleted"]),fields:z26.array(z26.object({name:z26.string().min(1).max(256),before:z26.unknown().optional(),after:z26.unknown().optional()})).max(20)})).max(200),labels:z26.array(z26.object({key:z26.string().min(1).max(512),locale:z26.string().min(1).max(64).optional(),before:z26.unknown().nullable(),after:z26.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:EnvSchema,agentName:z26.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z26.unknown().optional(),capabilities:z26.array(z26.string()).optional(),dataSources:z26.array(z26.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z26.string().nullable(),startedAt:z26.coerce.date().nullable(),finishedAt:z26.coerce.date().nullable(),cancelledAt:z26.coerce.date().nullable(),costUsd:z26.number().nonnegative(),costCeilingUsd:z26.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z26.boolean(),lastCheckpointId:z26.uuid().nullable(),branchEnvId:z26.uuid().nullable(),parentSessionId:z26.uuid().nullable(),terminalReason:z26.string().nullable(),errorMessage:z26.string().nullable(),report:z26.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z26.object({id:z26.uuid(),sessionId:z26.uuid(),checkpointIdx:z26.number().int().nonnegative(),payloadRef:z26.string(),payloadSizeBytes:z26.number().int().nonnegative(),checksum:z26.string().length(64),createdAt:z26.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z26.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z26.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z26.object({session:AgentSessionDTOSchema,checkpoints:z26.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z26.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z26.object({reason:z26.string().min(1).max(120).optional()})}});import{z as z27}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z27.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z27.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z27.object({id:z27.uuid(),envId:z27.uuid(),sessionId:z27.uuid().nullable(),skillName:z27.string().min(1),classification:AgentBranchClassificationSchema,rationale:z27.string().nullable(),summary:z27.string().nullable(),surfaceDeltas:z27.record(z27.string(),z27.unknown()),createdAt:z27.coerce.date(),decidedAt:z27.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z27.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z27.object({path:z27.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z27.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z27.object({code:z27.literal("merge_conflict"),message:z27.string(),conflicts:z27.record(z27.string(),z27.number().int().nonnegative())})}});import{z as z28}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z28.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z28.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z28.object({description:z28.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z28.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),threadId:z28.uuid(),invocationId:z28.uuid(),agentKey:z28.string().min(1).max(120),anchorEnv:z28.string().min(1).max(64),retainedEnv:z28.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z28.string().min(1).nullable(),continuationInvocationId:z28.uuid().nullable(),askedAt:z28.coerce.date(),expiresAt:z28.coerce.date(),closedAt:z28.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z28.object({questionId:z28.uuid(),invocationId:z28.uuid(),askedAt:z28.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z28.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z28.object({question:AgentQuestionSchema,continuationInvocationId:z28.uuid(),deduped:z28.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z29}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z29.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z29.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z29.enum(["secret_text"]),IntegrationCredentialUsageSchema=z29.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z29.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z29.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z29.object({mode:IntegrationAuthModeSchema,label:z29.string().min(1),description:z29.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z29.object({id:z29.string().min(1),label:z29.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z29.boolean()}),IntegrationToolDefinitionDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),description:z29.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z29.object({title:z29.string().min(1),description:z29.string().min(1),command:z29.string().min(1).optional()}),IntegrationInfoDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z29.array(IntegrationAuthModeDTOSchema),credentials:z29.array(IntegrationCredentialDefinitionDTOSchema),tools:z29.array(IntegrationToolDefinitionDTOSchema),recipes:z29.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),installed:z29.boolean(),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z29.string().nullable(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),connectionStatus:z29.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),installedAt:z29.coerce.date().nullable(),updatedAt:z29.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z29.string(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z29.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z29.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z29.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z29.object({value:z29.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z29.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z29.object({id:z29.uuid(),organizationId:z29.string().min(1),integrationKey:z29.string().min(1),alias:z29.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z29.string().min(1),externalAccountName:z29.string().nullable(),externalBotUserId:z29.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z29.array(z29.string()),connectedAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z29.object({alias:z29.string().min(1).max(120).optional(),token:z29.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z29.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),alias:z29.string().min(1).max(120),token:z29.string().min(1)}),z29.object({mode:z29.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z29.object({integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),integrationKey:z29.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z29.object({mode:z29.literal("oauth"),integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),BindProjectChannelRequestSchema=z29.object({ref:z29.string().min(1),connectionAlias:z29.string().min(1).optional(),agentName:z29.string().min(1).max(160).nullable().optional(),force:z29.boolean().optional()}),ListProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1)}),SearchProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1),connectionAlias:z29.string().min(1),query:z29.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),connectionId:z29.uuid(),externalWorkspaceId:z29.string().min(1),externalChannelId:z29.string().min(1),externalChannelName:z29.string().nullable(),agentName:z29.string().nullable(),enabled:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z29.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z29.object({id:z29.string().min(1),name:z29.string().min(1),visibility:z29.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z29.string().min(1).nullable(),canMove:z29.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z29.object({markdown:z29.boolean().optional(),summary:z29.boolean().optional(),links:z29.boolean().optional(),branding:z29.boolean().optional(),images:z29.boolean().optional(),html:z29.union([z29.literal("cleaned"),z29.literal("raw"),z29.boolean()]).optional(),json:z29.union([z29.boolean(),z29.object({prompt:z29.string().min(1).max(1e4),schema:z29.record(z29.string(),z29.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z29.object({url:z29.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z29.object({query:z29.string().min(1),maxResults:z29.number().int().positive().max(20).optional(),sources:z29.array(z29.enum(["web","news","images"])).min(1).max(3).optional(),categories:z29.array(z29.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z29.enum(["hour","day","week","month","year"]).optional(),location:z29.string().min(1).max(160).optional(),country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(100).optional(),types:z29.array(z29.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),sources:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),passages:z29.number().int().min(1).max(5).optional(),skills:z29.literal("only").optional(),language:z29.string().min(1).optional(),topic:z29.string().min(1).optional(),license:z29.string().min(1).optional(),minStars:z29.number().int().min(0).optional(),maxStars:z29.number().int().min(0).optional(),archived:z29.boolean().optional(),fork:z29.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(500).optional(),authors:z29.array(z29.string().min(1)).min(1).optional(),categories:z29.array(z29.string().min(1)).min(1).optional(),from:z29.iso.date().optional(),to:z29.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),query:z29.string().min(1).max(500).optional(),maxPassages:z29.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),intent:z29.string().min(1).max(500),mode:z29.enum(["similar","citers","references"]).optional(),maxResults:z29.number().int().min(1).max(500).optional(),rerank:z29.boolean().optional(),anchors:z29.array(z29.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z29.object({url:z29.string().url(),search:z29.string().min(1).optional(),limit:z29.number().int().positive().max(200).optional(),includeSubdomains:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z29.object({url:z29.string().url(),limit:z29.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z29.object({text:z29.string().min(1).max(200).optional(),cron:z29.string().min(1).max(120).optional(),timezone:z29.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z29.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z29.union([z29.object({type:z29.enum(["scrape","crawl"]).default("scrape"),urls:z29.array(z29.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z29.object({type:z29.literal("search"),queries:z29.array(z29.string().min(1).max(256)).min(1).max(12),searchWindow:z29.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z29.number().int().min(1).max(50).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z29.object({name:z29.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),notification:z29.object({email:z29.object({enabled:z29.boolean().default(!0),recipients:z29.array(z29.string().email()).min(1).max(20),includeDiffs:z29.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z29.object({monitorId:z29.string().uuid(),name:z29.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),status:z29.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z29.object({monitorId:z29.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z29.string().uuid()}),RunProjectIntegrationToolRequestSchema=z29.object({tool:z29.string().min(1),input:z29.record(z29.string(),z29.unknown()),connectionAlias:z29.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z29.object({provider:z29.string().min(1),providerCredits:z29.number().nonnegative().optional(),providerCostUsd:z29.number().nonnegative().optional(),requests:z29.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z29.object({credits:z29.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),json:z29.unknown().optional(),branding:z29.record(z29.string(),z29.unknown()).optional(),warning:z29.string().optional()}),FirecrawlSearchToolOutputSchema=z29.object({query:z29.string(),provider:z29.literal("firecrawl"),warning:z29.string().optional(),results:z29.array(z29.object({title:z29.string(),url:z29.string(),snippet:z29.string().optional(),content:z29.string().optional(),score:z29.number().optional(),publishedAt:z29.string().optional()}))}),FirecrawlResearchPaperSchema=z29.object({paperId:z29.string(),primaryId:z29.string().optional(),ids:z29.record(z29.string(),z29.array(z29.string())).optional(),title:z29.string().optional(),abstract:z29.string().optional(),score:z29.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z29.object({text:z29.string(),score:z29.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(z29.object({id:z29.string(),type:z29.string().min(1).optional(),url:z29.string(),title:z29.string().optional(),passages:z29.array(z29.object({text:z29.string()}).passthrough())}).passthrough()),coverage:z29.record(z29.string(),z29.string()).optional(),reranked:z29.boolean().optional(),repos:z29.array(z29.record(z29.string(),z29.unknown())).optional(),sources:z29.array(z29.record(z29.string(),z29.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),paper:z29.record(z29.string(),z29.unknown()),paperId:z29.string().optional(),query:z29.string().optional(),passages:z29.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema),poolSize:z29.number().int().nonnegative(),truncated:z29.boolean(),note:z29.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),count:z29.number(),links:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),description:z29.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),total:z29.number(),pages:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),warning:z29.string().optional()})),warning:z29.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z29.object({cron:z29.string().optional(),text:z29.string().optional(),timezone:z29.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z29.object({id:z29.string().optional(),type:z29.enum(["scrape","crawl","search"]).optional(),urls:z29.array(z29.string()).optional(),queries:z29.array(z29.string()).optional(),searchWindow:z29.string().optional(),maxResults:z29.number().optional(),includeDomains:z29.array(z29.string()).optional(),excludeDomains:z29.array(z29.string()).optional(),scrapeOptions:z29.record(z29.string(),z29.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z29.object({id:z29.string(),name:z29.string(),status:z29.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z29.string().nullable().optional(),lastRunAt:z29.string().nullable().optional(),currentCheckId:z29.string().nullable().optional(),targets:z29.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z29.string().nullable().optional(),judgeEnabled:z29.boolean().optional(),estimatedCreditsPerMonth:z29.number().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z29.object({id:z29.string(),monitorId:z29.string(),scheduledFor:z29.string().nullable().optional(),startedAt:z29.string().nullable().optional(),finishedAt:z29.string().nullable().optional(),estimatedCredits:z29.number().optional(),reservedCredits:z29.number().optional(),actualCredits:z29.number().optional(),billingStatus:z29.string().nullable().optional(),summary:z29.object({totalPages:z29.number().optional(),same:z29.number().optional(),changed:z29.number().optional(),new:z29.number().optional(),removed:z29.number().optional(),error:z29.number().optional()}).passthrough().optional(),error:z29.string().nullable().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitors:z29.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),deleted:z29.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),checks:z29.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),check:FirecrawlMonitorCheckOutputSchema,next:z29.string().optional()}),FirecrawlToolKeySchema=z29.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z29.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),tool:z29.string().min(1),connectionAlias:z29.string().min(1).nullable().optional(),output:z29.record(z29.string(),z29.unknown()),executedAt:z29.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z29.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z29.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z29.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z29.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z29.array(ProjectChannelCandidateDTOSchema))}});import{z as z30}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z30.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z30.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z30.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z30.object({userId:z30.string().min(1),name:z30.string(),email:z30.string().min(1),subscribed:z30.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z30.object({maxSubscribers:z30.number().int().positive(),subscriberCount:z30.number().int().nonnegative(),effectiveRecipientCount:z30.number().int().nonnegative(),currentUserSubscribed:z30.boolean(),candidates:z30.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z30.object({userIds:z30.array(z30.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z30.object({topic:UserManagedNotificationTopicSchema,enabled:z30.boolean(),source:z30.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z30.object({topics:z30.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z30.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z30.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z30.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z30.string().nullable(),maskedEmail:z30.string().min(1),applied:z30.boolean(),expiresAt:z30.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z30.object({scheduleId:z30.string().min(1),scheduleName:z30.string(),projectId:z30.string().min(1),projectName:z30.string(),env:z30.string().min(1)}),FollowedSchedulesSchema=z30.object({schedules:z30.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z31}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z31.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z31.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z31.uuid(),env:z31.string().min(1),name:z31.string().min(1),cron:z31.string().min(1),command:z31.string().min(1),secretKeys:z31.array(z31.string().min(1)),enabled:z31.boolean(),lastRunAt:z31.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z31.string().nullable(),overPolicyReasons:z31.array(z31.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120),cron:z31.string().min(1).max(120),command:z31.string().min(1).max(500),secretKeys:z31.array(ProjectSecretKeySchema).default([]),enabled:z31.boolean().optional()}),UpdateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120).optional(),cron:z31.string().min(1).max(120).optional(),command:z31.string().min(1).max(500).optional(),secretKeys:z31.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z31.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z31.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z31.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z31.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z31.object({maxRuns:z31.number().int().positive(),retentionDays:z31.number().int().positive().nullable(),outputRetentionDays:z31.number().int().positive(),maxOutputBytes:z31.number().int().positive()}),SchedulePolicyStateSchema=z31.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z31.object({code:z31.enum(["Free","Premium","Pro"]),source:z31.enum(["cached_subscription","free_fallback"]),activeSchedules:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),concurrency:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),compute:z31.object({settledMs:z31.number().int().nonnegative(),reservedMs:z31.number().int().nonnegative(),includedMs:z31.number().int().positive(),remainingMs:z31.number().int().nonnegative(),resetsAt:z31.coerce.date()}),upgrade:z31.object({code:z31.literal("Premium"),activeSchedulesLimit:z31.number().int().positive(),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),maxConcurrentRuns:z31.number().int().positive(),computeIncludedMs:z31.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z31.array(z31.string())}),ProjectScheduleUsageSchema=z31.object({runCount:z31.number().int().nonnegative(),runsWithOutput:z31.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z31.object({id:z31.uuid(),scheduleId:z31.uuid(),projectId:z31.uuid(),env:z31.string().min(1),scheduleName:z31.string().min(1),command:z31.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z31.object({id:z31.string().min(1),name:z31.string().min(1)}).nullable(),queuedAt:z31.coerce.date(),startedAt:z31.coerce.date().nullable(),finishedAt:z31.coerce.date().nullable(),exitCode:z31.number().int().nullable(),errorCode:z31.string().nullable(),error:z31.string().nullable(),outputBytes:z31.number().int().nonnegative(),outputTruncated:z31.boolean(),outputExpiresAt:z31.coerce.date().nullable(),metadataExpiresAt:z31.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z31.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z31.coerce.date().nullable(),items:z31.array(z31.object({key:z31.string().min(1),updatedAt:z31.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z31.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z31.object({trigger:z31.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z31.object({limit:z31.coerce.number().int().min(1).max(100).default(25),cursor:z31.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z31.object({items:z31.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z31.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z31.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z31.object({items:z31.array(ProjectScheduleRunDTOSchema),nextCursor:z31.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z32}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z32.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z32.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z32.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("user"),userId:z32.string().min(1)}).strict(),z32.object({kind:z32.literal("agent"),agentKey:z32.string().min(1).max(120),agentId:z32.uuid().optional()}).strict(),z32.object({kind:z32.literal("system")}).strict()]),NotificationSummarySchema=z32.string().trim().min(1).max(1200),NotificationRunOutcomeSchema=z32.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z32.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z32.discriminatedUnion("topic",[z32.object({topic:z32.literal("agent_question"),questionId:z32.uuid(),title:z32.string().trim().min(1).max(80),description:z32.string().trim().min(1).max(240)}).strict(),z32.object({topic:z32.literal("agent_run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().optional(),proposalId:z32.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().optional(),summary:NotificationSummarySchema.optional()}).strict()]),NotificationEnvelopeSchema=z32.object({id:z32.uuid(),projectId:z32.uuid(),sourceKey:z32.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z32.literal(1),payload:NotificationPayloadSchema,createdAt:z32.coerce.date()}),NotificationRecipientStateSchema=z32.object({id:z32.uuid(),notificationId:z32.uuid(),projectId:z32.uuid(),userId:z32.string().min(1),readAt:z32.coerce.date().nullable(),archivedAt:z32.coerce.date().nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationDeliveryStateSchema=z32.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z32.object({id:z32.uuid(),notificationRecipientId:z32.uuid(),projectId:z32.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z32.number().int().nonnegative(),nextAttemptAt:z32.coerce.date().nullable(),lastAttemptAt:z32.coerce.date().nullable(),sentAt:z32.coerce.date().nullable(),failureCode:z32.string().max(80).nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationPreferenceSchema=z32.object({topic:WorkNotificationTopicSchema,channel:z32.literal("email"),enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z32.object({topics:z32.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("question"),questionId:z32.uuid()}).strict(),z32.object({kind:z32.literal("run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z32.object({kind:z32.literal("retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().nullable(),proposalId:z32.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z32.object({kind:z32.literal("merge_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().nullable()}).strict()]),NotificationViewSchema=z32.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z32.object({items:z32.array(NotificationViewSchema),nextCursor:z32.string().nullable(),unreadCount:z32.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z32.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z32.string().min(1).max(120).optional(),sourceKey:z32.string().min(1).max(255).optional(),unread:z32.stringbool().optional(),archived:z32.stringbool().optional(),limit:z32.coerce.number().int().min(1).max(100).optional(),cursor:z32.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z32.object({recipient:NotificationRecipientStateSchema,unreadCount:z32.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z32.object({read:z32.boolean().optional(),archived:z32.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z33}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z33.object({id:z33.uuid(),occurredAt:z33.coerce.date(),projectId:z33.uuid().nullable(),env:z33.string().nullable(),actor:z33.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z33.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z33.unknown().optional(),ipAddress:z33.string().nullable().optional(),userAgent:z33.string().nullable().optional(),error:z33.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z33.object({rows:z33.array(AuditLogRowDTOSchema),nextCursor:z33.string().nullable()})),AuditLogQuerySchema=z33.object({env:z33.string().optional(),action:AuditActionSchema.optional(),actor:z33.string().optional(),from:z33.coerce.date().optional(),to:z33.coerce.date().optional(),limit:z33.coerce.number().int().min(1).max(200).optional(),cursor:z33.string().optional()})}});import{z as z34}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z34.object({surface:SurfaceNameSchema,key:z34.string(),label:z34.string()}),InlineSchema=z34.object({text:z34.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z34.discriminatedUnion("type",[z34.object({type:z34.literal("paragraph"),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("preview"),ref:DiffRefSchema,caption:z34.string().optional()}),z34.object({type:z34.literal("code"),code:z34.string(),lang:z34.string().optional(),caption:z34.string().optional()}),z34.object({type:z34.literal("risk"),level:z34.enum(["warning","error"]),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("list"),items:z34.array(z34.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z34.object({headline:z34.string(),blocks:z34.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z34.object({summary:EnvDiffSummarySchema,fingerprint:z34.string(),generatedAt:z34.coerce.date(),cached:z34.boolean().optional(),credits:z34.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z35}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z35.object({date:z35.string(),visitors:z35.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z35.object({key:z35.string(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z35.object({path:z35.string(),pageName:z35.string().nullable().optional(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z35.object({preset:z35.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z35.string(),requestedTo:z35.string(),effectiveFrom:z35.string(),effectiveTo:z35.string(),isRetentionLimited:z35.boolean(),groupBy:z35.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z35.object({date:z35.string(),content:z35.string(),updatedAt:z35.string(),updatedByUserId:z35.string()}),ProjectPageviewAnalyticsDTOSchema=z35.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative(),bounceRate:z35.number().min(0).max(100),viewsPerVisit:z35.number().nonnegative(),averageVisitDurationSeconds:z35.number().nonnegative(),visitorsSeries:z35.array(ProjectDailyVisitorsDTOSchema),topPages:z35.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z35.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z36}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z36.object({id:z36.string(),email:z36.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z36.coerce.date(),createdAt:z36.coerce.date(),inviterUserId:z36.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z36.object({id:z36.string(),token:z36.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z36.object({success:z36.boolean(),projectId:z36.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z37}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z37.object({id:z37.string(),name:z37.string(),image:z37.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z37.object({count:z37.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z37.object({counts:z37.object({signed_up:z37.int(),activated:z37.int()}),credits:z37.object({total:z37.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z37.email(),emailVerified:z37.boolean(),createdAt:z37.coerce.date(),updatedAt:z37.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z38}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z38.object({id:z38.string(),principalType:ProjectPrincipalTypeSchema,principalId:z38.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z38.coerce.date(),expiresAt:z38.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z38.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z38.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z38.record(z38.string(),z38.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z38.object({access:z38.array(ProjectAccessItemDTOSchema),invites:z38.array(ProjectInviteDTOSchema),organization:z38.object({name:z38.string().nullable(),logo:z38.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),projectId:z38.uuid()}))}});import{z as z39}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z39.object({publicationStatus:PublicationStatusSchema,appUrl:z39.string().nullable(),lastPublishedAt:z39.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z40}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z40.object({url:z40.url(),expiresAt:z40.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema})}});import{z as z41}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z41.string(),slug:z41.string().nullable(),logo:z41.string().nullable(),metadata:z41.record(z41.string(),z41.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z41.object({id:z41.string(),name:z41.string(),email:z41.email(),image:z41.string().nullable()}),OrganizationMemberDTOSchema=z41.object({id:z41.string(),userId:z41.string(),organizationId:z41.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z41.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z42}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z42.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z42.object({reason:CancellationReasonCodeSchema,details:z42.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z42.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z42.object({offerVersion:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),renewsOn:z42.string()}),PlanMigrationPreviewDTOSchema=z42.object({currency:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),startsAt:z42.string(),renewsAt:z42.string(),nextRenewalAmount:z42.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z42.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z42.object({id:z42.string(),organizationId:z42.string(),legacySubscriptionId:z42.string(),offeredPlanCode:z42.string(),offeredPlanName:z42.string(),offeredPriceAmount:z42.number(),offeredCurrency:z42.string(),offerVersion:z42.string(),state:PlanMigrationStateSchema,checkoutToken:z42.string().nullable(),deadlineAt:z42.string(),transitions:z42.array(z42.object({event:z42.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z42.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z42.object({included:z42.number().optional(),unitPrice:z42.number().optional(),dailyCap:z42.number().nullable().optional()}),EntitlementsDTOSchema=z42.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z42.object({retentionDays:z42.number().int().positive(),canUseExtendedDateRanges:z42.boolean()}).optional(),history:z42.object({retentionDays:z42.number().int().positive()}).optional(),members:z42.object({canInvite:z42.boolean(),maxMembers:z42.number().int().positive().nullable()}).optional(),domains:z42.object({canUseCustomDomains:z42.boolean(),maxDomains:z42.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z42.object({id:z42.string(),external_id:z42.string(),customerId:z42.string(),planId:z42.string(),planCode:z42.union([TemplateCodeSchema,z42.literal("Unknown")]),currentPeriod:z42.object({start:z42.string(),end:z42.string().nullable()}),cancelAt:z42.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z42.string(),nextPaymentAt:z42.string().nullable(),baseAmount:z42.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z42.object({totalCap:z42.number(),dailyCap:z42.number(),usedTotal:z42.number()}),CreditBalanceDTOSchema=z42.object({total:z42.number(),base:z42.number(),dailyBase:z42.number(),purchases:z42.number(),awards:z42.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z42.object({total:z42.number(),nearLimit:z42.boolean(),canChat:z42.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z42.object({dailyFreeAvailable:z42.number(),monthlyAvailable:z42.number(),purchasedAvailable:z42.number(),awardedAvailable:z42.number()}),ProjectDailyCreditAllowanceDTOSchema=z42.object({periodCap:z42.number(),dailyGrant:z42.number(),usedThisPeriod:z42.number(),remainingThisPeriod:z42.number()}),ProjectCreditBalanceDTOSchema=z42.object({projectId:z42.uuid(),organizationId:z42.string(),balance:z42.object({totalAvailable:z42.number(),nearLimit:z42.boolean(),canUseAi:z42.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z42.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z42.enum(["ok","near_limit","exhausted","unavailable"]),AgentRuntimeUsageDTOSchema=z42.object({planCode:z42.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z42.object({source:z42.enum(["cached_subscription","free_fallback"]),settledMs:z42.number().int().nonnegative(),reservedMs:z42.number().int().nonnegative(),includedMs:z42.number().int().positive(),remainingMs:z42.number().int().nonnegative(),resetsAt:z42.coerce.date()}).nullable()}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().nonnegative(),refillAmountUsd:z42.number().nonnegative()}),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().nonnegative().nullable(),refillAmountUsd:z42.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().min(.01).multipleOf(.01),refillAmountUsd:z42.number().min(.01).multipleOf(.01)}).strict(),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z42.object({invoiceId:z42.string(),newBalance:z42.int(),creditCount:z42.int(),amountUsd:z42.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z42.object({url:z42.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z43}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z43.object({brand:z43.string(),last4:z43.string(),exp:z43.string(),isDefault:z43.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z44}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z44.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z44.object({type:z44.literal("renameField"),contentType:z44.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z44.object({enabled:z44.boolean()}).strict(),ContentFieldGroupSchema=z44.object({id:z44.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z44.string().min(1).max(255),default:z44.boolean().optional()}).strict(),ContentTypeDTOSchema=z44.object({id:z44.string(),name:z44.string(),label:z44.string(),isSingleton:z44.boolean(),i18n:ContentTypeI18nSchema,groups:z44.array(ContentFieldGroupSchema).default([]),fields:z44.record(z44.string(),FieldDefinitionSchema),createdAt:z44.string(),updatedAt:z44.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z44.object({contentTypes:z44.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z44.object({id:z44.string(),entryId:z44.string(),documentId:z44.string(),slug:z44.string(),locale:z44.string().optional(),createdAt:z44.string(),updatedAt:z44.string(),__fimo:z44.object({contentType:z44.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({limit:z44.number(),offset:z44.number(),total:z44.number(),hasMore:z44.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z44.object({contentType:z44.string(),count:z44.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z44.object({counts:z44.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z44.object({count:z44.number().int().nonnegative(),sourceLocale:z44.string(),targetLocale:z44.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z44.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z44.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z44.union([z44.string(),z44.number(),z44.boolean(),z44.null()]),entryWhereOperatorSchema=z44.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z44.array(entryWhereScalarSchema).optional(),$nin:z44.array(entryWhereScalarSchema).optional(),$contains:z44.string().optional(),$startsWith:z44.string().optional(),$null:z44.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z44.object({data:z44.record(z44.string(),z44.unknown()),locale:z44.string().min(1).optional(),documentId:z44.uuid().optional()}),entryIdsSchema=z44.array(z44.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z44.object({sql:z44.string().min(1)}),BulkCreateEntriesRequestSchema=z44.object({entries:z44.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z44.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z44.object({updates:z44.array(z44.object({id:z44.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,locale:z44.string().min(1).optional()}),z44.object({where:EntryWhereSchema,locale:z44.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z44.object({data:z44.array(z44.record(z44.string(),z44.unknown())),meta:z44.object({rowCount:z44.number().int().nonnegative(),truncated:z44.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({created:z44.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({updated:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({deleted:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z45}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z45.object({index:z45.number().int().nonnegative(),contentType:z45.string(),field:z45.string(),value:z45.string(),against:z45.enum(["stored","batch"]),ownerDocumentId:z45.uuid().optional(),ownerIndex:z45.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z45.object({code:z45.literal("unique_conflict"),message:z45.string(),conflicts:z45.array(UniqueConflictSchema),truncated:z45.boolean().optional()})}});import{z as z46}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z46.object({kind:z46.literal("unique_conflict"),contentType:z46.string(),field:z46.string(),value:z46.string(),documentCount:z46.number().int().positive(),documentIds:z46.array(z46.uuid()),documentIdsTruncated:z46.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z46.object({code:z46.literal("schema_transition_rejected"),message:z46.string(),issues:z46.array(SchemaTransitionIssueSchema),truncated:z46.boolean().optional()})}});import{z as z47}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z47.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z47.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z47.object({field:CmsFieldNameSchema,direction:z47.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z47.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z47.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z47.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z47.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z47.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z48}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema))}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z51.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z51.object({items:z51.array(ProjectMessagePublicDTOSchema),nextCursor:z51.string().nullable()}),ChatLiveTurnDTOSchema=z51.object({invocationId:z51.string(),step:z51.enum(["preparing","working","compacting","merging"]),startedAt:z51.string()}),ChatLiveTurnStateDTOSchema=z51.object({threadId:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z51.object({id:z51.string(),role:z51.enum(["user","assistant"]),parts:z51.array(z51.unknown()),metadata:z51.record(z51.string(),z51.unknown()).nullable(),versionId:z51.string().nullable().optional(),createdAt:z51.date().transform(value=>value.toISOString()),providerMessageId:z51.string().nullable().optional(),invocationId:z51.string().nullable().optional(),invocationStatus:z51.string().nullable().optional(),invocationTerminalReason:z51.string().nullable().optional()}),ChatAttentionDTOSchema=z51.object({type:z51.literal("merge_conflict"),merge:z51.object({mergeId:z51.string().uuid(),projectId:z51.string(),fromEnv:z51.string(),toEnv:z51.string()}),publishAfterMerge:z51.boolean()}),ChatThreadMessagesPageDTOSchema=z51.object({threadId:z51.string().nullable(),title:z51.string().nullable(),messages:z51.array(ChatThreadMessageDTOSchema),nextCursor:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z51.object({kind:z51.literal("replay"),threadId:z51.string(),userMessageId:z51.string()}),ChatQueuedOutcomeDTOSchema=z51.object({kind:z51.literal("queued"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string()}),ChatBusyOutcomeDTOSchema=z51.object({kind:z51.literal("busy"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string().optional()}),ChatRefusedOutcomeDTOSchema=z51.object({kind:z51.literal("refused"),threadId:z51.string(),userMessageId:z51.string(),refusedInvocationId:z51.string(),terminalReason:z51.string()}),ChatNonStreamingOutcomeDTOSchema=z51.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z51.object({success:z51.boolean(),deletedCount:z51.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z51.object({code:z51.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z51.string()})}});import{z as z52}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z52.object({url:z52.string().url(),key:z52.string(),size:z52.number(),contentType:z52.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z53}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z53.object({canAccess:z53.boolean(),permissions:z53.record(z53.string(),z53.boolean()),role:z53.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z54}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z54.string().trim().default(""),sort:z54.enum(["recent","name","relevance"]).default("recent"),category:z54.string().optional()})}});import{z as z55}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z55.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z55.enum(["fimo","external"]),PaymentStatusSchema=z55.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z55.object({id:z55.string().uuid(),domain:z55.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z55.boolean(),price:z55.number().int().nullable(),renewalPrice:z55.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z55.string().nullable(),failureReason:z55.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z55.object({domain:z55.string(),available:z55.boolean(),premium:z55.boolean(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),purchaseType:z55.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z55.object({domain:z55.string(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),premium:z55.boolean(),allowedYears:z55.array(z55.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z55.object({firstName:z55.string().max(100),lastName:z55.string().max(100),companyName:z55.string().max(100).optional(),address1:z55.string().max(255),address2:z55.string().max(255).optional(),city:z55.string().max(100),state:z55.string().max(100),zip:z55.string().max(20),country:z55.string().max(2),phone:z55.string().max(30),email:z55.union([z55.string().email().max(255),z55.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z55.object({firstName:z55.string().min(1).max(100),lastName:z55.string().min(1).max(100),companyName:z55.string().max(100).optional(),address1:z55.string().min(1).max(255),address2:z55.string().max(255).optional(),city:z55.string().min(1).max(100),state:z55.string().min(1).max(100),zip:z55.string().min(1).max(20),country:z55.string().min(1).max(2),phone:z55.string().min(1).max(30),email:z55.string().email().max(255)}),SearchDomainsRequestSchema=z55.object({keyword:z55.string().min(1).max(100),tldFilter:z55.array(z55.string()).optional()}),CheckAvailabilityRequestSchema=z55.object({domains:z55.array(z55.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z55.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z55.object({domain:DomainNameSchema,years:z55.number().int().min(1).max(10).optional().default(3),autoRenew:z55.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z55.object({autoRenew:z55.boolean().optional()}),RenewDomainRequestSchema=z55.object({years:z55.number().int().min(1).max(10).optional().default(1),autoRenew:z55.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z55.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z55.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z55.object({verified:z55.boolean(),email:z55.string().nullable(),verifyBy:z55.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z56}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z56.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z56.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z56.object({txtName:z56.string().nullable().optional(),txtValue:z56.string().nullable().optional(),httpUrl:z56.string().nullable().optional(),httpBody:z56.string().nullable().optional(),cname:z56.string().nullable().optional(),cnameTarget:z56.string().nullable().optional()}),SSLValidationErrorSchema=z56.object({message:z56.string()}),OwnershipVerificationSchema=z56.object({type:z56.string(),name:z56.string(),value:z56.string()}),ProjectDomainSSLDTOSchema=z56.object({status:z56.string(),method:z56.string().nullable(),type:z56.string().nullable(),validationRecords:z56.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z56.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z56.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z56.enum(["subdomain","apex"]),RedirectConfigSchema=z56.object({type:z56.literal("apex_to_www"),linkedDomainId:z56.string()}).nullable().optional(),ProjectDomainDTOSchema=z56.object({id:z56.string(),hostname:z56.string(),status:z56.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z56.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z56.string(),scdCnameTarget:z56.string().optional(),apexTargets:z56.array(z56.string()),dnsAutoConfigured:z56.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z56.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z56.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z56.object({hostname:z56.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z56.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z56.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z56.object({available:z56.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),hostname:z56.string()}))}});import{z as z57}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z57.object({slug:z57.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z57.object({subdomain:z57.string(),subdomainUpdatedAt:z57.coerce.date()})),SubdomainSuggestionsQuerySchema=z57.object({base:z57.string().max(100).optional(),max:z57.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z57.object({suggestions:z57.array(z57.string())}))}});import{z as z58}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z58.object({translated:z58.number().int().nonnegative(),total:z58.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z58.object({locale:z58.string(),isDefault:z58.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z58.object({defaultLocale:z58.string(),locales:z58.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z58.object({locale:z58.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z58.object({locale:z58.string().min(1).max(40)}),ProjectLocaleMutationSchema=z58.object({locale:z58.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z58.object({locale:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z59}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z59.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z59.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z59.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z59.number(),credits:z59.number().optional(),billingMode:z59.enum(["fimo-credits","provider-account"]).optional(),confidence:z59.enum(["exact","estimated","metered"]),basis:z59.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z60}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z60.object({options:z60.record(z60.string(),z60.unknown()),name:z60.string().optional(),parentId:z60.string().nullable().optional(),altText:z60.string().optional(),caption:z60.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z60.string().min(1).optional(),model:z60.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z60.object({jobId:z60.string(),status:z60.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z60.string().nullable().optional(),credits:z60.number().optional(),costUsd:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z60.object({error:z60.string(),code:z60.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z60.array(GenerationTaskIdSchema).optional(),availableModels:z60.array(z60.string()).optional(),issues:z60.array(z60.unknown()).optional()})}});import{z as z61}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z61.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z61.object({name:z61.string(),key:z61.string(),description:z61.string(),type:FlagTypeSchema,required:z61.boolean(),defaultValue:z61.unknown().optional(),enumValues:z61.array(z61.string()).optional(),isArray:z61.boolean()}),AssetModelPriceSchema=z61.object({unitPrice:z61.number(),unit:z61.string(),confidence:z61.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z61.object({id:z61.string(),shortName:z61.string(),provider:z61.string(),source:z61.string(),modality:z61.enum(["image","video","audio"]),tags:z61.array(z61.string()),displayName:z61.string(),description:z61.string(),flags:z61.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z61.object({model:z61.string(),costUsd:z61.number(),credits:z61.number(),billingMode:z61.enum(["fimo-credits","provider-account"]),confidence:z61.enum(["exact","estimated","metered"]),basis:z61.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z62}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z62.object({tourId:z62.string(),version:z62.string(),status:z62.string(),completedAt:z62.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z62.array(UserTourDTOSchema))}});import{z as z63}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z63.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z63.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z63.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z63.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z63.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z63.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z63.enum(["user","agent","system"]),SupportReportTagSchema=z63.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z63.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z63.object({organization:z63.object({id:z63.string().trim().min(1).max(255),name:z63.string().trim().max(240).optional()}),project:z63.object({id:z63.uuid(),name:z63.string().trim().max(240).optional(),createdAt:z63.coerce.date().optional()}).optional(),environment:z63.string().trim().max(255).optional(),clientVersion:z63.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z63.string().trim().max(200).optional(),limit:z63.coerce.number().int().min(1).max(100).default(50),offset:z63.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z63.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z63.uuid().nullable().optional(),note:z63.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z63.object({kind:SupportReportLinkKindSchema,label:z63.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z63.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z63.object({kind:SupportReportActorKindSchema,id:z63.string().nullable(),name:z63.string().nullable()}),SupportReportLinkDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportLinkKindSchema,label:z63.string(),url:SupportReportHttpUrlSchema,externalId:z63.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportEventKindSchema,body:z63.string().nullable(),metadata:z63.record(z63.string(),z63.unknown()),actor:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z63.object({id:z63.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z63.array(z63.string()),source:SupportReportSourceSchema,message:z63.string(),reporter:z63.object({id:z63.string().nullable(),name:z63.string().nullable(),email:z63.string().nullable()}),organization:z63.object({id:z63.string().nullable(),name:z63.string()}),project:z63.object({id:z63.uuid().nullable(),name:z63.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z63.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z63.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z63.string().nullable(),deliveredAt:z63.coerce.date().nullable()}).nullable(),duplicateOfReportId:z63.uuid().nullable(),resolvedAt:z63.coerce.date().nullable(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z63.string().nullable(),clientVersion:z63.string().nullable(),links:z63.array(SupportReportLinkDTOSchema),events:z63.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z63.object({reports:z63.array(SupportReportSummaryDTOSchema),total:z63.number().int().nonnegative(),statusCounts:z63.object({new:z63.number().int().nonnegative(),in_progress:z63.number().int().nonnegative(),waiting:z63.number().int().nonnegative(),resolved:z63.number().int().nonnegative(),duplicate:z63.number().int().nonnegative(),irrelevant:z63.number().int().nonnegative(),ignored:z63.number().int().nonnegative()}),limit:z63.number().int().positive(),offset:z63.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z63.object({id:z63.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z63.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z64}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z64.iso.datetime({offset:!0}).pipe(z64.coerce.date()),OpsRecentChatInputSchema=z64.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z64.string().trim().min(1).max(255).optional(),limit:z64.coerce.number().int().min(1).max(200).default(100),cursor:z64.string().trim().min(1).max(2e3).optional(),slim:z64.boolean().default(!0),reason:z64.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z64.object({id:z64.string(),threadId:z64.string(),providerMessageId:z64.string().nullable(),invocationId:z64.string().nullable(),env:z64.string().nullable(),role:z64.string(),parts:z64.array(z64.record(z64.string(),z64.unknown())),metadata:z64.object({status:z64.string().optional(),traceUrl:z64.string().optional(),externalFileChanges:z64.array(z64.unknown()).optional()}),stats:z64.object({toolCount:z64.number().int().nonnegative(),failedToolCount:z64.number().int().nonnegative()}),createdAt:z64.iso.datetime({offset:!0}),project:z64.object({id:z64.string(),name:z64.string(),displayName:z64.string().nullable(),organizationId:z64.string().nullable()})}),OpsRecentChatResponseSchema=z64.object({target:z64.object({backendProfile:OpsBackendProfileSchema,projectEnv:z64.string().nullable()}),window:z64.object({from:z64.iso.datetime({offset:!0}),to:z64.iso.datetime({offset:!0})}),messages:z64.object({items:z64.array(OpsRecentChatMessageSchema),nextCursor:z64.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z65}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z65.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z65.literal(!1),reason:z65.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z66}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z66.object({packageManager:z66.string().trim().min(1).max(200).nullable(),trackedLockfiles:z66.array(z66.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z66.string().trim().min(1)}),OpsProjectPackageManagerSchema=z66.object({target:z66.object({backendProfile:OpsBackendProfileSchema,projectId:z66.uuid(),projectEnv:z66.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z67}from"zod";function createAgentRunWebhookEventDataSchema(status){return z67.object({run:z67.object({id:z67.string(),agentName:z67.string(),trigger:z67.string(),status:z67.literal(status),startedAt:z67.string().nullable(),finishedAt:z67.string().nullable(),reason:z67.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z67.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z67.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z67.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z67.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z67.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z67.union([z67.literal(0),z67.literal(5),z67.literal(30),z67.literal(60)]),EntryChangedWebhookEventDataSchema=z67.object({reason:WebhookEntryChangeReasonSchema,operationId:z67.string().optional(),batch:z67.object({index:z67.number().int().positive(),total:z67.number().int().positive()}).optional(),changes:z67.array(z67.object({action:WebhookEntryChangeActionSchema,contentType:z67.string(),id:z67.string(),documentId:z67.string(),locale:z67.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z67.object({form:z67.object({id:z67.string(),label:z67.string()}),submission:z67.object({id:z67.string(),data:z67.record(z67.string(),z67.unknown()),submittedAt:z67.string()})}),PublishStartedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("publishing"),startedAt:z67.string()})}),PublishSucceededWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("published"),url:z67.string(),publishedAt:z67.string(),firstPublish:z67.boolean()})}),PublishFailedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("failed"),reason:z67.string()})}),PublishUnpublishedWebhookEventDataSchema=z67.object({publication:z67.object({previousUrl:z67.string(),unpublishedAt:z67.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),classification:z67.string(),summary:z67.string(),reasons:z67.array(z67.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),resolution:z67.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z67.object({report:z67.object({weekStart:z67.string(),weekEnd:z67.string(),pageviews:z67.number(),visitors:z67.number(),previousPageviews:z67.number(),previousVisitors:z67.number()})}),MediaAssetWebhookEventDataSchema=z67.object({id:z67.string().nullable(),name:z67.string().nullable(),type:z67.string(),mimeType:z67.string().nullable(),fileSize:z67.number().nullable()}),MediaUploadedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["updated","moved","analysis"]),analysis:z67.object({category:z67.string(),status:z67.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("generated"),generation:z67.object({model:z67.string(),mode:z67.string()})}),MediaProcessingFailedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["analysis","generation"]),failure:z67.object({code:z67.string()})}),DomainCreatedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string()})}),LabelChangedWebhookEventDataSchema=z67.object({changes:z67.array(z67.object({action:z67.enum(["created","updated","deleted"]),key:z67.string(),locale:z67.string(),value:z67.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),isDefault:z67.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),previousCode:z67.string()})}),LocaleDeletedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),entriesDeleted:z67.number().int().nonnegative(),labelsDeleted:z67.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z67.object({merge:z67.object({id:z67.string(),from:EnvSchema,to:EnvSchema,applied:z67.array(z67.object({surface:SurfaceNameSchema,count:z67.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema}),version:z67.object({versionId:z67.uuid(),name:z67.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z67.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z67.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z67.discriminatedUnion("source",[z67.object({source:z67.literal("literal"),value:z67.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z67.object({source:z67.literal("secret"),key:z67.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z67.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z67.object({name:z67.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z67.object({name:z67.string(),source:z67.enum(["literal","secret"]),secretKey:z67.string().nullable(),secretPrefix:z67.string().nullable(),configured:z67.literal(!0)}),WebhookFilterSchema=z67.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z67.string().min(1).max(255).optional(),agentName:z67.string().min(1).max(120).optional(),mediaType:z67.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z67.string().min(1).max(255).optional(),locale:z67.string().min(1).max(120).optional()}),JsonValueSchema=z67.lazy(()=>z67.union([z67.string(),z67.number(),z67.boolean(),z67.null(),z67.array(JsonValueSchema),z67.record(z67.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z67.url(),enabled:z67.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z67.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z67.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z67.url().optional(),enabled:z67.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z67.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z67.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z67.object({eventType:WebhookEventTypeSchema.optional(),data:z67.record(z67.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z67.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z67.uuid(),name:z67.string(),eventType:WebhookEventTypeSchema,enabled:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z67.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z67.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z67.coerce.date().nullable(),deliveryStats24h:z67.object({succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z67.uuid(),projectId:z67.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z67.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z67.number().int().positive(),test:z67.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z67.number().int().nonnegative(),responseStatus:z67.number().int().nullable(),lastErrorCode:z67.string().nullable(),lastErrorMessage:z67.string().nullable(),payloadAvailable:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z67.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z67.string().nullable(),qstashMessageId:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z67.object({items:z67.array(WebhookDeliveryDTOSchema),pagination:z67.object({page:z67.number().int().positive(),limit:z67.number().int().positive(),total:z67.number().int().nonnegative(),totalPages:z67.number().int().positive(),hasMore:z67.boolean()}),stats:z67.object({total:z67.number().int().nonnegative(),succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z67.object({id:z67.uuid(),deliveryId:z67.uuid(),attempt:z67.number().int().positive(),status:z67.enum(["delivering","succeeded","failed"]),responseStatus:z67.number().int().nullable(),durationMs:z67.number().int().nonnegative(),responseExcerpt:z67.string().nullable(),errorCode:z67.string().nullable(),errorMessage:z67.string().nullable(),createdAt:z67.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z67.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z67.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z68}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z68.object({key:z68.literal("fimo-2"),enabled:z68.boolean(),dismissed:z68.boolean().default(!1),interacted:z68.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z69}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z69.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z69.object({total:z69.number(),base:z69.number(),purchases:z69.number(),awards:z69.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z69.object({id:z69.string(),name:z69.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z69.object({type:z69.string(),brand:z69.string().nullable(),last4:z69.string().nullable(),expirationDate:z69.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z69.object({currency:z69.string(),nextPaymentAmount:z69.number().nullable(),nextPaymentAt:z69.string().nullable(),billingInterval:z69.string().nullable(),totalAmount:z69.number().nullable(),discountAmount:z69.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z69.object({id:z69.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z69.string().nullable(),currentPeriodEndsAt:z69.string().nullable(),renewsAt:z69.string().nullable(),cancelAt:z69.string().nullable(),renewAutomatically:z69.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z69.object({type:z69.enum(["low_balance","critical_balance","approaching_limit"]),message:z69.string(),estimatedPromptsRemaining:z69.number().nullable(),avgCostPerPrompt:z69.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z69.object({monthlyCredits:z69.number().nullable(),usedThisPeriod:z69.number(),remainingThisPeriod:z69.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z69.object({organizationId:z69.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z69.string().nullable(),tenureDays:z69.number().int().nonnegative(),capturedAt:z69.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z69.object({hasSubscription:z69.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z69.number().nullable(),alerts:z69.array(CreditAlertDTOSchema),portalUrl:z69.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z69.object({creditCount:z69.number().int().positive(),expiresAt:z69.string().datetime().nullable().optional(),message:z69.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("free"),amountCents:z69.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("purchase"),amountCents:z69.number().int().positive()}),CreditTopupRequestDTOSchema=z69.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z69.object({success:z69.boolean(),transactionId:z69.string().nullable(),newBalance:z69.number(),creditCount:z69.number(),type:z69.enum(["free","purchase"]),invoiceId:z69.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z70}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z70.object({totalCredits:z70.number(),totalCostUsd:z70.number(),totalMessages:z70.number(),avgCostPerMessage:z70.number(),periodStart:z70.string().nullable(),periodEnd:z70.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z70.object({date:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z70.array(UsageByUserForProjectDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z70.object({summary:UsageSummaryDTOSchema,byProject:z70.array(UsageByProjectDTOSchema),byUser:z70.array(UsageByUserDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z71}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z71.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z71.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z71.object({startDate:z71.string().optional(),endDate:z71.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z71.coerce.number().int().positive().default(1),limit:z71.coerce.number().int().positive().max(100).default(20),sortBy:z71.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z71.string().optional(),activeOnly:z71.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),avgCreditsPerMessage:z71.number(),periodStart:z71.string(),periodEnd:z71.string(),creditsChange:z71.number().nullable(),costChange:z71.number().nullable(),messagesChange:z71.number().nullable(),unattributedCredits:z71.number(),unattributedCostUsd:z71.number(),unattributedMessages:z71.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z71.object({organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number(),projectCount:z71.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().nullable(),userImage:z71.string().nullable(),organizationId:z71.string().nullable(),organizationName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),projectCount:z71.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z71.object({id:z71.string(),name:z71.string(),value:z71.number(),percentage:z71.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z71.object({day:z71.number(),hour:z71.number(),value:z71.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z71.object({summary:UsageOverviewSummaryDTOSchema,timeline:z71.array(UsageTimelinePointDTOSchema),topOrganizations:z71.array(OrganizationUsageRowDTOSchema),topUsers:z71.array(UserUsageRowDTOSchema),topProjects:z71.array(ProjectUsageRowDTOSchema),creditDistribution:z71.array(UsageDistributionItemDTOSchema),userDistribution:z71.array(UsageDistributionItemDTOSchema),heatmap:z71.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z71.object({page:z71.number(),limit:z71.number(),totalItems:z71.number(),totalPages:z71.number(),hasMore:z71.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z71.object({organizations:z71.array(OrganizationUsageRowDTOSchema),top:z71.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z71.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z71.object({users:z71.array(ExtendedUserUsageRowDTOSchema),top:z71.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z71.object({projects:z71.array(ExtendedProjectUsageRowDTOSchema),top:z71.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z71.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z71.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z71.object({credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),createdAt:z71.string(),memberCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z71.object({id:z71.string(),name:z71.string().nullable(),email:z71.string(),image:z71.string().nullable(),createdAt:z71.string(),organizationCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),displayName:z71.string().nullable(),createdAt:z71.string(),organizationId:z71.string(),organizationName:z71.string(),ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z72}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z72.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z72.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z72.object({command:z72.string().min(1).max(1e4),cwd:z72.string().optional(),projectEnv:EnvSchema.optional(),env:z72.record(z72.string(),z72.string()).optional(),name:z72.string().optional(),waitForCompletion:z72.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z72.object({identifier:z72.string(),status:SandboxProcessStatusSchema,command:z72.string().optional(),startedAt:z72.string().optional(),exitCode:z72.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z72.object({processes:z72.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z72.object({processId:z72.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z72.object({success:z72.boolean(),message:z72.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z73}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path52,message}=issue;return`${Array.isArray(path52)&&path52.length>0?`${path52.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path52,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path52,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers})}async rawRequest(path52,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path52}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path52} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path52,opts={}){let qs=lazyFetchQs(opts.against,{path:path52});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path52=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path52}?${qs}`:path52)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
43
43
 
44
44
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
45
45
 
@@ -206,13 +206,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
206
206
  `).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
207
207
  `);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
208
208
  `).slice(o);this.output.write(a.join(`
209
- `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z78,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z78=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
209
+ `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z79,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z79=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
210
210
  `);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y"),ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
211
211
  `:""}${o}
212
212
  `,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
213
- ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z78)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
213
+ ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z79)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
214
214
  ${t("cyan",d2)} `:`
215
- `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z78)} ${s}`}
215
+ `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z79)} ${s}`}
216
216
  ${$2}
217
217
  `}}}}).prompt()},"ot"),O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
218
218
  `);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
@@ -238,7 +238,7 @@ ${o}
238
238
  `}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
239
239
  `)?e.split(`
240
240
  `).map(s=>i(s)).join(`
241
- `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z78)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
241
+ `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z79)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
242
242
  `:""}${n}
243
243
  `;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
244
244
  ${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
@@ -354,7 +354,7 @@ return __eta.res;
354
354
  `)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp(string2){return string2.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
355
355
  `).length}function parse5(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
356
356
  `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile2(path52){let res="";try{res=fs18.readFileSync(path52,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path52}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path21.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path21.join(views,formattedPath)}else resolvedFilePath=path21.join(path21.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path21.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path21.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path21.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse5,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse5,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path52){try{return JSON.parse(readFileSync4(path52,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
357
- `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,subpath){let packagePath=join5(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function assertFrameworkRuntime(cwd,target){let missing=(target==="next"?["./forms","./next","./next/client"]:["./forms",`./${target}`]).filter(subpath=>!hasPackageExport(cwd,subpath));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project-local fimo package is missing ${missing.join(", ")}. Install the current fimo package, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo/next"},{suffix:".client.ts",runtimeImport:"fimo/next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo/sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z79}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path52 of schemaFiles){let fileUid=basename(path52,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path52)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path52,"utf-8"))}catch(error){errors.push(`${basename(path52)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path52)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path52)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path52)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path52)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path52)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
357
+ `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,subpath){let packagePath=join5(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function assertFrameworkRuntime(cwd,target){let missing=(target==="next"?["./forms","./next","./next/client"]:["./forms",`./${target}`]).filter(subpath=>!hasPackageExport(cwd,subpath));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project-local fimo package is missing ${missing.join(", ")}. Install the current fimo package, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo/next"},{suffix:".client.ts",runtimeImport:"fimo/next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo/sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z80}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path52 of schemaFiles){let fileUid=basename(path52,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path52)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path52,"utf-8"))}catch(error){errors.push(`${basename(path52)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path52)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path52)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path52)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path52)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path52)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
358
358
  - ${errors.join(`
359
359
  - `)}
360
360
  No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -367,7 +367,7 @@ ${imports}
367
367
  export const content = {
368
368
  ${entries2}
369
369
  } as const;
370
- `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,RUNTIME_TYPE_IMPORT_ORDER,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z79.object({uid:z79.string().min(1),name:z79.string().min(1).optional(),isSingleton:z79.boolean().optional(),i18n:z79.object({enabled:z79.boolean().optional()}).optional(),fields:z79.record(z79.string(),z79.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
370
+ `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,RUNTIME_TYPE_IMPORT_ORDER,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z80.object({uid:z80.string().min(1),name:z80.string().min(1).optional(),isSingleton:z80.boolean().optional(),i18n:z80.object({enabled:z80.boolean().optional()}).optional(),groups:z80.array(z80.object({id:z80.string().min(1),label:z80.string().min(1),default:z80.boolean().optional()}).strict()).optional(),fields:z80.record(z80.string(),z80.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
371
371
  `)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
372
372
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
373
373
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -1175,7 +1175,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1175
1175
  ${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
1176
1176
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path52=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path52,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(api,ctx.projectId,ctx.env,cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
1177
1177
 
1178
- ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs50 from"node:fs";import path51 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z73}from"zod";var CapabilityTokenSchema=z73.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z73.array(CapabilityTokenSchema);import{z as z74}from"zod";var CronTriggerSchema=z74.object({type:z74.literal("schedule"),cron:z74.string().min(1,"cron expression required"),tz:z74.string().optional()}),ManualTriggerSchema2=z74.object({type:z74.literal("manual")}),WebhookTriggerSchema2=z74.object({type:z74.literal("webhook"),path:z74.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z74.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z74.object({name:z74.string().min(1),capability_grant:z74.enum(["inherit","explicit"]).optional(),explicit_grants:z74.array(z74.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z74.object({"sub-agents":z74.array(SubAgentRefSchema)}),RuntimeConfigSchema=z74.object({cloud:z74.boolean().optional(),dev:z74.boolean().optional(),long_running:z74.boolean().optional()}),DataSourceSchema=z74.enum(["main","prod"]),ConfigValueKeySchema=z74.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z74.preprocess(value=>typeof value=="string"?{key:value}:value,z74.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z74.boolean().default(!0),delivery:z74.literal("process_env").default("process_env")})),IntegrationKeySchema=z74.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z74.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z74.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z74.object({enabled:z74.boolean().default(!0),tools:z74.record(IntegrationToolKeySchema,z74.boolean()).optional()})),IntegrationPolicySchema=z74.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z74.object({version:z74.literal(1),description:z74.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z74.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z74.array(DataSourceSchema).optional(),secrets:z74.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z75}from"zod";var SurfaceGuardPolicySchema=z75.enum(["block","warn","allow"]),ClassificationSchema=z75.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z75.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z75.object({enabled:z75.boolean(),allowed_skills:z75.array(z75.string().min(1)).default([]),allowed_classifications:z75.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z75.enum(["off","daily","weekly"]),NotificationFormatSchema=z75.object({markdown:z75.boolean().default(!0),html:z75.boolean().default(!1)}),NotificationsPolicySchema=z75.object({email_recipients:z75.array(z75.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z75.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z75.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z76}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z76.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z76.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
1178
+ ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs50 from"node:fs";import path51 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z74}from"zod";var CapabilityTokenSchema=z74.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z74.array(CapabilityTokenSchema);import{z as z75}from"zod";var CronTriggerSchema=z75.object({type:z75.literal("schedule"),cron:z75.string().min(1,"cron expression required"),tz:z75.string().optional()}),ManualTriggerSchema2=z75.object({type:z75.literal("manual")}),WebhookTriggerSchema2=z75.object({type:z75.literal("webhook"),path:z75.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z75.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z75.object({name:z75.string().min(1),capability_grant:z75.enum(["inherit","explicit"]).optional(),explicit_grants:z75.array(z75.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z75.object({"sub-agents":z75.array(SubAgentRefSchema)}),RuntimeConfigSchema=z75.object({cloud:z75.boolean().optional(),dev:z75.boolean().optional(),long_running:z75.boolean().optional()}),DataSourceSchema=z75.enum(["main","prod"]),ConfigValueKeySchema=z75.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z75.preprocess(value=>typeof value=="string"?{key:value}:value,z75.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z75.boolean().default(!0),delivery:z75.literal("process_env").default("process_env")})),IntegrationKeySchema=z75.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z75.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z75.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z75.object({enabled:z75.boolean().default(!0),tools:z75.record(IntegrationToolKeySchema,z75.boolean()).optional()})),IntegrationPolicySchema=z75.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z75.object({version:z75.literal(1),description:z75.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z75.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z75.array(DataSourceSchema).optional(),secrets:z75.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z76}from"zod";var SurfaceGuardPolicySchema=z76.enum(["block","warn","allow"]),ClassificationSchema=z76.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z76.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z76.object({enabled:z76.boolean(),allowed_skills:z76.array(z76.string().min(1)).default([]),allowed_classifications:z76.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z76.enum(["off","daily","weekly"]),NotificationFormatSchema=z76.object({markdown:z76.boolean().default(!0),html:z76.boolean().default(!1)}),NotificationsPolicySchema=z76.object({email_recipients:z76.array(z76.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z76.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z76.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z77}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z77.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z77.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
1179
1179
  ${line}`):next2=(content2.endsWith(`
1180
1180
  `)?content2:content2+`
1181
1181
  `)+line+`
@@ -1206,7 +1206,7 @@ Fix: add a route entry to ${configDisplayPath} "routes" with a matching "path".`
1206
1206
  Fix: add the route to src/routes.ts. Example: route('${route.path.replace(/^\//,"")}', './pages/YourPage.tsx')`);i18n.routingStrategy==="path-prefix"&&i18n.locales.length>1&&errors.push(...validateLocaleRouteCollisions({configRoutes,fileRoutes,i18n,configDisplayPath,routesSourceUsesLegacyHelper:sourceUsesLegacyFimoRoutes(routesFilePath)}));let routeById=new Map;for(let route of configRoutes){if(routeById.has(route.id)){let previousPath=routeById.get(route.id).path;errors.push(`Duplicate route id "${route.id}" found for paths "${previousPath}" and "${route.path}".`);continue}routeById.set(route.id,route)}for(let route of configRoutes){for(let issue of route.contract.issues)errors.push(`Route "${route.id}" (${route.path}): ${issue.message}
1207
1207
  Fix: ${issue.fix}`);errors.push(...validatePageSources(route))}errors.push(...validateRouteShapeCollisions(configRoutes));for(let route of configRoutes){let file=registrablePaths(route).map(candidate=>pathToFile.get(candidate)).find(Boolean);if(!file)continue;let routeModulePath=path24.resolve(srcDir,file);if(!fs21.existsSync(routeModulePath)){errors.push(`Route "${route.id}" (${route.path}) references missing module "${file}".
1208
1208
  Fix: create the file at src/${file}.`);continue}if(route.seo){let GLOBAL_VARIABLES=new Set(["siteName","label"]),seoFields=[{name:"title",value:route.seo.title},{name:"description",value:route.seo.description}];for(let field of seoFields){if(typeof field.value!="string")continue;let templatePattern=/\{\{([^}]+)\}\}/g,match;for(;(match=templatePattern.exec(field.value))!==null;){let variable=match[1].trim();if(GLOBAL_VARIABLES.has(variable))continue;let entryParamNames=route.contract.entryParams.map(param=>param.name),availableParams=entryParamNames.length>0?entryParamNames.join(", "):"none";if(variable.includes(".")){let paramKey=variable.split(".")[0];entryParamNames.includes(paramKey)||errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" but "${paramKey}" is not a declared entry param. Available params: ${availableParams}.`)}else errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" which is not a global variable (siteName, label) and not a dotted param reference (e.g., "{{param.field}}"). Available params: ${availableParams}.`)}}}}return{errors,routesChecked:configRoutes.length}}__name(validateRouteMetadata,"validateRouteMetadata");function validatePageSources(route){if(!route.sources)return[];let errors=[],entryParamNames=new Set(route.contract.entryParams.map(param=>param.name));for(let[sourceName,rawSource]of Object.entries(route.sources)){if(!/^[A-Za-z][\w-]*$/.test(sourceName)||!isRecord2(rawSource)){errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" is not a valid named source.`);continue}if(rawSource.type==="labels"){let match=rawSource.match;(!Array.isArray(match)||match.length===0||match.some(pattern=>{if(typeof pattern!="string")return!0;let wildcard=pattern.indexOf("*");return wildcard!==-1&&!(pattern.length>2&&pattern.endsWith(".*")&&wildcard===pattern.length-1)}))&&errors.push(`Route "${route.id}" (${route.path}): Labels source "${sourceName}" needs exact keys or prefixes ending in .*.`);continue}if(rawSource.type!=="single"&&rawSource.type!=="collection"){errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" type must be labels, single, or collection.`);continue}if((typeof rawSource.schema!="string"||!rawSource.schema)&&errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" needs a schema.`),rawSource.type==="collection"&&rawSource.query!==void 0&&!isRecord2(rawSource.query)){errors.push(`Route "${route.id}" (${route.path}): Collection source "${sourceName}" query must be an object.`);continue}for(let expression of pageSourceParamExpressions(rawSource.query)){let param=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/.exec(expression)?.[1];(!param||!entryParamNames.has(param))&&errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" references undeclared param "${param??expression}". Fix: use $params.<declared-entry-param>.<field>.`)}}return errors}__name(validatePageSources,"validatePageSources");function validateI18nConfig(config){let rawI18n=isRecord2(config.i18n)?config.i18n:{},errors=[],rawDefaultLocale=typeof rawI18n.defaultLocale=="string"?rawI18n.defaultLocale:"en",defaultLocale=normalizeFimoLocale(rawDefaultLocale);defaultLocale||errors.push(`Invalid i18n.defaultLocale "${rawDefaultLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);let rawLocales=Array.isArray(rawI18n.locales)?rawI18n.locales:defaultLocale?[defaultLocale]:[];rawI18n.locales!==void 0&&!Array.isArray(rawI18n.locales)&&errors.push("i18n.locales must be an array of locale strings.");let locales=[],seenLocales=new Set;for(let rawLocale of rawLocales){if(typeof rawLocale!="string"){errors.push(`Invalid i18n.locales entry ${JSON.stringify(rawLocale)}. Locale entries must be strings.`);continue}let locale=normalizeFimoLocale(rawLocale);if(!locale){errors.push(`Invalid i18n.locales entry "${rawLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);continue}seenLocales.has(locale)||(seenLocales.add(locale),locales.push(locale))}let effectiveDefaultLocale=defaultLocale??"en";seenLocales.has(effectiveDefaultLocale)||(errors.push(`i18n.locales must include i18n.defaultLocale "${effectiveDefaultLocale}".`),locales.unshift(effectiveDefaultLocale));let rawRouting=isRecord2(rawI18n.routing)?rawI18n.routing:{},routingStrategy=typeof rawRouting.strategy=="string"?rawRouting.strategy:"path-prefix";return routingStrategy!=="path-prefix"&&errors.push(`Unsupported i18n.routing.strategy "${routingStrategy}". Supported now: "path-prefix".`),{defaultLocale:effectiveDefaultLocale,locales,routingStrategy,errors}}__name(validateI18nConfig,"validateI18nConfig");function validateRouteShapeCollisions(configRoutes){let errors=[],byShape=new Map;for(let route of configRoutes){let shape=route.contract.canonicalPath.split("/").map(segment=>segment.startsWith(":")?":param":segment).join("/"),previous=byShape.get(shape);if(previous&&(previous.contract.localeParam||route.contract.localeParam)){errors.push(`Routes "${previous.id}" (${previous.path}) and "${route.id}" (${route.path}) both answer "${route.contract.canonicalPath}".
1209
- Fix: keep one of them, or give them distinct paths \u2014 a locale segment does not make two routes distinct.`);continue}previous||byShape.set(shape,route)}return errors}__name(validateRouteShapeCollisions,"validateRouteShapeCollisions");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Declare the locale as "/:locale/..." in ${args.configDisplayPath} and as ":locale?/..." in React Router so the default locale remains unprefixed.`)}if(!args.routesSourceUsesLegacyHelper)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);first2&&normalizeLocaleSpelling(first2)===`:${FIMO_LOCALE_PARAM}`||(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale project. It can capture locale URLs like "/${args.i18n.locales[0]}". Put an explicit optional ":locale?" segment first in the React Router path, or keep this route outside the localized route boundary.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesLegacyFimoRoutes(routesFilePath){if(!fs21.existsSync(routesFilePath))return!1;let source=fs21.readFileSync(routesFilePath,"utf-8"),importedName=source.match(/import\s*\{(?<imports>[^}]*)\}\s*from\s*['"]fimo\/react-router\/routes['"]/s)?.groups?.imports?.split(",").map(specifier=>specifier.trim().match(/^fimoRoutes(?:\s+as\s+(?<alias>[A-Za-z_$][\w$]*))?$/)?.groups?.alias??(specifier.trim()==="fimoRoutes"?"fimoRoutes":null)).find(name=>!!name);return importedName?new RegExp(`\\b${importedName}\\s*\\(`).test(source):!1}__name(sourceUsesLegacyFimoRoutes,"sourceUsesLegacyFimoRoutes");function normalizeLocaleSpelling(routePath){return routePath.replace(`:${FIMO_LOCALE_PARAM}?`,`:${FIMO_LOCALE_PARAM}`)}__name(normalizeLocaleSpelling,"normalizeLocaleSpelling");function registrablePaths(route){let declared=normalizeLocaleSpelling(route.contract.path);return route.contract.localeParam?.optional?[declared,route.contract.canonicalPath]:[declared]}__name(registrablePaths,"registrablePaths");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync6,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve6}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve6(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync6(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;let parsedFields={};for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition;if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"localized"in definition&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "localized" is not supported. Use "i18n": false to share one value across locales.`,file}),"i18n"in definition&&(typeof definition.i18n!="boolean"?errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" must be true or false.`,file}):type==="blocks"&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" is not supported on blocks fields.`,file})),type==="blocks"){let parsed2=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed2.success){for(let issue of parsed2.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}parsedFields[fieldName]=parsed2.data,walkContentFields({[fieldName]:parsed2.data},({field,path:path52,structuredDepth,insideStructuredContent})=>{if(field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path52.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path52.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path52.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(parsed.success&&(parsedFields[fieldName]=parsed.data),type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}for(let problem of collectConditionProblems(parsedFields))errors.push({rule:"schemas/conditions",message:problem.message,file});return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();init_project();import fs22 from"node:fs";import path25 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson2(path25.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs22.readFileSync(resolveProjectConfigPath(cwd),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson2(path25.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path25.isAbsolute(rawPath)?rawPath:path25.resolve(cwd,rawPath),pkg=readPackageJson2(path25.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs22.readFileSync(path25.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson2(filePath){try{return JSON.parse(fs22.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson2,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");import{execFile as execFile3}from"node:child_process";import fs23 from"node:fs";import path26 from"node:path";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3),LOCKFILE_MANAGERS2={"pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","yarn.lock":"yarn","package-lock.json":"npm"};async function inspectDependencyLifecycleScripts(cwd,execute=executeCommand){let selection=selectPackageManager(cwd);if(!selection)return{status:"warning",message:"Dependency lifecycle-script approval check skipped: no package manager could be selected from package.json or a lockfile."};if(!fs23.existsSync(path26.join(cwd,"node_modules")))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: ${selection.name} has no installed node_modules state to inspect.`};if(selection.name==="yarn")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: Yarn has no stable standalone blocked-script listing command."};if(selection.name==="npm")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: this npm version has no supported read-only blocked-script listing command."};try{let versionResult=await execute(selection.name,["--version"],cwd);if(selection.version&&!matchesRequestedVersion(versionResult.stdout,selection.version))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: the installed ${selection.name} version ${versionResult.stdout.trim()||"unknown"} does not match the exact packageManager pin ${selection.name}@${selection.version}.`};if(selection.name==="pnpm"&&!supportsPnpmIgnoredBuilds(versionResult.stdout))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: pnpm ${versionResult.stdout.trim()||"unknown"} does not support pnpm ignored-builds inspection (requires pnpm 10.1+).`};let args=selection.name==="pnpm"?["ignored-builds"]:["pm","untrusted"],result=await execute(selection.name,args,cwd);return selection.name==="pnpm"?parsePnpmIgnoredBuilds(result.stdout):parseBunUntrusted(result.stdout)}catch(error){return{status:"warning",message:`Dependency lifecycle-script approval check skipped: could not inspect ${selection.name} install state (${error instanceof Error?error.message:String(error)}).`}}}__name(inspectDependencyLifecycleScripts,"inspectDependencyLifecycleScripts");function parsePnpmIgnoredBuilds(output){let lines=output.split(/\r?\n/),section=null,packages=[];for(let line of lines){let trimmed=line.trim();if(/^Automatically ignored builds during installation:/i.test(trimmed)){section="automatic";continue}if(/^Explicitly ignored package builds/i.test(trimmed)){section="explicit";continue}if(section!=="automatic"||trimmed.length===0)continue;let entry=/^\s{2,}(\S.*)$/.exec(line)?.[1]?.trim();if(!entry){section=null;continue}if(/^Cannot identify as no node_modules found$/i.test(entry))return{status:"warning",message:"Dependency lifecycle-script approval check skipped: pnpm could not identify blocked builds because node_modules was not found."};/^None$/i.test(entry)||packages.push(entry.replace(/^[-*]\s+/,""))}return packages.length>0?{status:"blocked",packageManager:"pnpm",packages:[...new Set(packages)]}:{status:"clean",packageManager:"pnpm"}}__name(parsePnpmIgnoredBuilds,"parsePnpmIgnoredBuilds");function parseBunUntrusted(output){let packages=output.split(/\r?\n/).map(line=>line.trim().replace(/^[-*]\s+/,"")).map(line=>/^\.\/node_modules\/(.+?)\s+@[^\s]+$/.exec(line)?.[1]??null).filter(packageName=>packageName!==null);return packages.length>0?{status:"blocked",packageManager:"bun",packages:[...new Set(packages)]}:{status:"clean",packageManager:"bun"}}__name(parseBunUntrusted,"parseBunUntrusted");function selectPackageManager(cwd){let packageJson=readPackageJson3(path26.join(cwd,"package.json")),exact=typeof packageJson?.packageManager=="string"?parseExactPackageManager(packageJson.packageManager):null;if(exact)return exact;let lockfiles=Object.entries(LOCKFILE_MANAGERS2).filter(([lockfile])=>fs23.existsSync(path26.join(cwd,lockfile)));return lockfiles.length!==1?null:{name:lockfiles[0][1]}}__name(selectPackageManager,"selectPackageManager");function parseExactPackageManager(value){let match=/^(pnpm|bun|npm|yarn)@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/.exec(value.trim());return match?{name:match[1],version:match[2]}:null}__name(parseExactPackageManager,"parseExactPackageManager");function supportsPnpmIgnoredBuilds(version){let match=/^(\d+)\.(\d+)\.(\d+)/.exec(version.trim());if(!match)return!1;let major=Number(match[1]),minor=Number(match[2]);return major>10||major===10&&minor>=1}__name(supportsPnpmIgnoredBuilds,"supportsPnpmIgnoredBuilds");function matchesRequestedVersion(actual,requested){return actual.trim()===requested.split("+",1)[0]}__name(matchesRequestedVersion,"matchesRequestedVersion");async function executeCommand(command,args,cwd){let result=await execFileAsync3(command,args,{cwd,encoding:"utf8"});return{stdout:String(result.stdout),stderr:String(result.stderr)}}__name(executeCommand,"executeCommand");function readPackageJson3(filePath){try{return JSON.parse(fs23.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson3,"readPackageJson");init_project_context();init_project();init_dist();import{existsSync as existsSync8,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve7}from"node:path";import fs24 from"node:fs/promises";import path27 from"node:path";async function pathExists(targetPath){try{return await fs24.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs24.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path27.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs24.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path27.resolve(cwd,"dist/client"),serverDir=path27.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs24.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync7,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{join as join8}from"path";import{parseSync as parseSync2}from"oxc-parser";var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
1209
+ Fix: keep one of them, or give them distinct paths \u2014 a locale segment does not make two routes distinct.`);continue}previous||byShape.set(shape,route)}return errors}__name(validateRouteShapeCollisions,"validateRouteShapeCollisions");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Declare the locale as "/:locale/..." in ${args.configDisplayPath} and as ":locale?/..." in React Router so the default locale remains unprefixed.`)}if(!args.routesSourceUsesLegacyHelper)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);first2&&normalizeLocaleSpelling(first2)===`:${FIMO_LOCALE_PARAM}`||(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale project. It can capture locale URLs like "/${args.i18n.locales[0]}". Put an explicit optional ":locale?" segment first in the React Router path, or keep this route outside the localized route boundary.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesLegacyFimoRoutes(routesFilePath){if(!fs21.existsSync(routesFilePath))return!1;let source=fs21.readFileSync(routesFilePath,"utf-8"),importedName=source.match(/import\s*\{(?<imports>[^}]*)\}\s*from\s*['"]fimo\/react-router\/routes['"]/s)?.groups?.imports?.split(",").map(specifier=>specifier.trim().match(/^fimoRoutes(?:\s+as\s+(?<alias>[A-Za-z_$][\w$]*))?$/)?.groups?.alias??(specifier.trim()==="fimoRoutes"?"fimoRoutes":null)).find(name=>!!name);return importedName?new RegExp(`\\b${importedName}\\s*\\(`).test(source):!1}__name(sourceUsesLegacyFimoRoutes,"sourceUsesLegacyFimoRoutes");function normalizeLocaleSpelling(routePath){return routePath.replace(`:${FIMO_LOCALE_PARAM}?`,`:${FIMO_LOCALE_PARAM}`)}__name(normalizeLocaleSpelling,"normalizeLocaleSpelling");function registrablePaths(route){let declared=normalizeLocaleSpelling(route.contract.path);return route.contract.localeParam?.optional?[declared,route.contract.canonicalPath]:[declared]}__name(registrablePaths,"registrablePaths");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync6,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve6}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve6(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync6(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton,groups}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}let groupIds=new Set;if(groups!==void 0)if(!Array.isArray(groups))errors.push({rule:"schemas/groups",message:'"groups" must be an array.',file});else{let defaults=0;for(let[index2,group]of groups.entries()){let parsed=ContentFieldGroupSchema.safeParse(group);if(!parsed.success){errors.push({rule:"schemas/groups",message:`Group at index ${index2} is invalid: ${parsed.error.issues[0]?.message??"invalid group"}.`,file});continue}groupIds.has(parsed.data.id)&&errors.push({rule:"schemas/groups",message:`Group ID "${parsed.data.id}" is declared more than once.`,file}),groupIds.add(parsed.data.id),parsed.data.default&&(defaults+=1)}defaults>1&&errors.push({rule:"schemas/groups",message:"At most one group may be the default.",file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;let parsedFields={};for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition,memberships=Array.isArray(definition.group)?definition.group:definition.group===void 0?[]:[definition.group];new Set(memberships).size!==memberships.length&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" lists the same group more than once.`,file});for(let membership of memberships)(typeof membership!="string"||!groupIds.has(membership))&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" references unknown group "${String(membership)}".`,file});if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"localized"in definition&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "localized" is not supported. Use "i18n": false to share one value across locales.`,file}),"i18n"in definition&&(typeof definition.i18n!="boolean"?errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" must be true or false.`,file}):type==="blocks"&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" is not supported on blocks fields.`,file})),type==="blocks"){let parsed2=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed2.success){for(let issue of parsed2.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}parsedFields[fieldName]=parsed2.data,walkContentFields({[fieldName]:parsed2.data},({field,path:path52,structuredDepth,insideStructuredContent})=>{if(insideStructuredContent&&field.group!==void 0&&errors.push({rule:"schemas/field-group",message:`Field "${path52.join(".")}" cannot use "group" inside blocks.`,file}),field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path52.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path52.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path52.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(parsed.success&&(parsedFields[fieldName]=parsed.data),type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}for(let problem of collectConditionProblems(parsedFields))errors.push({rule:"schemas/conditions",message:problem.message,file});return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();init_project();import fs22 from"node:fs";import path25 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson2(path25.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs22.readFileSync(resolveProjectConfigPath(cwd),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson2(path25.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path25.isAbsolute(rawPath)?rawPath:path25.resolve(cwd,rawPath),pkg=readPackageJson2(path25.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs22.readFileSync(path25.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson2(filePath){try{return JSON.parse(fs22.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson2,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");import{execFile as execFile3}from"node:child_process";import fs23 from"node:fs";import path26 from"node:path";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3),LOCKFILE_MANAGERS2={"pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","yarn.lock":"yarn","package-lock.json":"npm"};async function inspectDependencyLifecycleScripts(cwd,execute=executeCommand){let selection=selectPackageManager(cwd);if(!selection)return{status:"warning",message:"Dependency lifecycle-script approval check skipped: no package manager could be selected from package.json or a lockfile."};if(!fs23.existsSync(path26.join(cwd,"node_modules")))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: ${selection.name} has no installed node_modules state to inspect.`};if(selection.name==="yarn")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: Yarn has no stable standalone blocked-script listing command."};if(selection.name==="npm")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: this npm version has no supported read-only blocked-script listing command."};try{let versionResult=await execute(selection.name,["--version"],cwd);if(selection.version&&!matchesRequestedVersion(versionResult.stdout,selection.version))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: the installed ${selection.name} version ${versionResult.stdout.trim()||"unknown"} does not match the exact packageManager pin ${selection.name}@${selection.version}.`};if(selection.name==="pnpm"&&!supportsPnpmIgnoredBuilds(versionResult.stdout))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: pnpm ${versionResult.stdout.trim()||"unknown"} does not support pnpm ignored-builds inspection (requires pnpm 10.1+).`};let args=selection.name==="pnpm"?["ignored-builds"]:["pm","untrusted"],result=await execute(selection.name,args,cwd);return selection.name==="pnpm"?parsePnpmIgnoredBuilds(result.stdout):parseBunUntrusted(result.stdout)}catch(error){return{status:"warning",message:`Dependency lifecycle-script approval check skipped: could not inspect ${selection.name} install state (${error instanceof Error?error.message:String(error)}).`}}}__name(inspectDependencyLifecycleScripts,"inspectDependencyLifecycleScripts");function parsePnpmIgnoredBuilds(output){let lines=output.split(/\r?\n/),section=null,packages=[];for(let line of lines){let trimmed=line.trim();if(/^Automatically ignored builds during installation:/i.test(trimmed)){section="automatic";continue}if(/^Explicitly ignored package builds/i.test(trimmed)){section="explicit";continue}if(section!=="automatic"||trimmed.length===0)continue;let entry=/^\s{2,}(\S.*)$/.exec(line)?.[1]?.trim();if(!entry){section=null;continue}if(/^Cannot identify as no node_modules found$/i.test(entry))return{status:"warning",message:"Dependency lifecycle-script approval check skipped: pnpm could not identify blocked builds because node_modules was not found."};/^None$/i.test(entry)||packages.push(entry.replace(/^[-*]\s+/,""))}return packages.length>0?{status:"blocked",packageManager:"pnpm",packages:[...new Set(packages)]}:{status:"clean",packageManager:"pnpm"}}__name(parsePnpmIgnoredBuilds,"parsePnpmIgnoredBuilds");function parseBunUntrusted(output){let packages=output.split(/\r?\n/).map(line=>line.trim().replace(/^[-*]\s+/,"")).map(line=>/^\.\/node_modules\/(.+?)\s+@[^\s]+$/.exec(line)?.[1]??null).filter(packageName=>packageName!==null);return packages.length>0?{status:"blocked",packageManager:"bun",packages:[...new Set(packages)]}:{status:"clean",packageManager:"bun"}}__name(parseBunUntrusted,"parseBunUntrusted");function selectPackageManager(cwd){let packageJson=readPackageJson3(path26.join(cwd,"package.json")),exact=typeof packageJson?.packageManager=="string"?parseExactPackageManager(packageJson.packageManager):null;if(exact)return exact;let lockfiles=Object.entries(LOCKFILE_MANAGERS2).filter(([lockfile])=>fs23.existsSync(path26.join(cwd,lockfile)));return lockfiles.length!==1?null:{name:lockfiles[0][1]}}__name(selectPackageManager,"selectPackageManager");function parseExactPackageManager(value){let match=/^(pnpm|bun|npm|yarn)@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/.exec(value.trim());return match?{name:match[1],version:match[2]}:null}__name(parseExactPackageManager,"parseExactPackageManager");function supportsPnpmIgnoredBuilds(version){let match=/^(\d+)\.(\d+)\.(\d+)/.exec(version.trim());if(!match)return!1;let major=Number(match[1]),minor=Number(match[2]);return major>10||major===10&&minor>=1}__name(supportsPnpmIgnoredBuilds,"supportsPnpmIgnoredBuilds");function matchesRequestedVersion(actual,requested){return actual.trim()===requested.split("+",1)[0]}__name(matchesRequestedVersion,"matchesRequestedVersion");async function executeCommand(command,args,cwd){let result=await execFileAsync3(command,args,{cwd,encoding:"utf8"});return{stdout:String(result.stdout),stderr:String(result.stderr)}}__name(executeCommand,"executeCommand");function readPackageJson3(filePath){try{return JSON.parse(fs23.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson3,"readPackageJson");init_project_context();init_project();init_dist();import{existsSync as existsSync8,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve7}from"node:path";import fs24 from"node:fs/promises";import path27 from"node:path";async function pathExists(targetPath){try{return await fs24.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs24.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path27.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs24.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path27.resolve(cwd,"dist/client"),serverDir=path27.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs24.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync7,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{join as join8}from"path";import{parseSync as parseSync2}from"oxc-parser";var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
1210
1210
  `);return{line:lines.length,column:lines[lines.length-1].length+1}}__name(getLineAndColumn,"getLineAndColumn");function isStringLiteral(node){return node?node.type==="Literal"&&typeof node.value=="string"||node.type==="TemplateLiteral"&&(!node.expressions||node.expressions.length===0):!1}__name(isStringLiteral,"isStringLiteral");var DYNAMIC_KEY_MESSAGE=`Dynamic translation key detected. The first argument to t() must be a string literal, not a variable or expression.
1211
1211
 
1212
1212
  This breaks source tracking for inline editing. Translation keys must be statically analyzable.
@@ -1355,7 +1355,7 @@ Run \`fimo integrations <command> --help\` for command-specific help.
1355
1355
  `);let removal="entriesDeleted"in response?` Deleted ${response.entriesDeleted} entr${response.entriesDeleted===1?"y":"ies"} and ${response.labelsDeleted} label${response.labelsDeleted===1?"":"s"}.`:"";return`${spec.verb} locale '${response.locale}' in '${env}'.${removal}
1356
1356
  Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_dist();init_project_context();var MAX_LIMIT=1e3;async function logsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.logs.read",{projectId:ctx.projectId,env:ctx.env});let limit;try{limit=parseLimit2(options.limit)}catch(error){ui.error({command:"logs",code:"LOGS_INVALID_LIMIT",message:errorMessage2(error)});return}let result;try{result=await api.getSandboxLogs(ctx.projectId,ctx.env,{limit,before:options.before})}catch(error){ui.error({command:"logs",code:"LOGS_REQUEST_FAILED",message:`Could not read sandbox logs: ${errorMessage2(error)}`});return}let data2={project_id:ctx.projectId,env:ctx.env,...result};if(result.status==="unavailable"){let{message}=result;ui.result({command:"logs",data:data2,render:__name(()=>message,"render")});return}let page=result,hint=page.previousCursor?buildOlderHint(page.previousCursor,ctx.env,options):void 0;ui.result({command:"logs",data:data2,render:__name(()=>renderLogs(page,ctx.env),"render"),...hint?{hint}:{}})}__name(logsCommand,"logsCommand");function parseLimit2(value){if(value===void 0)return;let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>MAX_LIMIT)throw new Error(`--limit must be an integer between 1 and ${MAX_LIMIT}.`);return limit}__name(parseLimit2,"parseLimit");function renderLogs(page,env){let lines=[],count=page.events.length;lines.push(`${env}: ${count} ${count===1?"event":"events"}${page.truncated?" (older ones remain)":""}`);for(let phase of page.retention.phases)lines.push(` ${renderPhase(phase)}`);if(page.retention.droppedOldest&&lines.push(" Note: the sandbox buffer dropped its oldest lines; they cannot be paged back to."),count===0)return lines.push(""),lines.push("No output recorded for these phases yet."),lines.join(`
1357
1357
  `);lines.push("");let width=Math.max(...page.events.map(event=>event.source.length));for(let event of[...page.events].reverse())lines.push(`${event.source.padEnd(width)} ${event.message}`);return lines.join(`
1358
- `)}__name(renderLogs,"renderLogs");function renderPhase(phase){let parts=[phase.status];return phase.exitCode!==null&&parts.push(`exit ${phase.exitCode}`),phase.startedAt&&parts.push(`started ${phase.startedAt}`),parts.push(`${phase.events} ${phase.events===1?"line":"lines"}`),`${phase.phase}: ${parts.join(", ")}`}__name(renderPhase,"renderPhase");function buildOlderHint(cursor,env,options){let args=["fimo","logs","--branch",env,"--before",cursor];return options.limit&&args.push("--limit",options.limit),options.cwd&&args.push("--cwd",options.cwd),`Older: ${args.map(quoteArgument).join(" ")}`}__name(buildOlderHint,"buildOlderHint");function quoteArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteArgument,"quoteArgument");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");init_esm();import{z as z80}from"zod";var projectScopeShape={projectId:z80.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z80.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z80.string().min(1).optional().describe("The locale to read or write."),entryDataField=z80.record(z80.string(),z80.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z80.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z80.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z80.uuid().describe("The Fimo media asset ID."),formIdField=z80.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z80.record(z80.string().min(1),z80.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z80.string().min(1).max(255).describe("Stable form name."),label:z80.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z80.object({...envScopeShape,task:z80.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z80.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z80.record(z80.string(),z80.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z80.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z80.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z80.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z80.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&&params.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z80.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z80.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z80.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z80.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z80.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z80.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,id:z80.uuid().describe("The entry ID."),locale:localeField,populate:z80.array(z80.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z80.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z80.object({...envScopeShape,search:z80.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z80.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z80.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z80.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,id:z80.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,id:z80.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,entries:z80.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,selection:z80.union([z80.object({ids:z80.array(z80.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z80.object({where:EntryWhereSchema}),z80.object({updates:z80.array(z80.object({id:z80.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,selection:z80.union([z80.object({ids:z80.array(z80.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z80.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z80.array(z80.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z80.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z80.object({...envScopeShape,locale:z80.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z80.object({...envScopeShape,locale:z80.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z80.object({...envScopeShape,key:labelKeyField,value:z80.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z80.object({...envScopeShape,records:z80.array(z80.object({key:labelKeyField,value:z80.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z80.object({...envScopeShape,locale:z80.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z80.object({...envScopeShape,parentId:z80.uuid().optional().describe("Limit results to one media-library folder."),search:z80.string().max(200).optional(),type:z80.enum(["file","folder"]).optional(),mimePrefix:z80.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z80.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z80.enum(["asc","desc"]).optional(),includePath:z80.boolean().optional(),excludeHidden:z80.boolean().optional(),limit:z80.number().int().min(1).max(100).optional(),offset:z80.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z80.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_read:{description:"Read exact bounded canonical text for one media asset, or ask one targeted model-backed question.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"read",operation:"assets.read",inputSchema:z80.object({...envScopeShape,id:assetIdField,cursor:z80.string().optional().describe("Opaque nextCursor from the previous exact page."),query:z80.string().trim().min(1).max(500).optional().describe("One targeted question about the asset.")}).refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/read`),body:{cursor:input.cursor,query:input.query}}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z80.object({...envScopeShape,name:z80.string().min(1).max(255).describe("Folder name."),parentId:z80.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z80.object({...envScopeShape,id:assetIdField,parentId:z80.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z80.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z80.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z80.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z80.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z80.object({...envScopeShape,id:formIdField,...z80.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z80.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z80.object({...envScopeShape,id:formIdField,limit:z80.number().int().min(1).max(100).optional(),offset:z80.number().int().min(0).optional(),searchQuery:z80.string().max(200).optional(),sortDirection:z80.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z80.object({...envScopeShape,id:formIdField,submissionId:z80.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z80.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z80.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z80.object({...envScopeShape,pattern:z80.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z80.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z80.object({...envScopeShape,pattern:z80.string().min(1).max(200).describe("Regular expression to search for."),include:z80.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z80.boolean().optional().describe("Case-insensitive matching."),maxMatches:z80.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z80.object({...envScopeShape,path:filePathField,content:z80.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z80.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z80.object({...envScopeShape,path:filePathField,oldString:z80.string().min(1).describe("Exact text to replace."),newString:z80.string().describe("Replacement text."),replaceAll:z80.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z80.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z80.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z80.object({...envScopeShape,agentName:z80.string().min(1).max(120).describe("The agent bundle name."),args:z80.record(z80.string(),z80.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z80.object({...projectScopeShape,sessionId:z80.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z81 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z81.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z81.union([z81.string(),z81.number().int()]),CursorSchema=z81.string(),TaskCreationParamsSchema=z81.looseObject({ttl:z81.union([z81.number(),z81.null()]).optional(),pollInterval:z81.number().optional()}),TaskMetadataSchema=z81.object({ttl:z81.number().optional()}),RelatedTaskMetadataSchema=z81.object({taskId:z81.string()}),RequestMetaSchema=z81.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z81.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z81.object({method:z81.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z81.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z81.object({method:z81.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z81.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z81.union([z81.string(),z81.number().int()]),JSONRPCRequestSchema=z81.object({jsonrpc:z81.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z81.object({jsonrpc:z81.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z81.object({jsonrpc:z81.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z81.object({jsonrpc:z81.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z81.object({code:z81.number().int(),message:z81.string(),data:z81.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z81.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z81.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z81.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z81.object({src:z81.string(),mimeType:z81.string().optional(),sizes:z81.array(z81.string()).optional(),theme:z81.enum(["light","dark"]).optional()}),IconsSchema=z81.object({icons:z81.array(IconSchema).optional()}),BaseMetadataSchema=z81.object({name:z81.string(),title:z81.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z81.string(),websiteUrl:z81.string().optional(),description:z81.string().optional()}),FormElicitationCapabilitySchema=z81.intersection(z81.object({applyDefaults:z81.boolean().optional()}),z81.record(z81.string(),z81.unknown())),ElicitationCapabilitySchema=z81.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z81.intersection(z81.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z81.record(z81.string(),z81.unknown()).optional())),ClientTasksCapabilitySchema=z81.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z81.looseObject({sampling:z81.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z81.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z81.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z81.looseObject({tools:z81.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z81.object({experimental:z81.record(z81.string(),AssertObjectSchema).optional(),sampling:z81.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z81.object({listChanged:z81.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z81.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z81.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z81.object({experimental:z81.record(z81.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z81.object({listChanged:z81.boolean().optional()}).optional(),resources:z81.object({subscribe:z81.boolean().optional(),listChanged:z81.boolean().optional()}).optional(),tools:z81.object({listChanged:z81.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z81.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z81.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z81.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z81.object({progress:z81.number(),total:z81.optional(z81.number()),message:z81.optional(z81.string())}),ProgressNotificationParamsSchema=z81.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z81.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z81.object({taskId:z81.string(),status:TaskStatusSchema,ttl:z81.union([z81.number(),z81.null()]),createdAt:z81.string(),lastUpdatedAt:z81.string(),pollInterval:z81.optional(z81.number()),statusMessage:z81.optional(z81.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z81.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z81.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z81.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z81.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z81.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z81.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z81.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z81.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z81.object({uri:z81.string(),mimeType:z81.optional(z81.string()),_meta:z81.record(z81.string(),z81.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z81.string()}),Base64Schema=z81.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z81.enum(["user","assistant"]),AnnotationsSchema=z81.object({audience:z81.array(RoleSchema).optional(),priority:z81.number().min(0).max(1).optional(),lastModified:z81.iso.datetime({offset:!0}).optional()}),ResourceSchema=z81.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z81.string(),description:z81.optional(z81.string()),mimeType:z81.optional(z81.string()),annotations:AnnotationsSchema.optional(),_meta:z81.optional(z81.looseObject({}))}),ResourceTemplateSchema=z81.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z81.string(),description:z81.optional(z81.string()),mimeType:z81.optional(z81.string()),annotations:AnnotationsSchema.optional(),_meta:z81.optional(z81.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z81.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z81.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z81.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z81.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z81.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z81.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z81.array(z81.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z81.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z81.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z81.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z81.object({name:z81.string(),description:z81.optional(z81.string()),required:z81.optional(z81.boolean())}),PromptSchema=z81.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z81.optional(z81.string()),arguments:z81.optional(z81.array(PromptArgumentSchema)),_meta:z81.optional(z81.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z81.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z81.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z81.string(),arguments:z81.record(z81.string(),z81.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z81.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z81.object({type:z81.literal("text"),text:z81.string(),annotations:AnnotationsSchema.optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),ImageContentSchema=z81.object({type:z81.literal("image"),data:Base64Schema,mimeType:z81.string(),annotations:AnnotationsSchema.optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),AudioContentSchema=z81.object({type:z81.literal("audio"),data:Base64Schema,mimeType:z81.string(),annotations:AnnotationsSchema.optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),ToolUseContentSchema=z81.object({type:z81.literal("tool_use"),name:z81.string(),id:z81.string(),input:z81.record(z81.string(),z81.unknown()),_meta:z81.record(z81.string(),z81.unknown()).optional()}),EmbeddedResourceSchema=z81.object({type:z81.literal("resource"),resource:z81.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z81.literal("resource_link")}),ContentBlockSchema=z81.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z81.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z81.string().optional(),messages:z81.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z81.object({title:z81.string().optional(),readOnlyHint:z81.boolean().optional(),destructiveHint:z81.boolean().optional(),idempotentHint:z81.boolean().optional(),openWorldHint:z81.boolean().optional()}),ToolExecutionSchema=z81.object({taskSupport:z81.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z81.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z81.string().optional(),inputSchema:z81.object({type:z81.literal("object"),properties:z81.record(z81.string(),AssertObjectSchema).optional(),required:z81.array(z81.string()).optional()}).catchall(z81.unknown()),outputSchema:z81.object({type:z81.literal("object"),properties:z81.record(z81.string(),AssertObjectSchema).optional(),required:z81.array(z81.string()).optional()}).catchall(z81.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z81.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z81.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z81.array(ContentBlockSchema).default([]),structuredContent:z81.record(z81.string(),z81.unknown()).optional(),isError:z81.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z81.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z81.string(),arguments:z81.record(z81.string(),z81.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z81.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z81.object({autoRefresh:z81.boolean().default(!0),debounceMs:z81.number().int().nonnegative().default(300)}),LoggingLevelSchema=z81.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z81.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z81.string().optional(),data:z81.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z81.object({name:z81.string().optional()}),ModelPreferencesSchema=z81.object({hints:z81.array(ModelHintSchema).optional(),costPriority:z81.number().min(0).max(1).optional(),speedPriority:z81.number().min(0).max(1).optional(),intelligencePriority:z81.number().min(0).max(1).optional()}),ToolChoiceSchema=z81.object({mode:z81.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z81.object({type:z81.literal("tool_result"),toolUseId:z81.string().describe("The unique identifier for the corresponding tool call."),content:z81.array(ContentBlockSchema).default([]),structuredContent:z81.object({}).loose().optional(),isError:z81.boolean().optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),SamplingContentSchema=z81.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z81.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z81.object({role:RoleSchema,content:z81.union([SamplingMessageContentBlockSchema,z81.array(SamplingMessageContentBlockSchema)]),_meta:z81.record(z81.string(),z81.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z81.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z81.string().optional(),includeContext:z81.enum(["none","thisServer","allServers"]).optional(),temperature:z81.number().optional(),maxTokens:z81.number().int(),stopSequences:z81.array(z81.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z81.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z81.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z81.string(),stopReason:z81.optional(z81.enum(["endTurn","stopSequence","maxTokens"]).or(z81.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z81.string(),stopReason:z81.optional(z81.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z81.string())),role:RoleSchema,content:z81.union([SamplingMessageContentBlockSchema,z81.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z81.object({type:z81.literal("boolean"),title:z81.string().optional(),description:z81.string().optional(),default:z81.boolean().optional()}),StringSchemaSchema=z81.object({type:z81.literal("string"),title:z81.string().optional(),description:z81.string().optional(),minLength:z81.number().optional(),maxLength:z81.number().optional(),format:z81.enum(["email","uri","date","date-time"]).optional(),default:z81.string().optional()}),NumberSchemaSchema=z81.object({type:z81.enum(["number","integer"]),title:z81.string().optional(),description:z81.string().optional(),minimum:z81.number().optional(),maximum:z81.number().optional(),default:z81.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z81.object({type:z81.literal("string"),title:z81.string().optional(),description:z81.string().optional(),enum:z81.array(z81.string()),default:z81.string().optional()}),TitledSingleSelectEnumSchemaSchema=z81.object({type:z81.literal("string"),title:z81.string().optional(),description:z81.string().optional(),oneOf:z81.array(z81.object({const:z81.string(),title:z81.string()})),default:z81.string().optional()}),LegacyTitledEnumSchemaSchema=z81.object({type:z81.literal("string"),title:z81.string().optional(),description:z81.string().optional(),enum:z81.array(z81.string()),enumNames:z81.array(z81.string()).optional(),default:z81.string().optional()}),SingleSelectEnumSchemaSchema=z81.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z81.object({type:z81.literal("array"),title:z81.string().optional(),description:z81.string().optional(),minItems:z81.number().optional(),maxItems:z81.number().optional(),items:z81.object({type:z81.literal("string"),enum:z81.array(z81.string())}),default:z81.array(z81.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z81.object({type:z81.literal("array"),title:z81.string().optional(),description:z81.string().optional(),minItems:z81.number().optional(),maxItems:z81.number().optional(),items:z81.object({anyOf:z81.array(z81.object({const:z81.string(),title:z81.string()}))}),default:z81.array(z81.string()).optional()}),MultiSelectEnumSchemaSchema=z81.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z81.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z81.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z81.literal("form").optional(),message:z81.string(),requestedSchema:z81.object({type:z81.literal("object"),properties:z81.record(z81.string(),PrimitiveSchemaDefinitionSchema),required:z81.array(z81.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z81.literal("url"),message:z81.string(),elicitationId:z81.string(),url:z81.string().url()}),ElicitRequestParamsSchema=z81.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z81.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z81.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z81.enum(["accept","decline","cancel"]),content:z81.preprocess(val2=>val2===null?void 0:val2,z81.record(z81.string(),z81.union([z81.string(),z81.number(),z81.boolean(),z81.array(z81.string())])).optional())}),ResourceTemplateReferenceSchema=z81.object({type:z81.literal("ref/resource"),uri:z81.string()});var PromptReferenceSchema=z81.object({type:z81.literal("ref/prompt"),name:z81.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z81.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z81.object({name:z81.string(),value:z81.string()}),context:z81.object({arguments:z81.record(z81.string(),z81.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z81.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z81.looseObject({values:z81.array(z81.string()).max(100),total:z81.optional(z81.number().int()),hasMore:z81.optional(z81.boolean())})}),RootSchema=z81.object({uri:z81.string().startsWith("file://"),name:z81.string().optional(),_meta:z81.record(z81.string(),z81.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z81.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z81.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z81.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z81.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z81.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z81.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z81.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z81.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z81.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage6,refs){refs?.errorMessages&&errorMessage6&&(res.errorMessage={...res.errorMessage,[key]:errorMessage6})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage6,refs){res[key]=value,addErrorMessage(res,key,errorMessage6,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
1358
+ `)}__name(renderLogs,"renderLogs");function renderPhase(phase){let parts=[phase.status];return phase.exitCode!==null&&parts.push(`exit ${phase.exitCode}`),phase.startedAt&&parts.push(`started ${phase.startedAt}`),parts.push(`${phase.events} ${phase.events===1?"line":"lines"}`),`${phase.phase}: ${parts.join(", ")}`}__name(renderPhase,"renderPhase");function buildOlderHint(cursor,env,options){let args=["fimo","logs","--branch",env,"--before",cursor];return options.limit&&args.push("--limit",options.limit),options.cwd&&args.push("--cwd",options.cwd),`Older: ${args.map(quoteArgument).join(" ")}`}__name(buildOlderHint,"buildOlderHint");function quoteArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteArgument,"quoteArgument");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");init_esm();import{z as z81}from"zod";var projectScopeShape={projectId:z81.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z81.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z81.string().min(1).optional().describe("The locale to read or write."),entryDataField=z81.record(z81.string(),z81.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z81.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z81.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z81.uuid().describe("The Fimo media asset ID."),formIdField=z81.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z81.record(z81.string().min(1),z81.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z81.string().min(1).max(255).describe("Stable form name."),label:z81.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z81.object({...envScopeShape,task:z81.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z81.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z81.record(z81.string(),z81.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z81.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z81.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z81.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z81.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&&params.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z81.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z81.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z81.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z81.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z81.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z81.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,id:z81.uuid().describe("The entry ID."),locale:localeField,populate:z81.array(z81.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z81.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z81.object({...envScopeShape,search:z81.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z81.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z81.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z81.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,id:z81.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,id:z81.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,entries:z81.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,selection:z81.union([z81.object({ids:z81.array(z81.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z81.object({where:EntryWhereSchema}),z81.object({updates:z81.array(z81.object({id:z81.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,selection:z81.union([z81.object({ids:z81.array(z81.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z81.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z81.array(z81.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z81.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z81.object({...envScopeShape,locale:z81.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z81.object({...envScopeShape,locale:z81.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z81.object({...envScopeShape,key:labelKeyField,value:z81.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z81.object({...envScopeShape,records:z81.array(z81.object({key:labelKeyField,value:z81.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z81.object({...envScopeShape,locale:z81.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z81.object({...envScopeShape,parentId:z81.uuid().optional().describe("Limit results to one media-library folder."),search:z81.string().max(200).optional(),type:z81.enum(["file","folder"]).optional(),mimePrefix:z81.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z81.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z81.enum(["asc","desc"]).optional(),includePath:z81.boolean().optional(),excludeHidden:z81.boolean().optional(),limit:z81.number().int().min(1).max(100).optional(),offset:z81.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z81.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_read:{description:"Read exact bounded canonical text for one media asset, or ask one targeted model-backed question.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"read",operation:"assets.read",inputSchema:z81.object({...envScopeShape,id:assetIdField,cursor:z81.string().optional().describe("Opaque nextCursor from the previous exact page."),query:z81.string().trim().min(1).max(500).optional().describe("One targeted question about the asset.")}).refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/read`),body:{cursor:input.cursor,query:input.query}}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z81.object({...envScopeShape,name:z81.string().min(1).max(255).describe("Folder name."),parentId:z81.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z81.object({...envScopeShape,id:assetIdField,parentId:z81.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z81.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z81.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z81.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z81.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z81.object({...envScopeShape,id:formIdField,...z81.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z81.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z81.object({...envScopeShape,id:formIdField,limit:z81.number().int().min(1).max(100).optional(),offset:z81.number().int().min(0).optional(),searchQuery:z81.string().max(200).optional(),sortDirection:z81.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z81.object({...envScopeShape,id:formIdField,submissionId:z81.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z81.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z81.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z81.object({...envScopeShape,pattern:z81.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z81.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z81.object({...envScopeShape,pattern:z81.string().min(1).max(200).describe("Regular expression to search for."),include:z81.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z81.boolean().optional().describe("Case-insensitive matching."),maxMatches:z81.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z81.object({...envScopeShape,path:filePathField,content:z81.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z81.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z81.object({...envScopeShape,path:filePathField,oldString:z81.string().min(1).describe("Exact text to replace."),newString:z81.string().describe("Replacement text."),replaceAll:z81.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z81.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z81.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z81.object({...envScopeShape,agentName:z81.string().min(1).max(120).describe("The agent bundle name."),args:z81.record(z81.string(),z81.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z81.object({...projectScopeShape,sessionId:z81.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z82 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z82.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z82.union([z82.string(),z82.number().int()]),CursorSchema=z82.string(),TaskCreationParamsSchema=z82.looseObject({ttl:z82.union([z82.number(),z82.null()]).optional(),pollInterval:z82.number().optional()}),TaskMetadataSchema=z82.object({ttl:z82.number().optional()}),RelatedTaskMetadataSchema=z82.object({taskId:z82.string()}),RequestMetaSchema=z82.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z82.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z82.object({method:z82.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z82.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z82.object({method:z82.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z82.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z82.union([z82.string(),z82.number().int()]),JSONRPCRequestSchema=z82.object({jsonrpc:z82.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z82.object({jsonrpc:z82.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z82.object({jsonrpc:z82.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z82.object({jsonrpc:z82.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z82.object({code:z82.number().int(),message:z82.string(),data:z82.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z82.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z82.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z82.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z82.object({src:z82.string(),mimeType:z82.string().optional(),sizes:z82.array(z82.string()).optional(),theme:z82.enum(["light","dark"]).optional()}),IconsSchema=z82.object({icons:z82.array(IconSchema).optional()}),BaseMetadataSchema=z82.object({name:z82.string(),title:z82.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z82.string(),websiteUrl:z82.string().optional(),description:z82.string().optional()}),FormElicitationCapabilitySchema=z82.intersection(z82.object({applyDefaults:z82.boolean().optional()}),z82.record(z82.string(),z82.unknown())),ElicitationCapabilitySchema=z82.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z82.intersection(z82.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z82.record(z82.string(),z82.unknown()).optional())),ClientTasksCapabilitySchema=z82.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z82.looseObject({sampling:z82.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z82.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z82.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z82.looseObject({tools:z82.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z82.object({experimental:z82.record(z82.string(),AssertObjectSchema).optional(),sampling:z82.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z82.object({listChanged:z82.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z82.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z82.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z82.object({experimental:z82.record(z82.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z82.object({listChanged:z82.boolean().optional()}).optional(),resources:z82.object({subscribe:z82.boolean().optional(),listChanged:z82.boolean().optional()}).optional(),tools:z82.object({listChanged:z82.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z82.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z82.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z82.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z82.object({progress:z82.number(),total:z82.optional(z82.number()),message:z82.optional(z82.string())}),ProgressNotificationParamsSchema=z82.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z82.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z82.object({taskId:z82.string(),status:TaskStatusSchema,ttl:z82.union([z82.number(),z82.null()]),createdAt:z82.string(),lastUpdatedAt:z82.string(),pollInterval:z82.optional(z82.number()),statusMessage:z82.optional(z82.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z82.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z82.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z82.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z82.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z82.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z82.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z82.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z82.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z82.object({uri:z82.string(),mimeType:z82.optional(z82.string()),_meta:z82.record(z82.string(),z82.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z82.string()}),Base64Schema=z82.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z82.enum(["user","assistant"]),AnnotationsSchema=z82.object({audience:z82.array(RoleSchema).optional(),priority:z82.number().min(0).max(1).optional(),lastModified:z82.iso.datetime({offset:!0}).optional()}),ResourceSchema=z82.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z82.string(),description:z82.optional(z82.string()),mimeType:z82.optional(z82.string()),annotations:AnnotationsSchema.optional(),_meta:z82.optional(z82.looseObject({}))}),ResourceTemplateSchema=z82.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z82.string(),description:z82.optional(z82.string()),mimeType:z82.optional(z82.string()),annotations:AnnotationsSchema.optional(),_meta:z82.optional(z82.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z82.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z82.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z82.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z82.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z82.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z82.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z82.array(z82.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z82.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z82.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z82.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z82.object({name:z82.string(),description:z82.optional(z82.string()),required:z82.optional(z82.boolean())}),PromptSchema=z82.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z82.optional(z82.string()),arguments:z82.optional(z82.array(PromptArgumentSchema)),_meta:z82.optional(z82.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z82.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z82.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z82.string(),arguments:z82.record(z82.string(),z82.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z82.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z82.object({type:z82.literal("text"),text:z82.string(),annotations:AnnotationsSchema.optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),ImageContentSchema=z82.object({type:z82.literal("image"),data:Base64Schema,mimeType:z82.string(),annotations:AnnotationsSchema.optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),AudioContentSchema=z82.object({type:z82.literal("audio"),data:Base64Schema,mimeType:z82.string(),annotations:AnnotationsSchema.optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),ToolUseContentSchema=z82.object({type:z82.literal("tool_use"),name:z82.string(),id:z82.string(),input:z82.record(z82.string(),z82.unknown()),_meta:z82.record(z82.string(),z82.unknown()).optional()}),EmbeddedResourceSchema=z82.object({type:z82.literal("resource"),resource:z82.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z82.literal("resource_link")}),ContentBlockSchema=z82.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z82.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z82.string().optional(),messages:z82.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z82.object({title:z82.string().optional(),readOnlyHint:z82.boolean().optional(),destructiveHint:z82.boolean().optional(),idempotentHint:z82.boolean().optional(),openWorldHint:z82.boolean().optional()}),ToolExecutionSchema=z82.object({taskSupport:z82.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z82.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z82.string().optional(),inputSchema:z82.object({type:z82.literal("object"),properties:z82.record(z82.string(),AssertObjectSchema).optional(),required:z82.array(z82.string()).optional()}).catchall(z82.unknown()),outputSchema:z82.object({type:z82.literal("object"),properties:z82.record(z82.string(),AssertObjectSchema).optional(),required:z82.array(z82.string()).optional()}).catchall(z82.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z82.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z82.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z82.array(ContentBlockSchema).default([]),structuredContent:z82.record(z82.string(),z82.unknown()).optional(),isError:z82.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z82.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z82.string(),arguments:z82.record(z82.string(),z82.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z82.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z82.object({autoRefresh:z82.boolean().default(!0),debounceMs:z82.number().int().nonnegative().default(300)}),LoggingLevelSchema=z82.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z82.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z82.string().optional(),data:z82.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z82.object({name:z82.string().optional()}),ModelPreferencesSchema=z82.object({hints:z82.array(ModelHintSchema).optional(),costPriority:z82.number().min(0).max(1).optional(),speedPriority:z82.number().min(0).max(1).optional(),intelligencePriority:z82.number().min(0).max(1).optional()}),ToolChoiceSchema=z82.object({mode:z82.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z82.object({type:z82.literal("tool_result"),toolUseId:z82.string().describe("The unique identifier for the corresponding tool call."),content:z82.array(ContentBlockSchema).default([]),structuredContent:z82.object({}).loose().optional(),isError:z82.boolean().optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),SamplingContentSchema=z82.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z82.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z82.object({role:RoleSchema,content:z82.union([SamplingMessageContentBlockSchema,z82.array(SamplingMessageContentBlockSchema)]),_meta:z82.record(z82.string(),z82.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z82.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z82.string().optional(),includeContext:z82.enum(["none","thisServer","allServers"]).optional(),temperature:z82.number().optional(),maxTokens:z82.number().int(),stopSequences:z82.array(z82.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z82.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z82.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z82.string(),stopReason:z82.optional(z82.enum(["endTurn","stopSequence","maxTokens"]).or(z82.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z82.string(),stopReason:z82.optional(z82.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z82.string())),role:RoleSchema,content:z82.union([SamplingMessageContentBlockSchema,z82.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z82.object({type:z82.literal("boolean"),title:z82.string().optional(),description:z82.string().optional(),default:z82.boolean().optional()}),StringSchemaSchema=z82.object({type:z82.literal("string"),title:z82.string().optional(),description:z82.string().optional(),minLength:z82.number().optional(),maxLength:z82.number().optional(),format:z82.enum(["email","uri","date","date-time"]).optional(),default:z82.string().optional()}),NumberSchemaSchema=z82.object({type:z82.enum(["number","integer"]),title:z82.string().optional(),description:z82.string().optional(),minimum:z82.number().optional(),maximum:z82.number().optional(),default:z82.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z82.object({type:z82.literal("string"),title:z82.string().optional(),description:z82.string().optional(),enum:z82.array(z82.string()),default:z82.string().optional()}),TitledSingleSelectEnumSchemaSchema=z82.object({type:z82.literal("string"),title:z82.string().optional(),description:z82.string().optional(),oneOf:z82.array(z82.object({const:z82.string(),title:z82.string()})),default:z82.string().optional()}),LegacyTitledEnumSchemaSchema=z82.object({type:z82.literal("string"),title:z82.string().optional(),description:z82.string().optional(),enum:z82.array(z82.string()),enumNames:z82.array(z82.string()).optional(),default:z82.string().optional()}),SingleSelectEnumSchemaSchema=z82.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z82.object({type:z82.literal("array"),title:z82.string().optional(),description:z82.string().optional(),minItems:z82.number().optional(),maxItems:z82.number().optional(),items:z82.object({type:z82.literal("string"),enum:z82.array(z82.string())}),default:z82.array(z82.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z82.object({type:z82.literal("array"),title:z82.string().optional(),description:z82.string().optional(),minItems:z82.number().optional(),maxItems:z82.number().optional(),items:z82.object({anyOf:z82.array(z82.object({const:z82.string(),title:z82.string()}))}),default:z82.array(z82.string()).optional()}),MultiSelectEnumSchemaSchema=z82.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z82.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z82.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z82.literal("form").optional(),message:z82.string(),requestedSchema:z82.object({type:z82.literal("object"),properties:z82.record(z82.string(),PrimitiveSchemaDefinitionSchema),required:z82.array(z82.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z82.literal("url"),message:z82.string(),elicitationId:z82.string(),url:z82.string().url()}),ElicitRequestParamsSchema=z82.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z82.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z82.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z82.enum(["accept","decline","cancel"]),content:z82.preprocess(val2=>val2===null?void 0:val2,z82.record(z82.string(),z82.union([z82.string(),z82.number(),z82.boolean(),z82.array(z82.string())])).optional())}),ResourceTemplateReferenceSchema=z82.object({type:z82.literal("ref/resource"),uri:z82.string()});var PromptReferenceSchema=z82.object({type:z82.literal("ref/prompt"),name:z82.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z82.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z82.object({name:z82.string(),value:z82.string()}),context:z82.object({arguments:z82.record(z82.string(),z82.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z82.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z82.looseObject({values:z82.array(z82.string()).max(100),total:z82.optional(z82.number().int()),hasMore:z82.optional(z82.boolean())})}),RootSchema=z82.object({uri:z82.string().startsWith("file://"),name:z82.string().optional(),_meta:z82.record(z82.string(),z82.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z82.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z82.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z82.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z82.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z82.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z82.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z82.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z82.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z82.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage6,refs){refs?.errorMessages&&errorMessage6&&(res.errorMessage={...res.errorMessage,[key]:errorMessage6})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage6,refs){res[key]=value,addErrorMessage(res,key,errorMessage6,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
1359
1359
  ]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
1360
1360
  ]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
1361
1361
  `:`[${source[i]}\r
@@ -1421,7 +1421,7 @@ ${renderFields({"Run count":data2.usage.runCount,"Runs with output":data2.usage.
1421
1421
  Output
1422
1422
  ${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
1423
1423
  `)}__name(renderFields,"renderFields");function renderTable(headers,rows){if(rows.length===0)return"No results.";let widths=headers.map((header,index2)=>Math.max(header.length,...rows.map(row2=>String(row2[index2]??"").length)));return[headers,...rows].map(row2=>row2.map((value,index2)=>String(value).padEnd(widths[index2])).join(" ").trimEnd()).join(`
1424
- `)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_esm();init_dist();import fs49 from"node:fs";import path49 from"node:path";import{isDeepStrictEqual}from"node:util";init_sync_schemas();init_api();init_project_context();init_project();var SYSTEM_SCHEMA_FIELDS=new Set(RESERVED_CONTENT_FIELD_NAMES),SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message,options){super(message,options),this.name="SchemaCommandError",this.code=code2}};function isRecord4(value){return!!(value&&typeof value=="object"&&!Array.isArray(value))}__name(isRecord4,"isRecord");function schemaMatches(actual,expected){if(!isRecord4(actual)||!isRecord4(actual.fields))return!1;let userFields=Object.fromEntries(Object.entries(actual.fields).filter(([fieldName])=>!SYSTEM_SCHEMA_FIELDS.has(fieldName)));return actual.name===expected.name&&actual.label===expected.label&&actual.isSingleton===expected.isSingleton&&isDeepStrictEqual(actual.i18n,expected.i18n)&&isDeepStrictEqual(userFields,expected.fields)}__name(schemaMatches,"schemaMatches");async function readBackSchemaBatch(api,projectId,schemas3){let checks=await Promise.all(schemas3.map(async schema=>{try{let actual=await api.getSchema(projectId,schema.name);return{name:schema.name,actual,state:schemaMatches(actual,schema)?"matched":"mismatched"}}catch(error){if(error instanceof ApiRequestError&&error.status===404)return{name:schema.name,state:"absent"};throw error}})),matched=checks.filter(check=>check.state==="matched"),absent=checks.filter(check=>check.state==="absent"),mismatched=checks.filter(check=>check.state==="mismatched");return matched.length===schemas3.length?{state:"committed",results:matched.map(check=>check.actual)}:absent.length===schemas3.length?{state:"absent"}:{state:"ambiguous",details:[matched.length>0?`matched: ${matched.map(check=>check.name).join(", ")}`:null,absent.length>0?`absent: ${absent.map(check=>check.name).join(", ")}`:null,mismatched.length>0?`mismatched: ${mismatched.map(check=>check.name).join(", ")}`:null].filter(Boolean).join("; ")}}__name(readBackSchemaBatch,"readBackSchemaBatch");async function upsertSchemasWithReconciliation(api,projectId,schemas3,operations){let timeout;try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let firstReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(firstReadBack.state==="committed")return firstReadBack.results;if(firstReadBack.state==="ambiguous")throw ambiguousSchemaPushError(firstReadBack.details,timeout);try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let secondReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(secondReadBack.state==="committed")return secondReadBack.results;let detail=secondReadBack.state==="absent"?"all requested schemas remain absent after one retry":secondReadBack.details;throw ambiguousSchemaPushError(detail,timeout)}__name(upsertSchemasWithReconciliation,"upsertSchemasWithReconciliation");function ambiguousSchemaPushError(detail,cause){return new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 (${detail}). No further write was attempted; read the schemas back before rerunning.`,{cause})}__name(ambiguousSchemaPushError,"ambiguousSchemaPushError");async function readBackAfterTimeout(api,projectId,schemas3,timeout){try{return await readBackSchemaBatch(api,projectId,schemas3)}catch(error){let detail=error instanceof Error?error.message:String(error);throw new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 and read-back failed (${detail}). No retry was attempted.`,{cause:timeout})}}__name(readBackAfterTimeout,"readBackAfterTimeout");function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path49.join(cwd,"src/schemas"),allSchemaFiles=fs49.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs49.readFileSync(path49.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path49.join(schemasDir,file);if(!fs49.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path49.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
1424
+ `)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_esm();init_dist();import fs49 from"node:fs";import path49 from"node:path";import{isDeepStrictEqual}from"node:util";init_sync_schemas();init_api();init_project_context();init_project();var SYSTEM_SCHEMA_FIELDS=new Set(RESERVED_CONTENT_FIELD_NAMES),SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message,options){super(message,options),this.name="SchemaCommandError",this.code=code2}};function isRecord4(value){return!!(value&&typeof value=="object"&&!Array.isArray(value))}__name(isRecord4,"isRecord");function schemaMatches(actual,expected){if(!isRecord4(actual)||!isRecord4(actual.fields))return!1;let userFields=Object.fromEntries(Object.entries(actual.fields).filter(([fieldName])=>!SYSTEM_SCHEMA_FIELDS.has(fieldName)));return actual.name===expected.name&&actual.label===expected.label&&actual.isSingleton===expected.isSingleton&&isDeepStrictEqual(actual.i18n,expected.i18n)&&isDeepStrictEqual(actual.groups??[],expected.groups)&&isDeepStrictEqual(userFields,expected.fields)}__name(schemaMatches,"schemaMatches");async function readBackSchemaBatch(api,projectId,schemas3){let checks=await Promise.all(schemas3.map(async schema=>{try{let actual=await api.getSchema(projectId,schema.name);return{name:schema.name,actual,state:schemaMatches(actual,schema)?"matched":"mismatched"}}catch(error){if(error instanceof ApiRequestError&&error.status===404)return{name:schema.name,state:"absent"};throw error}})),matched=checks.filter(check=>check.state==="matched"),absent=checks.filter(check=>check.state==="absent"),mismatched=checks.filter(check=>check.state==="mismatched");return matched.length===schemas3.length?{state:"committed",results:matched.map(check=>check.actual)}:absent.length===schemas3.length?{state:"absent"}:{state:"ambiguous",details:[matched.length>0?`matched: ${matched.map(check=>check.name).join(", ")}`:null,absent.length>0?`absent: ${absent.map(check=>check.name).join(", ")}`:null,mismatched.length>0?`mismatched: ${mismatched.map(check=>check.name).join(", ")}`:null].filter(Boolean).join("; ")}}__name(readBackSchemaBatch,"readBackSchemaBatch");async function upsertSchemasWithReconciliation(api,projectId,schemas3,operations){let timeout;try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let firstReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(firstReadBack.state==="committed")return firstReadBack.results;if(firstReadBack.state==="ambiguous")throw ambiguousSchemaPushError(firstReadBack.details,timeout);try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let secondReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(secondReadBack.state==="committed")return secondReadBack.results;let detail=secondReadBack.state==="absent"?"all requested schemas remain absent after one retry":secondReadBack.details;throw ambiguousSchemaPushError(detail,timeout)}__name(upsertSchemasWithReconciliation,"upsertSchemasWithReconciliation");function ambiguousSchemaPushError(detail,cause){return new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 (${detail}). No further write was attempted; read the schemas back before rerunning.`,{cause})}__name(ambiguousSchemaPushError,"ambiguousSchemaPushError");async function readBackAfterTimeout(api,projectId,schemas3,timeout){try{return await readBackSchemaBatch(api,projectId,schemas3)}catch(error){let detail=error instanceof Error?error.message:String(error);throw new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 and read-back failed (${detail}). No retry was attempted.`,{cause:timeout})}}__name(readBackAfterTimeout,"readBackAfterTimeout");function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},groups:schema.groups??[],fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path49.join(cwd,"src/schemas"),allSchemaFiles=fs49.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs49.readFileSync(path49.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path49.join(schemasDir,file);if(!fs49.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path49.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
1425
1425
  `));return JSON.parse(fs49.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(api,ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSingle(ctx.projectId,typeName,{locale:options.locale,populate:options.populate});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let body=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),result=await api.updateSingle(ctx.projectId,typeName,options.locale,body);ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");init_skills();init_status();init_dist5();init_dist();init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();import{readFileSync as readFileSync11}from"node:fs";import path50 from"node:path";var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
1426
1426
  Examples:
1427
1427
  fimo support report "Preview deployment fails after validation"