fimo 2.0.1 → 2.1.0-staging.2

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,25 @@ 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 process8.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()}`,process8.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=path54.basename(filename,path54.extname(filename)),this}executableDir(path55){return path55===void 0?this._executableDir:(this._executableDir=path55,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(process8.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(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.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,path54){let conditionPath=[...path54,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,path54)=>{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,path54));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path54,fieldName,variant.uid]);else walk(field.schema.fields,[...path54,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path54,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path54,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.discriminatedUnion("command",[z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),z14.object({kind:z14.literal("app"),command:z14.literal("connect"),integrationKey:z14.string().trim().min(1).max(80)}).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(path54){return[...path54.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path54){return pageRouteParamNames(path54).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 record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).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(),toolCallOutcomes:z26.array(z26.object({toolName:z26.string().min(1).max(120),success:z26.boolean(),code:z26.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).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,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,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,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,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),type:z29.enum(["native","mcp"]).optional(),url:z29.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z29.array(IntegrationAuthModeDTOSchema),credentials:z29.array(IntegrationCredentialDefinitionDTOSchema),tools:z29.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z29.enum(["available","unavailable"]).optional(),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(),setupState:z29.enum(["setup_required","ready","attention"]),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),McpHeaderNameSchema=z29.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z29.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z29.record(McpHeaderNameSchema,z29.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z29.object({alias:z29.string().min(1).max(120).optional(),token:z29.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),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).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}),z29.object({mode:z29.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z29.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z29.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z29.union([z29.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z29.object({type:z29.literal("mcp"),name:z29.string().trim().min(1).max(120),url:z29.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z29.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z29.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z29.object({integrationKey:z29.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z29.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("oauth"),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),ReusableMcpServerAuthKindSchema=z29.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z29.object({id:z29.uuid(),name:z29.string().min(1),host:z29.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z29.string().min(1),availability:z29.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z29.object({query:z29.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z29.object({serverId:z29.uuid()}),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),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z29.array(ReusableMcpServerDTOSchema)),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("Pro"),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,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,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),PreviewInstallApprovalTargetSchema=z40.object({name:z40.string().min(1),locator:z40.string().min(1).optional(),source:z40.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),targets:z40.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional(),approval:z40.object({id:z40.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z40.object({approvalId:z40.uuid()}),PreviewInstallPolicyApprovalEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal("progress"),step:z40.enum(["approval","install","restart","readiness"]),message:z40.string()}),z40.object({type:z40.literal("approved")}),z40.object({type:z40.literal("complete")}),z40.object({type:z40.literal("error"),code:z40.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z40.string()})])}});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"]),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()})}),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((path54,ctx)=>{let segments=path54.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("cli"),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:path54,message}=issue;return`${Array.isArray(path54)&&path54.length>0?`${path54.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,path54,status,detail,code2,body){super(`API ${method} ${path54} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path54,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}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(path54,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}${path54}`,{...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",path54,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path54,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}${path54}`,{...init,headers})}async rawRequest(path54,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}${path54}`,{...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"} ${path54} 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 addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).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 connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).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,path54,opts={}){let qs=lazyFetchQs(opts.against,{path:path54});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),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).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(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.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,path54){let conditionPath=[...path54,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,path54)=>{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,path54));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path54,fieldName,variant.uid]);else walk(field.schema.fields,[...path54,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path54,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path54,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.discriminatedUnion("command",[z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),z14.object({kind:z14.literal("app"),command:z14.literal("connect"),integrationKey:z14.string().trim().min(1).max(80)}).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";function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"series":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"findings":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"image":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
43
+ `)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.fallback?.length??0),0)}function reportBlockMarkdown(block){let parts=[];switch(block.title&&parts.push(`## ${block.title}`),block.type){case"text":parts.push(block.text);break;case"metric":parts.push(block.items.map(item=>[`**${item.value}${item.unit??""}** \u2014 ${item.label}`,item.note].filter(Boolean).join(`
44
+ `)).join(`
45
+
46
+ `));break;case"series":parts.push(block.points.map(point=>`- ${point.label}: ${formatReportValue(point.value,block.unit)}`).join(`
47
+ `)),block.caption&&parts.push(block.caption);break;case"findings":parts.push(block.items.map(item=>[`**${[item.label,item.heading].filter(Boolean).join(" \u2014 ")}**`,item.body,item.evidence].filter(Boolean).join(`
48
+ `)).join(`
49
+
50
+ `));break;case"table":parts.push([`| ${block.columns.map(column=>escapeCell(column.label)).join(" | ")} |`,`| ${block.columns.map(()=>"---").join(" | ")} |`,...block.rows.map(row2=>`| ${row2.cells.map(cell=>escapeCell(cell.text)).join(" | ")} |`)].join(`
51
+ `)),block.caption&&parts.push(block.caption);break;case"image":parts.push([`_${block.alt}_`,block.caption].filter(Boolean).join(`
52
+
53
+ `));break;case"links":parts.push(block.items.map(item=>`- [${escapeCell(item.label)}](${item.url})${item.description?` \u2014 ${item.description}`:""}`).join(`
54
+ `));break;case"code":parts.push(`\`\`\`${block.language??""}
55
+ ${block.code}
56
+ \`\`\``),block.caption&&parts.push(block.caption);break}return parts.join(`
57
+
58
+ `)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&&sections.push(...document.details.map(reportBlockMarkdown)),sections.join(`
59
+
60
+ `)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),ReportSeriesBlockSchema=z15.object({type:z15.literal("series"),...blockCommon,unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."})}),ReportFindingsBlockSchema=z15.object({type:z15.literal("findings"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema,label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Several ranked problems, risks, or recommendations. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index2)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportImageBlockSchema=z15.object({type:z15.literal("image"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual evidence or a visual deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z16}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=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.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:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.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(path54){return[...path54.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path54){return pageRouteParamNames(path54).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 record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).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 z17}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=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),previewEnabled:z17.boolean().default(!0),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}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=z18.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z18.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z18.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z18.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z18.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),EnvDiffResultSchema=z18.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z18.coerce.date(),surfaces:z18.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z19}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=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:EnvSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}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=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}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=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}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=z22.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z22.object({type:z22.literal("manual")}),ScheduleTriggerSchema=z22.object({type:z22.literal("schedule"),cron:z22.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:z22.string().optional()}),WebhookTriggerSchema=z22.object({type:z22.literal("webhook"),path:z22.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z22.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z23}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=z23.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z23.object({token:z23.string().min(1),risk:CapabilityRiskTierSchema,description:z23.string()}),AgentSubAgentSummarySchema=z23.object({name:z23.string().min(1),grant:z23.enum(["inherit","explicit"]),effectiveCaps:z23.array(z23.string().min(1))}),AgentInstallSummaryDTOSchema=z23.object({agentName:z23.string().min(1),env:z23.string().min(1),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z23.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z23.array(CapabilitySummaryEntrySchema),criticalCapabilities:z23.array(CapabilitySummaryEntrySchema),subAgents:z23.array(AgentSubAgentSummarySchema),declaresDelegate:z23.boolean(),cycle:z23.array(z23.string()).nullable(),missingSubAgents:z23.array(z23.string()),warnings:z23.array(z23.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z24}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=z24.object({kind:TriggerKindSchema,summary:z24.string()}),AgentListItemTriggerStateSchema=z24.object({triggerIndex:z24.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z24.boolean(),wired:z24.boolean(),syncError:z24.string().nullable()}),AgentListItemDTOSchema=z24.object({name:z24.string().min(1),description:z24.string().nullable(),goalFirstLine:z24.string().nullable(),declaredCapabilities:z24.array(CapabilitySummaryEntrySchema),triggers:z24.array(AgentListItemTriggerSchema),triggerStates:z24.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}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=z25.object({args:z25.unknown().optional(),requestId:z25.string().min(1).max(128).optional()}),DispatchSkippedSchema=z25.object({skipped:z25.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z25.object({sessionId:z25.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z25.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z26}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=z26.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.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=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}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_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z27.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z27.object({cpuMs:z27.number().nonnegative().default(0),netBytes:z27.number().nonnegative().default(0),walltimeMs:z27.number().nonnegative().default(0),llmTokensIn:z27.number().nonnegative().optional(),llmTokensOut:z27.number().nonnegative().optional(),stepCount:z27.number().int().nonnegative().optional(),toolCallCounts:z27.record(z27.string().min(1).max(120),z27.number().int().nonnegative()).optional(),toolCallOutcomes:z27.array(z27.object({toolName:z27.string().min(1).max(120),success:z27.boolean(),code:z27.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z27.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z27.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z27.object({capturedAt:z27.coerce.date(),fingerprint:z27.string().min(1).max(256),counts:z27.object({code:z27.number().int().nonnegative(),content:z27.number().int().nonnegative(),schemas:z27.number().int().nonnegative(),labels:z27.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z27.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z27.object({diff:DiffReportSchema,code:z27.array(CodeFileDiffSchema.extend({raw:z27.string().max(24576)})).max(200),schemas:z27.array(SchemaTypeDiffSchema).max(200),content:z27.array(z27.object({key:z27.string().min(1).max(512),collection:z27.string().min(1).max(256),slug:z27.string().max(512).optional(),verb:z27.enum(["added","modified","deleted"]),fields:z27.array(z27.object({name:z27.string().min(1).max(256),before:z27.unknown().optional(),after:z27.unknown().optional()})).max(20)})).max(200),labels:z27.array(z27.object({key:z27.string().min(1).max(512),locale:z27.string().min(1).max(64).optional(),before:z27.unknown().nullable(),after:z27.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z27.object({id:z27.uuid(),projectId:z27.uuid(),env:EnvSchema,agentName:z27.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z27.unknown().optional(),capabilities:z27.array(z27.string()).optional(),dataSources:z27.array(z27.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z27.string().nullable(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),cancelledAt:z27.coerce.date().nullable(),costUsd:z27.number().nonnegative(),costCeilingUsd:z27.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z27.boolean(),lastCheckpointId:z27.uuid().nullable(),branchEnvId:z27.uuid().nullable(),parentSessionId:z27.uuid().nullable(),terminalReason:z27.string().nullable(),errorMessage:z27.string().nullable(),reportDocument:ReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z27.object({id:z27.uuid(),sessionId:z27.uuid(),checkpointIdx:z27.number().int().nonnegative(),payloadRef:z27.string(),payloadSizeBytes:z27.number().int().nonnegative(),checksum:z27.string().length(64),createdAt:z27.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z27.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z27.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z27.object({session:AgentSessionDTOSchema,checkpoints:z27.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z27.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=z27.object({reason:z27.string().min(1).max(120).optional()})}});import{z as z28}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=z28.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z28.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z28.object({id:z28.uuid(),envId:z28.uuid(),sessionId:z28.uuid().nullable(),skillName:z28.string().min(1),classification:AgentBranchClassificationSchema,rationale:z28.string().nullable(),summary:z28.string().nullable(),surfaceDeltas:z28.record(z28.string(),z28.unknown()),createdAt:z28.coerce.date(),decidedAt:z28.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z28.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z28.object({path:z28.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z28.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z28.object({code:z28.literal("merge_conflict"),message:z28.string(),conflicts:z28.record(z28.string(),z28.number().int().nonnegative())})}});import{z as z29}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=z29.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z29.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=z29.object({description:z29.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z29.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),threadId:z29.uuid(),invocationId:z29.uuid(),agentKey:z29.string().min(1).max(120),anchorEnv:z29.string().min(1).max(64),retainedEnv:z29.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z29.string().min(1).nullable(),continuationInvocationId:z29.uuid().nullable(),askedAt:z29.coerce.date(),expiresAt:z29.coerce.date(),closedAt:z29.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z29.object({questionId:z29.uuid(),invocationId:z29.uuid(),askedAt:z29.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z29.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z29.object({question:AgentQuestionSchema,continuationInvocationId:z29.uuid(),deduped:z29.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z30}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,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,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,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z30.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z30.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z30.enum(["secret_text"]),IntegrationCredentialUsageSchema=z30.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z30.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z30.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z30.object({mode:IntegrationAuthModeSchema,label:z30.string().min(1),description:z30.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z30.object({id:z30.string().min(1),label:z30.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z30.boolean()}),IntegrationToolDefinitionDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),description:z30.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z30.object({title:z30.string().min(1),description:z30.string().min(1),command:z30.string().min(1).optional()}),IntegrationInfoDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),type:z30.enum(["native","mcp"]).optional(),url:z30.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z30.array(IntegrationAuthModeDTOSchema),credentials:z30.array(IntegrationCredentialDefinitionDTOSchema),tools:z30.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z30.enum(["available","unavailable"]).optional(),recipes:z30.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),installed:z30.boolean(),enabled:z30.boolean(),setupState:z30.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z30.string().nullable(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),connectionStatus:z30.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),installedAt:z30.coerce.date().nullable(),updatedAt:z30.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),enabled:z30.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z30.string(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z30.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z30.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z30.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z30.object({value:z30.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z30.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z30.object({id:z30.uuid(),organizationId:z30.string().min(1),integrationKey:z30.string().min(1),alias:z30.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z30.string().min(1),externalAccountName:z30.string().nullable(),externalBotUserId:z30.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z30.array(z30.string()),connectedAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z30.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z30.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z30.record(McpHeaderNameSchema,z30.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z30.object({alias:z30.string().min(1).max(120).optional(),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z30.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),alias:z30.string().min(1).max(120),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}),z30.object({mode:z30.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z30.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z30.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z30.union([z30.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z30.object({type:z30.literal("mcp"),name:z30.string().trim().min(1).max(120),url:z30.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z30.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z30.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z30.object({integrationKey:z30.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z30.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("oauth"),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),ReusableMcpServerAuthKindSchema=z30.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z30.object({id:z30.uuid(),name:z30.string().min(1),host:z30.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z30.string().min(1),availability:z30.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z30.object({query:z30.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z30.object({serverId:z30.uuid()}),StartProjectIntegrationConnectResponseSchema=z30.object({integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),integrationKey:z30.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z30.object({mode:z30.literal("oauth"),integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),BindProjectChannelRequestSchema=z30.object({ref:z30.string().min(1),connectionAlias:z30.string().min(1).optional(),agentName:z30.string().min(1).max(160).nullable().optional(),force:z30.boolean().optional()}),ListProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1)}),SearchProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1),connectionAlias:z30.string().min(1),query:z30.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),connectionId:z30.uuid(),externalWorkspaceId:z30.string().min(1),externalChannelId:z30.string().min(1),externalChannelName:z30.string().nullable(),agentName:z30.string().nullable(),enabled:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z30.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z30.object({id:z30.string().min(1),name:z30.string().min(1),visibility:z30.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z30.string().min(1).nullable(),canMove:z30.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z30.object({markdown:z30.boolean().optional(),summary:z30.boolean().optional(),links:z30.boolean().optional(),branding:z30.boolean().optional(),images:z30.boolean().optional(),html:z30.union([z30.literal("cleaned"),z30.literal("raw"),z30.boolean()]).optional(),json:z30.union([z30.boolean(),z30.object({prompt:z30.string().min(1).max(1e4),schema:z30.record(z30.string(),z30.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z30.object({url:z30.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z30.object({query:z30.string().min(1),maxResults:z30.number().int().positive().max(20).optional(),sources:z30.array(z30.enum(["web","news","images"])).min(1).max(3).optional(),categories:z30.array(z30.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z30.enum(["hour","day","week","month","year"]).optional(),location:z30.string().min(1).max(160).optional(),country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(100).optional(),types:z30.array(z30.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),sources:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),passages:z30.number().int().min(1).max(5).optional(),skills:z30.literal("only").optional(),language:z30.string().min(1).optional(),topic:z30.string().min(1).optional(),license:z30.string().min(1).optional(),minStars:z30.number().int().min(0).optional(),maxStars:z30.number().int().min(0).optional(),archived:z30.boolean().optional(),fork:z30.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(500).optional(),authors:z30.array(z30.string().min(1)).min(1).optional(),categories:z30.array(z30.string().min(1)).min(1).optional(),from:z30.iso.date().optional(),to:z30.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),query:z30.string().min(1).max(500).optional(),maxPassages:z30.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),intent:z30.string().min(1).max(500),mode:z30.enum(["similar","citers","references"]).optional(),maxResults:z30.number().int().min(1).max(500).optional(),rerank:z30.boolean().optional(),anchors:z30.array(z30.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z30.object({url:z30.string().url(),search:z30.string().min(1).optional(),limit:z30.number().int().positive().max(200).optional(),includeSubdomains:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z30.object({url:z30.string().url(),limit:z30.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z30.object({text:z30.string().min(1).max(200).optional(),cron:z30.string().min(1).max(120).optional(),timezone:z30.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z30.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z30.union([z30.object({type:z30.enum(["scrape","crawl"]).default("scrape"),urls:z30.array(z30.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z30.object({type:z30.literal("search"),queries:z30.array(z30.string().min(1).max(256)).min(1).max(12),searchWindow:z30.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z30.number().int().min(1).max(50).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z30.object({name:z30.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),notification:z30.object({email:z30.object({enabled:z30.boolean().default(!0),recipients:z30.array(z30.string().email()).min(1).max(20),includeDiffs:z30.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=z30.object({monitorId:z30.string().uuid(),name:z30.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),status:z30.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z30.object({monitorId:z30.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z30.string().uuid()}),RunProjectIntegrationToolRequestSchema=z30.object({tool:z30.string().min(1),input:z30.record(z30.string(),z30.unknown()),connectionAlias:z30.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z30.object({provider:z30.string().min(1),providerCredits:z30.number().nonnegative().optional(),providerCostUsd:z30.number().nonnegative().optional(),requests:z30.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z30.object({credits:z30.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),json:z30.unknown().optional(),branding:z30.record(z30.string(),z30.unknown()).optional(),warning:z30.string().optional()}),FirecrawlSearchToolOutputSchema=z30.object({query:z30.string(),provider:z30.literal("firecrawl"),warning:z30.string().optional(),results:z30.array(z30.object({title:z30.string(),url:z30.string(),snippet:z30.string().optional(),content:z30.string().optional(),score:z30.number().optional(),publishedAt:z30.string().optional()}))}),FirecrawlResearchPaperSchema=z30.object({paperId:z30.string(),primaryId:z30.string().optional(),ids:z30.record(z30.string(),z30.array(z30.string())).optional(),title:z30.string().optional(),abstract:z30.string().optional(),score:z30.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z30.object({text:z30.string(),score:z30.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(z30.object({id:z30.string(),type:z30.string().min(1).optional(),url:z30.string(),title:z30.string().optional(),passages:z30.array(z30.object({text:z30.string()}).passthrough())}).passthrough()),coverage:z30.record(z30.string(),z30.string()).optional(),reranked:z30.boolean().optional(),repos:z30.array(z30.record(z30.string(),z30.unknown())).optional(),sources:z30.array(z30.record(z30.string(),z30.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),paper:z30.record(z30.string(),z30.unknown()),paperId:z30.string().optional(),query:z30.string().optional(),passages:z30.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema),poolSize:z30.number().int().nonnegative(),truncated:z30.boolean(),note:z30.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),count:z30.number(),links:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),description:z30.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),total:z30.number(),pages:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),warning:z30.string().optional()})),warning:z30.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z30.object({cron:z30.string().optional(),text:z30.string().optional(),timezone:z30.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z30.object({id:z30.string().optional(),type:z30.enum(["scrape","crawl","search"]).optional(),urls:z30.array(z30.string()).optional(),queries:z30.array(z30.string()).optional(),searchWindow:z30.string().optional(),maxResults:z30.number().optional(),includeDomains:z30.array(z30.string()).optional(),excludeDomains:z30.array(z30.string()).optional(),scrapeOptions:z30.record(z30.string(),z30.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z30.object({id:z30.string(),name:z30.string(),status:z30.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z30.string().nullable().optional(),lastRunAt:z30.string().nullable().optional(),currentCheckId:z30.string().nullable().optional(),targets:z30.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z30.string().nullable().optional(),judgeEnabled:z30.boolean().optional(),estimatedCreditsPerMonth:z30.number().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z30.object({id:z30.string(),monitorId:z30.string(),scheduledFor:z30.string().nullable().optional(),startedAt:z30.string().nullable().optional(),finishedAt:z30.string().nullable().optional(),estimatedCredits:z30.number().optional(),reservedCredits:z30.number().optional(),actualCredits:z30.number().optional(),billingStatus:z30.string().nullable().optional(),summary:z30.object({totalPages:z30.number().optional(),same:z30.number().optional(),changed:z30.number().optional(),new:z30.number().optional(),removed:z30.number().optional(),error:z30.number().optional()}).passthrough().optional(),error:z30.string().nullable().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitors:z30.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),deleted:z30.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),checks:z30.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),check:FirecrawlMonitorCheckOutputSchema,next:z30.string().optional()}),FirecrawlToolKeySchema=z30.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=z30.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),tool:z30.string().min(1),connectionAlias:z30.string().min(1).nullable().optional(),output:z30.record(z30.string(),z30.unknown()),executedAt:z30.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z30.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z30.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z30.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z30.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z30.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z30.array(ProjectChannelCandidateDTOSchema))}});import{z as z31}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=z31.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z31.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z31.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z31.object({userId:z31.string().min(1),name:z31.string(),email:z31.string().min(1),subscribed:z31.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z31.object({maxSubscribers:z31.number().int().positive(),subscriberCount:z31.number().int().nonnegative(),effectiveRecipientCount:z31.number().int().nonnegative(),currentUserSubscribed:z31.boolean(),candidates:z31.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z31.object({userIds:z31.array(z31.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z31.object({topic:UserManagedNotificationTopicSchema,enabled:z31.boolean(),source:z31.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z31.object({topics:z31.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z31.object({enabled:z31.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z31.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z31.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z31.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z31.string().nullable(),maskedEmail:z31.string().min(1),applied:z31.boolean(),expiresAt:z31.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z31.object({scheduleId:z31.string().min(1),scheduleName:z31.string(),projectId:z31.string().min(1),projectName:z31.string(),env:z31.string().min(1)}),FollowedSchedulesSchema=z31.object({schedules:z31.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z32}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=z32.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=z32.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z32.uuid(),env:z32.string().min(1),name:z32.string().min(1),cron:z32.string().min(1),command:z32.string().min(1),secretKeys:z32.array(z32.string().min(1)),enabled:z32.boolean(),lastRunAt:z32.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z32.string().nullable(),overPolicyReasons:z32.array(z32.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120),cron:z32.string().min(1).max(120),command:z32.string().min(1).max(500),secretKeys:z32.array(ProjectSecretKeySchema).default([]),enabled:z32.boolean().optional()}),UpdateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120).optional(),cron:z32.string().min(1).max(120).optional(),command:z32.string().min(1).max(500).optional(),secretKeys:z32.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z32.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z32.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z32.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z32.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z32.object({maxRuns:z32.number().int().positive(),retentionDays:z32.number().int().positive().nullable(),outputRetentionDays:z32.number().int().positive(),maxOutputBytes:z32.number().int().positive()}),SchedulePolicyStateSchema=z32.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z32.object({code:z32.enum(["Free","Premium","Pro"]),source:z32.enum(["cached_subscription","free_fallback"]),activeSchedules:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),concurrency:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),compute:z32.object({settledMs:z32.number().int().nonnegative(),reservedMs:z32.number().int().nonnegative(),includedMs:z32.number().int().positive(),remainingMs:z32.number().int().nonnegative(),resetsAt:z32.coerce.date()}),upgrade:z32.object({code:z32.literal("Pro"),activeSchedulesLimit:z32.number().int().positive(),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),maxConcurrentRuns:z32.number().int().positive(),computeIncludedMs:z32.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z32.array(z32.string())}),ProjectScheduleUsageSchema=z32.object({runCount:z32.number().int().nonnegative(),runsWithOutput:z32.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z32.object({id:z32.uuid(),scheduleId:z32.uuid(),projectId:z32.uuid(),env:z32.string().min(1),scheduleName:z32.string().min(1),command:z32.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z32.object({id:z32.string().min(1),name:z32.string().min(1)}).nullable(),queuedAt:z32.coerce.date(),startedAt:z32.coerce.date().nullable(),finishedAt:z32.coerce.date().nullable(),exitCode:z32.number().int().nullable(),errorCode:z32.string().nullable(),error:z32.string().nullable(),outputBytes:z32.number().int().nonnegative(),outputTruncated:z32.boolean(),outputExpiresAt:z32.coerce.date().nullable(),metadataExpiresAt:z32.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z32.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z32.coerce.date().nullable(),items:z32.array(z32.object({key:z32.string().min(1),updatedAt:z32.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z32.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z32.object({trigger:z32.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z32.object({limit:z32.coerce.number().int().min(1).max(100).default(25),cursor:z32.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z32.object({items:z32.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z32.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z32.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z32.object({items:z32.array(ProjectScheduleRunDTOSchema),nextCursor:z32.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z33}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,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_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z33.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z33.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z33.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("user"),userId:z33.string().min(1)}).strict(),z33.object({kind:z33.literal("agent"),agentKey:z33.string().min(1).max(120),agentId:z33.uuid().optional()}).strict(),z33.object({kind:z33.literal("system")}).strict()]),NotificationSummarySchema=z33.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z33.string().trim().min(1).max(120).optional(),brief:ReportBriefSchema.optional()},NotificationRunOutcomeSchema=z33.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z33.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z33.discriminatedUnion("topic",[z33.object({topic:z33.literal("agent_question"),questionId:z33.uuid(),title:z33.string().trim().min(1).max(80),description:z33.string().trim().min(1).max(240)}).strict(),z33.object({topic:z33.literal("agent_run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().optional(),proposalId:z33.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z33.object({id:z33.uuid(),projectId:z33.uuid(),sourceKey:z33.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z33.literal(1),payload:NotificationPayloadSchema,createdAt:z33.coerce.date()}),NotificationRecipientStateSchema=z33.object({id:z33.uuid(),notificationId:z33.uuid(),projectId:z33.uuid(),userId:z33.string().min(1),readAt:z33.coerce.date().nullable(),archivedAt:z33.coerce.date().nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationDeliveryStateSchema=z33.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z33.object({id:z33.uuid(),notificationRecipientId:z33.uuid(),projectId:z33.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z33.number().int().nonnegative(),nextAttemptAt:z33.coerce.date().nullable(),lastAttemptAt:z33.coerce.date().nullable(),sentAt:z33.coerce.date().nullable(),failureCode:z33.string().max(80).nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationPreferenceSchema=z33.object({topic:WorkNotificationTopicSchema,channel:z33.literal("email"),enabled:z33.boolean(),source:z33.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z33.object({topics:z33.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("question"),questionId:z33.uuid()}).strict(),z33.object({kind:z33.literal("run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z33.object({kind:z33.literal("retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().nullable(),proposalId:z33.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z33.object({kind:z33.literal("merge_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().nullable()}).strict()]),NotificationViewSchema=z33.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z33.object({items:z33.array(NotificationViewSchema),nextCursor:z33.string().nullable(),unreadCount:z33.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z33.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z33.string().min(1).max(120).optional(),sourceKey:z33.string().min(1).max(255).optional(),unread:z33.stringbool().optional(),archived:z33.stringbool().optional(),limit:z33.coerce.number().int().min(1).max(100).optional(),cursor:z33.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=z33.object({recipient:NotificationRecipientStateSchema,unreadCount:z33.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z33.object({read:z33.boolean().optional(),archived:z33.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z34}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=z34.object({id:z34.uuid(),occurredAt:z34.coerce.date(),projectId:z34.uuid().nullable(),env:z34.string().nullable(),actor:z34.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z34.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z34.unknown().optional(),ipAddress:z34.string().nullable().optional(),userAgent:z34.string().nullable().optional(),error:z34.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z34.object({rows:z34.array(AuditLogRowDTOSchema),nextCursor:z34.string().nullable()})),AuditLogQuerySchema=z34.object({env:z34.string().optional(),action:AuditActionSchema.optional(),actor:z34.string().optional(),from:z34.coerce.date().optional(),to:z34.coerce.date().optional(),limit:z34.coerce.number().int().min(1).max(200).optional(),cursor:z34.string().optional()})}});import{z as z35}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=z35.object({surface:SurfaceNameSchema,key:z35.string(),label:z35.string()}),InlineSchema=z35.object({text:z35.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z35.discriminatedUnion("type",[z35.object({type:z35.literal("paragraph"),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("preview"),ref:DiffRefSchema,caption:z35.string().optional()}),z35.object({type:z35.literal("code"),code:z35.string(),lang:z35.string().optional(),caption:z35.string().optional()}),z35.object({type:z35.literal("risk"),level:z35.enum(["warning","error"]),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("list"),items:z35.array(z35.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z35.object({headline:z35.string(),blocks:z35.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z35.object({summary:EnvDiffSummarySchema,fingerprint:z35.string(),generatedAt:z35.coerce.date(),cached:z35.boolean().optional(),credits:z35.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z36}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=z36.object({date:z36.string(),visitors:z36.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z36.object({key:z36.string(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z36.object({path:z36.string(),pageName:z36.string().nullable().optional(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z36.object({preset:z36.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z36.string(),requestedTo:z36.string(),effectiveFrom:z36.string(),effectiveTo:z36.string(),isRetentionLimited:z36.boolean(),groupBy:z36.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z36.object({date:z36.string(),content:z36.string(),updatedAt:z36.string(),updatedByUserId:z36.string()}),ProjectPageviewAnalyticsDTOSchema=z36.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative(),bounceRate:z36.number().min(0).max(100),viewsPerVisit:z36.number().nonnegative(),averageVisitDurationSeconds:z36.number().nonnegative(),visitorsSeries:z36.array(ProjectDailyVisitorsDTOSchema),topPages:z36.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z36.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),email:z37.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z37.coerce.date(),createdAt:z37.coerce.date(),inviterUserId:z37.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z37.object({id:z37.string(),token:z37.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z37.object({success:z37.boolean(),projectId:z37.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),name:z38.string(),image:z38.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z38.object({count:z38.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z38.object({counts:z38.object({signed_up:z38.int(),activated:z38.int()}),credits:z38.object({total:z38.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z38.email(),emailVerified:z38.boolean(),createdAt:z38.coerce.date(),updatedAt:z38.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z39}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=z39.object({id:z39.string(),principalType:ProjectPrincipalTypeSchema,principalId:z39.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z39.coerce.date(),expiresAt:z39.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=z39.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z39.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z39.record(z39.string(),z39.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z39.object({access:z39.array(ProjectAccessItemDTOSchema),invites:z39.array(ProjectInviteDTOSchema),organization:z39.object({name:z39.string().nullable(),logo:z39.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z39.object({success:z39.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z39.object({success:z39.boolean(),projectId:z39.uuid()}))}});import{z as z40}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=z40.object({publicationStatus:PublicationStatusSchema,appUrl:z40.string().nullable(),lastPublishedAt:z40.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z41}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z41.object({url:z41.url(),expiresAt:z41.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z41.object({name:z41.string().min(1),locator:z41.string().min(1).optional(),source:z41.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z41.object({kind:z41.literal("dependency_build_scripts_blocked"),packageManager:z41.enum(["pnpm","yarn","bun"]),packages:z41.array(z41.string()),targets:z41.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z41.string(),approvalKey:z41.string(),command:z41.string().optional(),approval:z41.object({id:z41.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z41.object({code:z41.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z41.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z41.object({approvalId:z41.uuid()}),PreviewInstallPolicyApprovalEventSchema=z41.discriminatedUnion("type",[z41.object({type:z41.literal("progress"),step:z41.enum(["approval","install","restart","readiness"]),message:z41.string()}),z41.object({type:z41.literal("approved")}),z41.object({type:z41.literal("complete")}),z41.object({type:z41.literal("error"),code:z41.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z41.string()})])}});import{z as z42}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:z42.string(),slug:z42.string().nullable(),logo:z42.string().nullable(),metadata:z42.record(z42.string(),z42.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),email:z42.email(),image:z42.string().nullable()}),OrganizationMemberDTOSchema=z42.object({id:z42.string(),userId:z42.string(),organizationId:z42.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z42.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z43}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=z43.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z43.object({reason:CancellationReasonCodeSchema,details:z43.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z43.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z43.object({offerVersion:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),renewsOn:z43.string()}),PlanMigrationPreviewDTOSchema=z43.object({currency:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),startsAt:z43.string(),renewsAt:z43.string(),nextRenewalAmount:z43.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z43.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z43.object({id:z43.string(),organizationId:z43.string(),legacySubscriptionId:z43.string(),offeredPlanCode:z43.string(),offeredPlanName:z43.string(),offeredPriceAmount:z43.number(),offeredCurrency:z43.string(),offerVersion:z43.string(),state:PlanMigrationStateSchema,checkoutToken:z43.string().nullable(),deadlineAt:z43.string(),transitions:z43.array(z43.object({event:z43.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z43.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z43.object({included:z43.number().optional(),unitPrice:z43.number().optional(),dailyCap:z43.number().nullable().optional()}),EntitlementsDTOSchema=z43.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z43.object({retentionDays:z43.number().int().positive(),canUseExtendedDateRanges:z43.boolean()}).optional(),history:z43.object({retentionDays:z43.number().int().positive()}).optional(),members:z43.object({canInvite:z43.boolean(),maxMembers:z43.number().int().positive().nullable()}).optional(),domains:z43.object({canUseCustomDomains:z43.boolean(),maxDomains:z43.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z43.object({id:z43.string(),external_id:z43.string(),customerId:z43.string(),planId:z43.string(),planCode:z43.union([TemplateCodeSchema,z43.literal("Unknown")]),currentPeriod:z43.object({start:z43.string(),end:z43.string().nullable()}),cancelAt:z43.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z43.string(),nextPaymentAt:z43.string().nullable(),baseAmount:z43.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z43.object({totalCap:z43.number(),dailyCap:z43.number(),usedTotal:z43.number()}),CreditBalanceDTOSchema=z43.object({total:z43.number(),base:z43.number(),dailyBase:z43.number(),purchases:z43.number(),awards:z43.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z43.object({total:z43.number(),nearLimit:z43.boolean(),canChat:z43.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z43.object({dailyFreeAvailable:z43.number(),monthlyAvailable:z43.number(),purchasedAvailable:z43.number(),awardedAvailable:z43.number()}),ProjectDailyCreditAllowanceDTOSchema=z43.object({periodCap:z43.number(),dailyGrant:z43.number(),usedThisPeriod:z43.number(),remainingThisPeriod:z43.number()}),ProjectCreditBalanceDTOSchema=z43.object({projectId:z43.uuid(),organizationId:z43.string(),balance:z43.object({totalAvailable:z43.number(),nearLimit:z43.boolean(),canUseAi:z43.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z43.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z43.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z43.object({planCode:z43.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z43.object({source:z43.enum(["cached_subscription","free_fallback"]),settledMs:z43.number().int().nonnegative(),reservedMs:z43.number().int().nonnegative(),includedMs:z43.number().int().positive(),remainingMs:z43.number().int().nonnegative(),resetsAt:z43.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().nonnegative(),refillAmountUsd:z43.number().nonnegative()}),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().nonnegative().nullable(),refillAmountUsd:z43.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().min(.01).multipleOf(.01),refillAmountUsd:z43.number().min(.01).multipleOf(.01)}).strict(),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z43.object({invoiceId:z43.string(),newBalance:z43.int(),creditCount:z43.int(),amountUsd:z43.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z43.object({url:z43.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 z44}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=z44.object({brand:z44.string(),last4:z44.string(),exp:z44.string(),isDefault:z44.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z45}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=z45.string().superRefine((path54,ctx)=>{let segments=path54.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=z45.object({type:z45.literal("renameField"),contentType:z45.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z45.object({enabled:z45.boolean()}).strict(),ContentFieldGroupSchema=z45.object({id:z45.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z45.string().min(1).max(255),default:z45.boolean().optional()}).strict(),ContentTypeDTOSchema=z45.object({id:z45.string(),name:z45.string(),label:z45.string(),isSingleton:z45.boolean(),i18n:ContentTypeI18nSchema,groups:z45.array(ContentFieldGroupSchema).default([]),fields:z45.record(z45.string(),FieldDefinitionSchema),createdAt:z45.string(),updatedAt:z45.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z45.object({contentTypes:z45.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z45.object({id:z45.string(),entryId:z45.string(),documentId:z45.string(),slug:z45.string(),locale:z45.string().optional(),createdAt:z45.string(),updatedAt:z45.string(),__fimo:z45.object({contentType:z45.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({limit:z45.number(),offset:z45.number(),total:z45.number(),hasMore:z45.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z45.object({contentType:z45.string(),count:z45.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z45.object({counts:z45.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z45.object({count:z45.number().int().nonnegative(),sourceLocale:z45.string(),targetLocale:z45.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z45.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z45.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z45.union([z45.string(),z45.number(),z45.boolean(),z45.null()]),entryWhereOperatorSchema=z45.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z45.array(entryWhereScalarSchema).optional(),$nin:z45.array(entryWhereScalarSchema).optional(),$contains:z45.string().optional(),$startsWith:z45.string().optional(),$null:z45.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z45.object({data:z45.record(z45.string(),z45.unknown()),locale:z45.string().min(1).optional(),documentId:z45.uuid().optional()}),entryIdsSchema=z45.array(z45.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z45.object({sql:z45.string().min(1)}),BulkCreateEntriesRequestSchema=z45.object({entries:z45.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z45.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z45.object({updates:z45.array(z45.object({id:z45.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,locale:z45.string().min(1).optional()}),z45.object({where:EntryWhereSchema,locale:z45.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z45.object({data:z45.array(z45.record(z45.string(),z45.unknown())),meta:z45.object({rowCount:z45.number().int().nonnegative(),truncated:z45.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({created:z45.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({updated:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({deleted:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z46}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z46.object({index:z46.number().int().nonnegative(),contentType:z46.string(),field:z46.string(),value:z46.string(),against:z46.enum(["stored","batch"]),ownerDocumentId:z46.uuid().optional(),ownerIndex:z46.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z46.object({code:z46.literal("unique_conflict"),message:z46.string(),conflicts:z46.array(UniqueConflictSchema),truncated:z46.boolean().optional()})}});import{z as z47}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=z47.object({kind:z47.literal("unique_conflict"),contentType:z47.string(),field:z47.string(),value:z47.string(),documentCount:z47.number().int().positive(),documentIds:z47.array(z47.uuid()),documentIdsTruncated:z47.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z47.object({code:z47.literal("schema_transition_rejected"),message:z47.string(),issues:z47.array(SchemaTransitionIssueSchema),truncated:z47.boolean().optional()})}});import{z as z48}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=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z48.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z48.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z48.object({field:CmsFieldNameSchema,direction:z48.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z48.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z48.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z48.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z48.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z48.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z49}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=z49.object({id:z49.string(),name:z49.string()}),AssetDTOSchema=z49.object({id:z49.string(),name:z49.string(),type:AssetTypeSchema,originalFileName:z49.string().nullable(),parentId:z49.string().nullable(),mimeType:z49.string().nullable(),fileSize:z49.number().nullable(),url:z49.string().nullable(),storageKey:z49.string().nullable(),createdAt:z49.string(),updatedAt:z49.string(),altText:z49.string().nullable().optional(),caption:z49.string().nullable().optional(),aiCaption:z49.string().nullable().optional(),aiAltText:z49.string().nullable().optional(),aiTags:z49.array(z49.string()).nullable().optional(),aiPrimaryColor:z49.string().nullable().optional(),aiProcessingStatus:z49.string().nullable().optional(),width:z49.number().nullable().optional(),height:z49.number().nullable().optional(),path:z49.array(AssetPathItemSchema).optional(),hasChildren:z49.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z49.lazy(()=>z49.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z49.array(AssetDTOSchema))}});import{z as z50}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z50.object({key:z50.string(),value:z50.string().optional(),defaultValue:z50.string(),locale:z50.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z51}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=z51.object({id:z51.string(),name:z51.string(),type:z51.enum(["file","folder"]),path:z51.string(),children:z51.lazy(()=>z51.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z51.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z51.object({path:z51.string(),exists:z51.boolean(),type:z51.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z52}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=z52.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z52.object({items:z52.array(ProjectMessagePublicDTOSchema),nextCursor:z52.string().nullable()}),ChatLiveTurnDTOSchema=z52.object({invocationId:z52.string(),step:z52.enum(["preparing","working","compacting","merging"]),startedAt:z52.string()}),ChatLiveTurnStateDTOSchema=z52.object({threadId:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z52.object({id:z52.string(),role:z52.enum(["user","assistant"]),parts:z52.array(z52.unknown()),metadata:z52.record(z52.string(),z52.unknown()).nullable(),versionId:z52.string().nullable().optional(),createdAt:z52.date().transform(value=>value.toISOString()),providerMessageId:z52.string().nullable().optional(),invocationId:z52.string().nullable().optional(),invocationStatus:z52.string().nullable().optional(),invocationTerminalReason:z52.string().nullable().optional()}),ChatAttentionDTOSchema=z52.object({type:z52.literal("merge_conflict"),merge:z52.object({mergeId:z52.string().uuid(),projectId:z52.string(),fromEnv:z52.string(),toEnv:z52.string()}),publishAfterMerge:z52.boolean()}),ChatThreadMessagesPageDTOSchema=z52.object({threadId:z52.string().nullable(),title:z52.string().nullable(),messages:z52.array(ChatThreadMessageDTOSchema),nextCursor:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z52.object({kind:z52.literal("replay"),threadId:z52.string(),userMessageId:z52.string()}),ChatQueuedOutcomeDTOSchema=z52.object({kind:z52.literal("queued"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string()}),ChatBusyOutcomeDTOSchema=z52.object({kind:z52.literal("busy"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string().optional()}),ChatRefusedOutcomeDTOSchema=z52.object({kind:z52.literal("refused"),threadId:z52.string(),userMessageId:z52.string(),refusedInvocationId:z52.string(),terminalReason:z52.string()}),ChatNonStreamingOutcomeDTOSchema=z52.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z52.object({success:z52.boolean(),deletedCount:z52.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z52.object({code:z52.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z52.string()})}});import{z as z53}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=z53.object({url:z53.string().url(),key:z53.string(),size:z53.number(),contentType:z53.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z54}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=z54.object({canAccess:z54.boolean(),permissions:z54.record(z54.string(),z54.boolean()),role:z54.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z55}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:z55.string().trim().default(""),sort:z55.enum(["recent","name","relevance"]).default("recent"),category:z55.string().optional()})}});import{z as z56}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=z56.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z56.enum(["fimo","external"]),PaymentStatusSchema=z56.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z56.object({id:z56.string().uuid(),domain:z56.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z56.boolean(),price:z56.number().int().nullable(),renewalPrice:z56.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z56.string().nullable(),failureReason:z56.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z56.object({domain:z56.string(),available:z56.boolean(),premium:z56.boolean(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),purchaseType:z56.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z56.object({domain:z56.string(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),premium:z56.boolean(),allowedYears:z56.array(z56.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z56.object({firstName:z56.string().max(100),lastName:z56.string().max(100),companyName:z56.string().max(100).optional(),address1:z56.string().max(255),address2:z56.string().max(255).optional(),city:z56.string().max(100),state:z56.string().max(100),zip:z56.string().max(20),country:z56.string().max(2),phone:z56.string().max(30),email:z56.union([z56.string().email().max(255),z56.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z56.object({firstName:z56.string().min(1).max(100),lastName:z56.string().min(1).max(100),companyName:z56.string().max(100).optional(),address1:z56.string().min(1).max(255),address2:z56.string().max(255).optional(),city:z56.string().min(1).max(100),state:z56.string().min(1).max(100),zip:z56.string().min(1).max(20),country:z56.string().min(1).max(2),phone:z56.string().min(1).max(30),email:z56.string().email().max(255)}),SearchDomainsRequestSchema=z56.object({keyword:z56.string().min(1).max(100),tldFilter:z56.array(z56.string()).optional()}),CheckAvailabilityRequestSchema=z56.object({domains:z56.array(z56.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=z56.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z56.object({domain:DomainNameSchema,years:z56.number().int().min(1).max(10).optional().default(3),autoRenew:z56.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z56.object({autoRenew:z56.boolean().optional()}),RenewDomainRequestSchema=z56.object({years:z56.number().int().min(1).max(10).optional().default(1),autoRenew:z56.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z56.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z56.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z56.object({verified:z56.boolean(),email:z56.string().nullable(),verifyBy:z56.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z57}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=z57.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=z57.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=z57.object({txtName:z57.string().nullable().optional(),txtValue:z57.string().nullable().optional(),httpUrl:z57.string().nullable().optional(),httpBody:z57.string().nullable().optional(),cname:z57.string().nullable().optional(),cnameTarget:z57.string().nullable().optional()}),SSLValidationErrorSchema=z57.object({message:z57.string()}),OwnershipVerificationSchema=z57.object({type:z57.string(),name:z57.string(),value:z57.string()}),ProjectDomainSSLDTOSchema=z57.object({status:z57.string(),method:z57.string().nullable(),type:z57.string().nullable(),validationRecords:z57.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z57.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z57.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z57.enum(["subdomain","apex"]),RedirectConfigSchema=z57.object({type:z57.literal("apex_to_www"),linkedDomainId:z57.string()}).nullable().optional(),ProjectDomainDTOSchema=z57.object({id:z57.string(),hostname:z57.string(),status:z57.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z57.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z57.string(),scdCnameTarget:z57.string().optional(),apexTargets:z57.array(z57.string()),dnsAutoConfigured:z57.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z57.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z57.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z57.object({hostname:z57.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:z57.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z57.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z57.object({success:z57.boolean(),hostname:z57.string()}))}});import{z as z58}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=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z58.object({slug:z58.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z58.object({subdomain:z58.string(),subdomainUpdatedAt:z58.coerce.date()})),SubdomainSuggestionsQuerySchema=z58.object({base:z58.string().max(100).optional(),max:z58.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z58.object({suggestions:z58.array(z58.string())}))}});import{z as z59}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=z59.object({translated:z59.number().int().nonnegative(),total:z59.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z59.object({locale:z59.string(),isDefault:z59.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z59.object({defaultLocale:z59.string(),locales:z59.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z59.object({locale:z59.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z59.object({locale:z59.string().min(1).max(40)}),ProjectLocaleMutationSchema=z59.object({locale:z59.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z59.object({locale:z59.string(),entriesDeleted:z59.number().int().nonnegative(),labelsDeleted:z59.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z60}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=z60.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z60.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=z60.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z60.number(),credits:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),confidence:z60.enum(["exact","estimated","metered"]),basis:z60.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z61}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=z61.object({options:z61.record(z61.string(),z61.unknown()),name:z61.string().optional(),parentId:z61.string().nullable().optional(),altText:z61.string().optional(),caption:z61.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z61.string().min(1).optional(),model:z61.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=z61.object({jobId:z61.string(),status:z61.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z61.string().nullable().optional(),credits:z61.number().optional(),costUsd:z61.number().optional(),billingMode:z61.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z61.object({error:z61.string(),code:z61.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:z61.array(GenerationTaskIdSchema).optional(),availableModels:z61.array(z61.string()).optional(),issues:z61.array(z61.unknown()).optional()})}});import{z as z62}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=z62.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z62.object({name:z62.string(),key:z62.string(),description:z62.string(),type:FlagTypeSchema,required:z62.boolean(),defaultValue:z62.unknown().optional(),enumValues:z62.array(z62.string()).optional(),isArray:z62.boolean()}),AssetModelPriceSchema=z62.object({unitPrice:z62.number(),unit:z62.string(),confidence:z62.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z62.object({id:z62.string(),shortName:z62.string(),provider:z62.string(),source:z62.string(),modality:z62.enum(["image","video","audio"]),tags:z62.array(z62.string()),displayName:z62.string(),description:z62.string(),flags:z62.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z62.object({model:z62.string(),costUsd:z62.number(),credits:z62.number(),billingMode:z62.enum(["fimo-credits","provider-account"]),confidence:z62.enum(["exact","estimated","metered"]),basis:z62.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z63}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=z63.object({tourId:z63.string(),version:z63.string(),status:z63.string(),completedAt:z63.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z63.array(UserTourDTOSchema))}});import{z as z64}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=z64.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z64.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z64.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z64.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z64.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z64.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z64.enum(["user","agent","system"]),SupportReportTagSchema=z64.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z64.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z64.object({organization:z64.object({id:z64.string().trim().min(1).max(255),name:z64.string().trim().max(240).optional()}),project:z64.object({id:z64.uuid(),name:z64.string().trim().max(240).optional(),createdAt:z64.coerce.date().optional()}).optional(),environment:z64.string().trim().max(255).optional(),clientVersion:z64.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z64.string().trim().max(200).optional(),limit:z64.coerce.number().int().min(1).max(100).default(50),offset:z64.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z64.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z64.uuid().nullable().optional(),note:z64.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=z64.object({message:z64.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z64.object({kind:SupportReportLinkKindSchema,label:z64.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z64.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z64.object({kind:SupportReportActorKindSchema,id:z64.string().nullable(),name:z64.string().nullable()}),SupportReportLinkDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportLinkKindSchema,label:z64.string(),url:SupportReportHttpUrlSchema,externalId:z64.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportEventKindSchema,body:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()),actor:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z64.object({id:z64.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z64.array(z64.string()),source:SupportReportSourceSchema,message:z64.string(),reporter:z64.object({id:z64.string().nullable(),name:z64.string().nullable(),email:z64.string().nullable()}),organization:z64.object({id:z64.string().nullable(),name:z64.string()}),project:z64.object({id:z64.uuid().nullable(),name:z64.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z64.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z64.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z64.string().nullable(),deliveredAt:z64.coerce.date().nullable()}).nullable(),duplicateOfReportId:z64.uuid().nullable(),resolvedAt:z64.coerce.date().nullable(),createdAt:z64.coerce.date(),updatedAt:z64.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z64.string().nullable(),clientVersion:z64.string().nullable(),links:z64.array(SupportReportLinkDTOSchema),events:z64.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z64.object({reports:z64.array(SupportReportSummaryDTOSchema),total:z64.number().int().nonnegative(),statusCounts:z64.object({new:z64.number().int().nonnegative(),in_progress:z64.number().int().nonnegative(),waiting:z64.number().int().nonnegative(),resolved:z64.number().int().nonnegative(),duplicate:z64.number().int().nonnegative(),irrelevant:z64.number().int().nonnegative(),ignored:z64.number().int().nonnegative()}),limit:z64.number().int().positive(),offset:z64.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z64.object({id:z64.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z64.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z65}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=z65.iso.datetime({offset:!0}).pipe(z65.coerce.date()),OpsRecentChatInputSchema=z65.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z65.string().trim().min(1).max(255).optional(),limit:z65.coerce.number().int().min(1).max(200).default(100),cursor:z65.string().trim().min(1).max(2e3).optional(),slim:z65.boolean().default(!0),reason:z65.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=z65.object({id:z65.string(),threadId:z65.string(),providerMessageId:z65.string().nullable(),invocationId:z65.string().nullable(),env:z65.string().nullable(),role:z65.string(),parts:z65.array(z65.record(z65.string(),z65.unknown())),metadata:z65.object({status:z65.string().optional(),traceUrl:z65.string().optional(),externalFileChanges:z65.array(z65.unknown()).optional()}),stats:z65.object({toolCount:z65.number().int().nonnegative(),failedToolCount:z65.number().int().nonnegative()}),createdAt:z65.iso.datetime({offset:!0}),project:z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),organizationId:z65.string().nullable()})}),OpsRecentChatResponseSchema=z65.object({target:z65.object({backendProfile:OpsBackendProfileSchema,projectEnv:z65.string().nullable()}),window:z65.object({from:z65.iso.datetime({offset:!0}),to:z65.iso.datetime({offset:!0})}),messages:z65.object({items:z65.array(OpsRecentChatMessageSchema),nextCursor:z65.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z66}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=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z66.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z66.literal(!1),reason:z66.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z67}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=z67.object({packageManager:z67.string().trim().min(1).max(200).nullable(),trackedLockfiles:z67.array(z67.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z67.string().trim().min(1)}),OpsProjectPackageManagerSchema=z67.object({target:z67.object({backendProfile:OpsBackendProfileSchema,projectId:z67.uuid(),projectEnv:z67.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z68}from"zod";function createAgentRunWebhookEventDataSchema(status){return z68.object({run:z68.object({id:z68.string(),agentName:z68.string(),trigger:z68.string(),status:z68.literal(status),startedAt:z68.string().nullable(),finishedAt:z68.string().nullable(),reason:z68.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=z68.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z68.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z68.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z68.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z68.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z68.union([z68.literal(0),z68.literal(5),z68.literal(30),z68.literal(60)]),EntryChangedWebhookEventDataSchema=z68.object({reason:WebhookEntryChangeReasonSchema,operationId:z68.string().optional(),batch:z68.object({index:z68.number().int().positive(),total:z68.number().int().positive()}).optional(),changes:z68.array(z68.object({action:WebhookEntryChangeActionSchema,contentType:z68.string(),id:z68.string(),documentId:z68.string(),locale:z68.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z68.object({form:z68.object({id:z68.string(),label:z68.string()}),submission:z68.object({id:z68.string(),data:z68.record(z68.string(),z68.unknown()),submittedAt:z68.string()})}),PublishStartedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("publishing"),startedAt:z68.string()})}),PublishSucceededWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("published"),url:z68.string(),publishedAt:z68.string(),firstPublish:z68.boolean()})}),PublishFailedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("failed"),reason:z68.string()})}),PublishUnpublishedWebhookEventDataSchema=z68.object({publication:z68.object({previousUrl:z68.string(),unpublishedAt:z68.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),classification:z68.string(),summary:z68.string(),reasons:z68.array(z68.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),resolution:z68.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z68.object({report:z68.object({weekStart:z68.string(),weekEnd:z68.string(),pageviews:z68.number(),visitors:z68.number(),previousPageviews:z68.number(),previousVisitors:z68.number()})}),MediaAssetWebhookEventDataSchema=z68.object({id:z68.string().nullable(),name:z68.string().nullable(),type:z68.string(),mimeType:z68.string().nullable(),fileSize:z68.number().nullable()}),MediaUploadedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["updated","moved","analysis"]),analysis:z68.object({category:z68.string(),status:z68.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("generated"),generation:z68.object({model:z68.string(),mode:z68.string()})}),MediaProcessingFailedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["analysis","generation"]),failure:z68.object({code:z68.string()})}),DomainCreatedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string()})}),LabelChangedWebhookEventDataSchema=z68.object({changes:z68.array(z68.object({action:z68.enum(["created","updated","deleted"]),key:z68.string(),locale:z68.string(),value:z68.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),isDefault:z68.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),previousCode:z68.string()})}),LocaleDeletedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),entriesDeleted:z68.number().int().nonnegative(),labelsDeleted:z68.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z68.object({environment:z68.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z68.object({environment:z68.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z68.object({merge:z68.object({id:z68.string(),from:EnvSchema,to:EnvSchema,applied:z68.array(z68.object({surface:SurfaceNameSchema,count:z68.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z68.object({environment:z68.object({name:EnvSchema}),version:z68.object({versionId:z68.uuid(),name:z68.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=z68.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z68.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z68.discriminatedUnion("source",[z68.object({source:z68.literal("literal"),value:z68.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z68.object({source:z68.literal("secret"),key:z68.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z68.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z68.object({name:z68.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z68.object({name:z68.string(),source:z68.enum(["literal","secret"]),secretKey:z68.string().nullable(),secretPrefix:z68.string().nullable(),configured:z68.literal(!0)}),WebhookFilterSchema=z68.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z68.string().min(1).max(255).optional(),agentName:z68.string().min(1).max(120).optional(),mediaType:z68.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z68.string().min(1).max(255).optional(),locale:z68.string().min(1).max(120).optional()}),JsonValueSchema=z68.lazy(()=>z68.union([z68.string(),z68.number(),z68.boolean(),z68.null(),z68.array(JsonValueSchema),z68.record(z68.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z68.url(),enabled:z68.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z68.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z68.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z68.url().optional(),enabled:z68.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z68.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z68.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z68.object({eventType:WebhookEventTypeSchema.optional(),data:z68.record(z68.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z68.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z68.uuid(),name:z68.string(),eventType:WebhookEventTypeSchema,enabled:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z68.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z68.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z68.coerce.date().nullable(),deliveryStats24h:z68.object({succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z68.uuid(),projectId:z68.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z68.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z68.number().int().positive(),test:z68.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z68.number().int().nonnegative(),responseStatus:z68.number().int().nullable(),lastErrorCode:z68.string().nullable(),lastErrorMessage:z68.string().nullable(),payloadAvailable:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z68.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z68.string().nullable(),qstashMessageId:z68.string().nullable(),deliveredAt:z68.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z68.object({items:z68.array(WebhookDeliveryDTOSchema),pagination:z68.object({page:z68.number().int().positive(),limit:z68.number().int().positive(),total:z68.number().int().nonnegative(),totalPages:z68.number().int().positive(),hasMore:z68.boolean()}),stats:z68.object({total:z68.number().int().nonnegative(),succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z68.object({id:z68.uuid(),deliveryId:z68.uuid(),attempt:z68.number().int().positive(),status:z68.enum(["delivering","succeeded","failed"]),responseStatus:z68.number().int().nullable(),durationMs:z68.number().int().nonnegative(),responseExcerpt:z68.string().nullable(),errorCode:z68.string().nullable(),errorMessage:z68.string().nullable(),createdAt:z68.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z68.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z68.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z69}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=z69.object({key:z69.literal("fimo-2"),enabled:z69.boolean(),dismissed:z69.boolean().default(!1),interacted:z69.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z70}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=z70.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z70.object({total:z70.number(),base:z70.number(),purchases:z70.number(),awards:z70.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z70.object({id:z70.string(),name:z70.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z70.object({type:z70.string(),brand:z70.string().nullable(),last4:z70.string().nullable(),expirationDate:z70.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z70.object({currency:z70.string(),nextPaymentAmount:z70.number().nullable(),nextPaymentAt:z70.string().nullable(),billingInterval:z70.string().nullable(),totalAmount:z70.number().nullable(),discountAmount:z70.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z70.object({id:z70.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z70.string().nullable(),currentPeriodEndsAt:z70.string().nullable(),renewsAt:z70.string().nullable(),cancelAt:z70.string().nullable(),renewAutomatically:z70.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z70.object({type:z70.enum(["low_balance","critical_balance","approaching_limit"]),message:z70.string(),estimatedPromptsRemaining:z70.number().nullable(),avgCostPerPrompt:z70.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z70.object({monthlyCredits:z70.number().nullable(),usedThisPeriod:z70.number(),remainingThisPeriod:z70.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z70.object({organizationId:z70.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z70.string().nullable(),tenureDays:z70.number().int().nonnegative(),capturedAt:z70.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z70.object({hasSubscription:z70.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z70.number().nullable(),alerts:z70.array(CreditAlertDTOSchema),portalUrl:z70.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z70.object({creditCount:z70.number().int().positive(),expiresAt:z70.string().datetime().nullable().optional(),message:z70.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("free"),amountCents:z70.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("purchase"),amountCents:z70.number().int().positive()}),CreditTopupRequestDTOSchema=z70.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z70.object({success:z70.boolean(),transactionId:z70.string().nullable(),newBalance:z70.number(),creditCount:z70.number(),type:z70.enum(["free","purchase"]),invoiceId:z70.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z71}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=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),periodStart:z71.string().nullable(),periodEnd:z71.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z71.array(UsageByUserForProjectDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z71.object({summary:UsageSummaryDTOSchema,byProject:z71.array(UsageByProjectDTOSchema),byUser:z71.array(UsageByUserDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z72}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=z72.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z72.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z72.object({startDate:z72.string().optional(),endDate:z72.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z72.coerce.number().int().positive().default(1),limit:z72.coerce.number().int().positive().max(100).default(20),sortBy:z72.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z72.string().optional(),activeOnly:z72.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z72.object({totalCredits:z72.number(),totalCostUsd:z72.number(),totalMessages:z72.number(),avgCostPerMessage:z72.number(),avgCreditsPerMessage:z72.number(),periodStart:z72.string(),periodEnd:z72.string(),creditsChange:z72.number().nullable(),costChange:z72.number().nullable(),messagesChange:z72.number().nullable(),unattributedCredits:z72.number(),unattributedCostUsd:z72.number(),unattributedMessages:z72.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z72.object({date:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z72.object({organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number(),projectCount:z72.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z72.object({userId:z72.string(),userName:z72.string().nullable(),userEmail:z72.string().nullable(),userImage:z72.string().nullable(),organizationId:z72.string().nullable(),organizationName:z72.string().nullable(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),projectCount:z72.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z72.object({projectId:z72.string(),projectName:z72.string(),projectDisplayName:z72.string().nullable(),organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z72.object({id:z72.string(),name:z72.string(),value:z72.number(),percentage:z72.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z72.object({day:z72.number(),hour:z72.number(),value:z72.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z72.object({summary:UsageOverviewSummaryDTOSchema,timeline:z72.array(UsageTimelinePointDTOSchema),topOrganizations:z72.array(OrganizationUsageRowDTOSchema),topUsers:z72.array(UserUsageRowDTOSchema),topProjects:z72.array(ProjectUsageRowDTOSchema),creditDistribution:z72.array(UsageDistributionItemDTOSchema),userDistribution:z72.array(UsageDistributionItemDTOSchema),heatmap:z72.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z72.object({page:z72.number(),limit:z72.number(),totalItems:z72.number(),totalPages:z72.number(),hasMore:z72.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z72.object({organizations:z72.array(OrganizationUsageRowDTOSchema),top:z72.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z72.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z72.object({users:z72.array(ExtendedUserUsageRowDTOSchema),top:z72.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z72.object({projects:z72.array(ExtendedProjectUsageRowDTOSchema),top:z72.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z72.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z72.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z72.object({credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),createdAt:z72.string(),memberCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z72.object({id:z72.string(),name:z72.string().nullable(),email:z72.string(),image:z72.string().nullable(),createdAt:z72.string(),organizationCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),displayName:z72.string().nullable(),createdAt:z72.string(),organizationId:z72.string(),organizationName:z72.string(),ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z73}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=z73.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z73.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z73.object({command:z73.string().min(1).max(1e4),cwd:z73.string().optional(),projectEnv:EnvSchema.optional(),env:z73.record(z73.string(),z73.string()).optional(),name:z73.string().optional(),waitForCompletion:z73.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z73.object({identifier:z73.string(),status:SandboxProcessStatusSchema,command:z73.string().optional(),startedAt:z73.string().optional(),exitCode:z73.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z73.object({processes:z73.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z73.object({processId:z73.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z73.object({success:z73.boolean(),message:z73.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z74}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_agent_report();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:path54,message}=issue;return`${Array.isArray(path54)&&path54.length>0?`${path54.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,path54,status,detail,code2,body){super(`API ${method} ${path54} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path54,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}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(path54,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}${path54}`,{...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",path54,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path54,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}${path54}`,{...init,headers})}async rawRequest(path54,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}${path54}`,{...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"} ${path54} 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 addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).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 connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).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,path54,opts={}){let qs=lazyFetchQs(opts.against,{path:path54});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),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).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
61
 
44
62
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
45
63
 
@@ -206,13 +224,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
206
224
  `).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
225
  `);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
226
  `).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,z80,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"),z80=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(`
227
+ `)),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,z81,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"),z81=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
228
  `);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
229
  `:""}${o}
212
230
  `,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",z80)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
231
+ ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z81)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
214
232
  ${t("cyan",d2)} `:`
215
- `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z80)} ${s}`}
233
+ `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z81)} ${s}`}
216
234
  ${$2}
217
235
  `}}}}).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
236
  `);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 +256,7 @@ ${o}
238
256
  `}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
239
257
  `)?e.split(`
240
258
  `).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",z80)} ${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)}
259
+ `):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",z81)} ${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
260
  `:""}${n}
243
261
  `;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
262
  ${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
@@ -354,7 +372,7 @@ return __eta.res;
354
372
  `)}}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(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
355
373
  `).length}function parse6(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
374
  `).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(path54){let res="";try{res=fs18.readFileSync(path54,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path54}`):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(parse6,"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=parse6,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(path54){try{return JSON.parse(readFileSync4(path54,"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,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"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 requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, 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(requiredFormEntries,"requiredFormEntries");__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 z81}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 readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}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,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"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"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React 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/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, 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 this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` 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 path54 of schemaFiles){let fileUid=basename(path54,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path54)} 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(path54,"utf-8"))}catch(error){errors.push(`${basename(path54)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path54)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path54)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path54)} 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(path54)} 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(path54)} 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:
375
+ `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"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 requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, 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(requiredFormEntries,"requiredFormEntries");__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 z82}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 readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}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,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"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"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React 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/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, 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 this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` 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 path54 of schemaFiles){let fileUid=basename(path54,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path54)} 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(path54,"utf-8"))}catch(error){errors.push(`${basename(path54)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path54)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path54)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path54)} 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(path54)} 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(path54)} 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
376
  - ${errors.join(`
359
377
  - `)}
360
378
  No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -367,7 +385,7 @@ ${imports}
367
385
  export const content = {
368
386
  ${entries2}
369
387
  } 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=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",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,MINIMUM_FRAMEWORK_COMPANION_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",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z81.object({uid:z81.string().min(1),name:z81.string().min(1).optional(),isSingleton:z81.boolean().optional(),i18n:z81.object({enabled:z81.boolean().optional()}).optional(),groups:z81.array(z81.object({id:z81.string().min(1),label:z81.string().min(1),default:z81.boolean().optional()}).strict()).optional(),fields:z81.record(z81.string(),z81.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(readProjectPackage,"readProjectPackage");__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(`
388
+ `}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=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",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,MINIMUM_FRAMEWORK_COMPANION_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",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z82.object({uid:z82.string().min(1),name:z82.string().min(1).optional(),isSingleton:z82.boolean().optional(),i18n:z82.object({enabled:z82.boolean().optional()}).optional(),groups:z82.array(z82.object({id:z82.string().min(1),label:z82.string().min(1),default:z82.boolean().optional()}).strict()).optional(),fields:z82.record(z82.string(),z82.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(readProjectPackage,"readProjectPackage");__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
389
  `)}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
390
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
373
391
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -1168,20 +1186,24 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1168
1186
  ${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(`
1169
1187
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path54=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path54,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)}
1170
1188
 
1171
- ${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 fs52 from"node:fs";import path53 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])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,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 union=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)&&union.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(union).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
1189
+ ${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 fs52 from"node:fs";import path53 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 z75}from"zod";var CapabilityTokenSchema=z75.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=z75.array(CapabilityTokenSchema);import{z as z76}from"zod";var CronTriggerSchema=z76.object({type:z76.literal("schedule"),cron:z76.string().min(1,"cron expression required"),tz:z76.string().optional()}),ManualTriggerSchema2=z76.object({type:z76.literal("manual")}),WebhookTriggerSchema2=z76.object({type:z76.literal("webhook"),path:z76.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z76.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z76.object({name:z76.string().min(1),capability_grant:z76.enum(["inherit","explicit"]).optional(),explicit_grants:z76.array(z76.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=z76.object({"sub-agents":z76.array(SubAgentRefSchema)}),RuntimeConfigSchema=z76.object({cloud:z76.boolean().optional(),dev:z76.boolean().optional(),long_running:z76.boolean().optional()}),DataSourceSchema=z76.enum(["main","prod"]),ConfigValueKeySchema=z76.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=z76.preprocess(value=>typeof value=="string"?{key:value}:value,z76.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z76.boolean().default(!0),delivery:z76.literal("process_env").default("process_env")})),IntegrationKeySchema=z76.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z76.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=z76.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z76.object({enabled:z76.boolean().default(!0),tools:z76.record(IntegrationToolKeySchema,z76.boolean()).optional()})),IntegrationPolicySchema=z76.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z76.object({version:z76.literal(1),description:z76.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z76.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z76.array(DataSourceSchema).optional(),secrets:z76.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])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,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 z77}from"zod";var SurfaceGuardPolicySchema=z77.enum(["block","warn","allow"]),ClassificationSchema=z77.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z77.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z77.object({enabled:z77.boolean(),allowed_skills:z77.array(z77.string().min(1)).default([]),allowed_classifications:z77.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z77.enum(["off","daily","weekly"]),NotificationFormatSchema=z77.object({markdown:z77.boolean().default(!0),html:z77.boolean().default(!1)}),NotificationsPolicySchema=z77.object({email_recipients:z77.array(z77.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z77.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z77.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 z78}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=z78.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z78.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 union=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)&&union.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(union).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
1172
1190
  ${line}`):next2=(content2.endsWith(`
1173
1191
  `)?content2:content2+`
1174
1192
  `)+line+`
1175
1193
  `,fs9.writeFileSync(configPath,next2)}__name(writeDescriptionToConfig,"writeDescriptionToConfig");async function createAgentCommand(name,options){try{let result=await createAgent({name,template:options.template,cwd:options.cwd,description:options.description,requireFimoProject:options.cwd===void 0});if(!result.ok){ui.error({command:"agents create",code:"AGENT_CREATE_FAILED",message:result.error??"Failed to scaffold agent."});return}let rel=path9.relative(process.cwd(),result.agentDir);ui.ok({command:"agents create",headline:`Created agent at ${rel}`,details:{agent:name,agent_dir:result.agentDir,relative_dir:rel},hint:"Next: `fimo agents validate "+name+"` then push to main to wire its triggers."})}catch(err){err instanceof InvalidAgentNameError?ui.error({command:"agents create",code:"INVALID_AGENT_NAME",message:err.message}):printBundleError("agents create",err)}}__name(createAgentCommand,"createAgentCommand");import path10 from"node:path";init_dist();init_api();init_config();async function agentIntegrationsCommand(name,opts){try{let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),bundle=await parseBundle(path10.join(resolveAgentBundlesDir(projectRoot),name)),policy=agentIntegrationPolicy(bundle.config),projectStatus=await loadProjectIntegrationStatus(opts,projectRoot),statusByKey=new Map(projectStatus.map(status=>[status.integrationKey,status])),keys=new Set([...Object.keys(policy),...projectStatus.map(status=>status.integrationKey)]);if(keys.size===0){ui.info({command:"agents integrations",message:`Agent '${name}' has no explicit integration policy and no project integrations were found.`});return}ui.table({command:"agents integrations",columns:[{key:"integration",label:"INTEGRATION"},{key:"project",label:"PROJECT"},{key:"agent",label:"AGENT"},{key:"tools",label:"TOOLS"}],rows:[...keys].sort().map(integrationKey=>{let entry=policy[integrationKey],status=statusByKey.get(integrationKey);return{integration:integrationKey,project:renderProjectStatus(status),agent:renderAgentPolicy(entry),tools:renderTools(entry)}})})}catch(err){printBundleError("agents integrations",err)}}__name(agentIntegrationsCommand,"agentIntegrationsCommand");async function loadProjectIntegrationStatus(opts,projectRoot){let projectId=opts.project??resolveFimoProject(projectRoot)?.settings.projectId;if(!projectId)return[];try{return await new FimoApiClient(loadConfig()).listProjectIntegrations(projectId)}catch{return[]}}__name(loadProjectIntegrationStatus,"loadProjectIntegrationStatus");function renderProjectStatus(status){return status?status.enabled?`enabled (${status.authModeLabel??status.authMode??"auth unknown"})`:status.installed?"disabled":"available":"unknown"}__name(renderProjectStatus,"renderProjectStatus");function renderAgentPolicy(entry){return entry&&entry.enabled?"enabled":"disabled"}__name(renderAgentPolicy,"renderAgentPolicy");function renderTools(entry){if(!entry?.enabled)return"no tools";if(entry.tools===void 0)return"all available tools";if(enabledAgentIntegrationTools(entry).length===0)return"no tools";let tools=entry?.tools??{};return Object.entries(tools).sort(([a],[b])=>a.localeCompare(b)).map(([tool,enabled])=>`${tool}:${enabled?"on":"off"}`).join(", ")}__name(renderTools,"renderTools");init_dist();async function listAgents(opts={}){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd());return(await listBundles(resolveAgentBundlesDir(projectRoot))).map(b=>({name:b.name,declared:!0,triggers:(b.config.triggers??[]).map(t2=>t2.type),capabilities:[...b.capabilities]}))}__name(listAgents,"listAgents");async function listAgentsCommand(opts={}){let agents;try{agents=await listAgents(opts)}catch(err){ui.error({command:"agents list",code:"AGENT_BUNDLE_LIST_FAILED",message:err.message});return}if(agents.length===0){ui.info({command:"agents list",message:"(no agents)",hint:"Run `fimo agents create <name>` to scaffold one."});return}ui.table({command:"agents list",columns:[{key:"name",label:"NAME"},{key:"triggers",label:"TRIGGERS"},{key:"capabilities",label:"CAPS"}],rows:agents.map(a=>({name:a.name,triggers:a.triggers.length===0?"\u2014":a.triggers.join(", "),capabilities:a.capabilities.length===0?"(read-only)":`${a.capabilities.length} caps`}))})}__name(listAgentsCommand,"listAgentsCommand");init_dist();async function agentLogsCommand(name,options){try{ui.result({command:"agents logs",data:{agent:name,session:options.session??null,streaming_available:!1,deferred_milestone:"M17"},render:__name(()=>[`Streaming logs for agent '${name}'${options.session?` \xB7 session ${options.session}`:""}\u2026`,"Log streaming endpoint not yet deployed (M17). No logs to show."].join(`
1176
- `),"render"),warnings:["Log streaming endpoint not yet deployed (M17)."]})}catch(err){printBundleError("agents logs",err)}}__name(agentLogsCommand,"agentLogsCommand");init_dist();init_api();init_config();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),api=new FimoApiClient(cfg),session;try{if(options.session)session=await api.getAgentSession(projectId,options.session);else if(session=(await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit:1}))[0],!session){ui.info({command:"agents report",message:`(no runs for '${name}'${options.env?` on env '${options.env}'`:""})`});return}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let report=session.report?.trim(),shortId2=session.id.slice(0,8);if(!report){ui.result({command:"agents report",data:{agent:name,session_id:session.id,short_id:shortId2,status:session.status,terminal_reason:session.terminalReason??null,report:null},render:__name(()=>{let lines=[];return lines.push(`! No report for '${name}' \xB7 session ${shortId2} (${session.status}).`),session.terminalReason?lines.push(` reason: ${session.terminalReason}`):session.status!=="finished"&&lines.push(" The run has not finished yet \u2014 a report is written when it completes."),lines.join(`
1177
- `)},"render")});return}ui.result({command:"agents report",data:{agent:name,session_id:session.id,status:session.status,report},render:__name(()=>`Report \xB7 ${name} \xB7 session ${session.id} \xB7 ${session.status}
1194
+ `),"render"),warnings:["Log streaming endpoint not yet deployed (M17)."]})}catch(err){printBundleError("agents logs",err)}}__name(agentLogsCommand,"agentLogsCommand");init_esm();init_dist();init_api();init_config();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),api=new FimoApiClient(cfg),session;try{if(options.session)session=await api.getAgentSession(projectId,options.session);else if(session=(await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit:1}))[0],!session){ui.info({command:"agents report",message:`(no runs for '${name}'${options.env?` on env '${options.env}'`:""})`});return}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let shortId2=session.id.slice(0,8),document=session.reportDocument??null;if(!document){ui.result({command:"agents report",data:{agent:name,session_id:session.id,short_id:shortId2,status:session.status,terminal_reason:session.terminalReason??null,report_document:null},render:__name(()=>{let lines=[];return lines.push(`! No report for '${name}' \xB7 session ${shortId2} (${session.status}).`),session.terminalReason?lines.push(` reason: ${session.terminalReason}`):session.status!=="finished"&&lines.push(" The run has not finished yet \u2014 a report is written when it completes."),lines.join(`
1195
+ `)},"render")});return}ui.result({command:"agents report",data:{agent:name,session_id:session.id,status:session.status,report_document:document},render:__name(()=>`${`Report \xB7 ${name} \xB7 session ${session.id} \xB7 ${session.status}`}
1196
+
1197
+ ${renderDocument(document,{details:options.details===!0,agentName:name,sessionId:session.id})}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(agentReportCommand,"agentReportCommand");function renderDocument(document,target){if(target.details)return flattenReportDocument(document);let brief=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)].join(`
1198
+
1199
+ `);return document.details.length===0?brief:`${brief}
1178
1200
 
1179
- ${report}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(agentReportCommand,"agentReportCommand");function readProjectId(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId,"readProjectId");init_dist();init_api();init_config();import{execFile}from"node:child_process";import path11 from"node:path";import{promisify}from"node:util";var execFileAsync=promisify(execFile);async function detectBundleDrift(projectRoot,agentName){let porcelain;try{let{stdout}=await execFileAsync("git",["status","--porcelain"],{cwd:projectRoot});porcelain=stdout}catch{return[]}if(porcelain.length===0)return[];let prefix=`${path11.relative(projectRoot,resolveAgentBundlesDir(projectRoot)).replace(/\\/g,"/")}/${agentName}/`;return porcelain.split(`
1201
+ Full report: fimo agents report ${target.agentName} --session ${target.sessionId} --details`}__name(renderDocument,"renderDocument");function readProjectId(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId,"readProjectId");init_dist();init_api();init_config();import{execFile}from"node:child_process";import path11 from"node:path";import{promisify}from"node:util";var execFileAsync=promisify(execFile);async function detectBundleDrift(projectRoot,agentName){let porcelain;try{let{stdout}=await execFileAsync("git",["status","--porcelain"],{cwd:projectRoot});porcelain=stdout}catch{return[]}if(porcelain.length===0)return[];let prefix=`${path11.relative(projectRoot,resolveAgentBundlesDir(projectRoot)).replace(/\\/g,"/")}/${agentName}/`;return porcelain.split(`
1180
1202
  `).map(line=>line.replace(/\r$/,"")).filter(line=>{if(line.length===0)return!1;let pathPart=line.slice(3),[from,to]=pathPart.split(" -> ");return(from?.startsWith(prefix)??!1)||(to?.startsWith(prefix)??!1)})}__name(detectBundleDrift,"detectBundleDrift");async function runAgent(opts){let cwd=opts.cwd??process.cwd(),fimoProject=resolveFimoProject(cwd),projectRoot=fimoProject?.projectRoot??resolveProjectRoot(cwd);if(!opts.skipDriftCheck){let driftLines=await detectBundleDrift(projectRoot,opts.name);if(driftLines.length>0)return{exitCode:1,driftLines}}let env=opts.env??"main",projectId=opts.projectId??fimoProject?.settings.projectId;if(!projectId)throw new Error("Could not determine project id. Pass --project <id>, or run from inside a linked Fimo project.");let cfg=loadConfig(),api=new FimoApiClient(cfg);try{let result=await api.runAgent(projectId,env,opts.name,{});return{exitCode:0,sessionId:result.sessionId,skipped:result.skipped}}catch(err){throw err instanceof ApiRequestError?new Error(`Failed to run '${opts.name}' (HTTP ${err.status}): ${err.detail}`):err}}__name(runAgent,"runAgent");async function runAgentCommand(name,options){try{let result=await runAgent({name,cwd:options.cwd,env:options.env,projectId:options.project,skipDriftCheck:options.skipDriftCheck});if(result.driftLines&&result.driftLines.length>0){ui.error({command:"agents run",code:"BUNDLE_DRIFT",message:`Bundle '${name}' has local changes that haven't been deployed:
1181
1203
  ${result.driftLines.map(l=>` ${l}`).join(`
1182
1204
  `)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_api();init_config();init_project();async function agentRunsCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId2(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let limit=options.limit??20,cfg=loadConfig(),api=new FimoApiClient(cfg),sessions;try{sessions=await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}if(sessions.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${options.env?` on env '${options.env}'`:""})`});return}let rows=sessions.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,env:session.env,cost:`$${session.costUsd.toFixed(4)}`}));ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"env",label:"BRANCH"},{key:"cost",label:"COST"}],rows,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="cost")return"dim"},"cellStyle")})}catch(err){printBundleError("agents runs",err)}}__name(agentRunsCommand,"agentRunsCommand");function readProjectId2(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId2,"readProjectId");function statusRole(status){switch(status){case"finished":return"success";case"errored":return"error";case"cancelled":return"warn";case"running":return"accent";default:return}}__name(statusRole,"statusRole");function formatStartedAt(startedAt){if(!startedAt)return"\u2014";let date=startedAt instanceof Date?startedAt:new Date(startedAt);return Number.isNaN(date.getTime())?"\u2014":date.toISOString().slice(0,16).replace("T"," ")}__name(formatStartedAt,"formatStartedAt");function formatDuration(startedAt,endedAt){if(!startedAt||!endedAt)return"\u2014";let start=startedAt instanceof Date?startedAt:new Date(startedAt),ms=(endedAt instanceof Date?endedAt:new Date(endedAt)).getTime()-start.getTime();if(Number.isNaN(ms)||ms<0)return"\u2014";if(ms<1e3)return`${ms}ms`;let secs=Math.floor(ms/1e3);if(secs<60)return`${secs}s`;let mins=Math.floor(secs/60),remainingSecs=secs%60;return`${mins}m${remainingSecs.toString().padStart(2,"0")}s`}__name(formatDuration,"formatDuration");init_dist();var import_yaml3=__toESM(require_dist(),1);import fs10 from"node:fs";import path12 from"node:path";var SECRET_KEY_RE=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_CONFIG_PREFIX2=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/;async function agentSecretsListCommand(name,opts){try{let config=readAgentConfig(name,opts.cwd),secrets=normalizeSecrets(config.secrets);if(secrets.length===0){ui.info({command:"agents secrets list",message:`No secrets requested by agent '${name}'.`});return}ui.table({command:"agents secrets list",columns:[{key:"key",label:"KEY"},{key:"requirement",label:"REQUIREMENT"},{key:"delivery",label:"DELIVERY"}],rows:secrets.map(secret=>({key:secret.key,requirement:secret.required===!1?"optional":"required",delivery:secret.delivery??"process_env"}))})}catch(err){printBundleError("agents secrets list",err)}}__name(agentSecretsListCommand,"agentSecretsListCommand");async function agentSecretsAddCommand(name,key,opts){try{validateSecretKey(key);let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),secrets=normalizeSecrets(config.secrets);secrets.some(secret=>secret.key===key)||(secrets.push({key,required:!opts.optional,delivery:"process_env"}),config.secrets=secrets,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config))),ui.ok({command:"agents secrets add",headline:`Agent '${name}' now requests secret ${key}`,details:{agent:name,key,optional:opts.optional===!0}})}catch(err){printBundleError("agents secrets add",err)}}__name(agentSecretsAddCommand,"agentSecretsAddCommand");async function agentSecretsRemoveCommand(name,key,opts){try{let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),after2=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after2,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config)),ui.ok({command:"agents secrets remove",headline:`Agent '${name}' no longer requests secret ${key}`,details:{agent:name,key}})}catch(err){printBundleError("agents secrets remove",err)}}__name(agentSecretsRemoveCommand,"agentSecretsRemoveCommand");function normalizeSecrets(raw){if(!Array.isArray(raw))return[];let out=[];for(let item of raw){if(typeof item=="string"){out.push({key:item,required:!0,delivery:"process_env"});continue}if(item&&typeof item=="object"&&typeof item.key=="string"){let entry=item;out.push({key:entry.key,required:typeof entry.required=="boolean"?entry.required:!0,delivery:(entry.delivery==="process_env","process_env")})}}return out}__name(normalizeSecrets,"normalizeSecrets");function validateSecretKey(key){if(!SECRET_KEY_RE.test(key))throw new Error(`Secret key '${key}' must be UPPER_SNAKE_CASE.`);if(PUBLIC_CONFIG_PREFIX2.test(key))throw new Error(`Secret key '${key}' uses a public variable prefix. Use project variables for public values.`)}__name(validateSecretKey,"validateSecretKey");function readAgentConfig(name,cwd){return readAgentConfigWithPath(name,cwd).config}__name(readAgentConfig,"readAgentConfig");function readAgentConfigWithPath(name,cwd){let projectRoot=resolveProjectRoot(cwd??process.cwd()),filePath=path12.join(resolveAgentBundlesDir(projectRoot),name,"config.yaml");if(!fs10.existsSync(filePath))throw new Error(`Agent '${name}' does not have a config.yaml at ${filePath}.`);let parsed=(0,import_yaml3.parse)(fs10.readFileSync(filePath,"utf8")),config=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{};return{filePath,config}}__name(readAgentConfigWithPath,"readAgentConfigWithPath");init_dist();init_scaffold();async function listTemplatesCommand(){let templates=listAgentTemplates();if(templates.length===0){ui.info({command:"agents list-templates",message:"No agent templates bundled with this CLI."});return}ui.result({command:"agents list-templates",data:{templates},render:__name(()=>{let lines=["Available templates:"],longest=templates.reduce((acc,t2)=>Math.max(acc,t2.name.length),0);for(let t2 of templates){let padded=t2.name.padEnd(longest);lines.push(` ${padded} ${t2.goalFirstLine??"(no GOAL.md)"}`)}return lines.push(""),lines.push(" Use `fimo agents create <name> --template <template>` to scaffold."),lines.join(`
1183
1205
  `)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_api();init_auth();init_config();init_project_context();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=resolveAgentBundlesDir(projectRoot),configPath=resolveProjectPolicyPath(projectRoot),policy=validatePolicy(configPath,projectRoot),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path13.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[],cloudNotifications=hasCloudNotificationRecipients(configPath);for(let bundle of bundleList){let report=validateOneBundle(bundle,bundleList);!cloudNotifications&&(bundle.config.triggers??[]).some(t2=>t2.type!=="manual")&&report.warnings.push({pointer:`${path13.basename(configPath)}:agents.notifications.email_recipients`,message:"Cloud triggers stay unwired until `agents.notifications.email_recipients` is non-empty (ADR-0009)."}),reports.push(report)}return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function hasCloudNotificationRecipients(policyPath){if(!fs11.existsSync(policyPath))return!1;try{return(parseFimoConfig(fs11.readFileSync(policyPath,"utf8"),{path:path13.basename(policyPath)}).agents?.notifications?.email_recipients??[]).length>0}catch{return!1}}__name(hasCloudNotificationRecipients,"hasCloudNotificationRecipients");function validatePolicy(policyPath,projectRoot){if(!fs11.existsSync(policyPath))return null;try{let text3=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{path:path13.relative(projectRoot,policyPath)}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:path13.relative(projectRoot,policyPath),message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path13.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.nonDeclarable){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agent-bundle directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let api=new FimoApiClient(loadConfig()),context=await getProjectContext({cwd:projectRoot}),environment=await api.resolveProjectEnvironmentKey(projectId,context.env),agentsDir=resolveAgentBundlesDir(projectRoot),bundles=await listBundles(agentsDir),issues=[],configPath=__name(agentName=>path13.relative(projectRoot,path13.join(agentsDir,agentName,"config.yaml")).replaceAll("\\","/"),"configPath"),integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry),allTools:entry.tools===void 0,toolsConfigured:entry.tools!==void 0})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=configPath(agent.name),status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.toolsConfigured&&integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but its tools map allows none. Remove the tools map to allow all available tools, or set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await api.getProjectIntegrationInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key)),effectiveTools=integration.allTools?[...knownTools]:integration.tools;for(let tool of effectiveTools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await api.listProjectSecretEntries(projectId,{kind:"secret",environment})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:configPath(entry.name),message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or Fimo project config found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 Fimo config policy ok");else{lines.push(" \u2717 Fimo config");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
1184
- `)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs12 from"node:fs";import path14 from"node:path";import{z as z78}from"zod";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z78.object({sourceId:z78.string().min(1),path:z78.string().min(1),name:z78.string().min(1).optional(),parentId:z78.string().min(1).optional(),folderPath:z78.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z78.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index2,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index2,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
1206
+ `)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report brief; latest run unless --session is given").option("--session <id>","Target a specific session id").option("--details","Print the report's full evidence section as well as its brief").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs12 from"node:fs";import path14 from"node:path";import{z as z79}from"zod";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z79.object({sourceId:z79.string().min(1),path:z79.string().min(1),name:z79.string().min(1).optional(),parentId:z79.string().min(1).optional(),folderPath:z79.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z79.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index2,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index2,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
1185
1207
  ${issues.join(`
1186
1208
  `)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index2=nextIndex;nextIndex+=1,results[index2]=await run(items[index2])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}));ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item));return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}}),failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,env:ctx.env});let result=await api.readAsset(ctx.projectId,id,{cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_ENV2="main";var ENV_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidEnv2(env){return typeof env!="string"||env.length===0||env.length>255||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX2.test(env)}__name(isValidEnv2,"isValidEnv");function fnv1a82(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")}__name(fnv1a82,"fnv1a8");function envResourceKey2(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(env);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.env]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2),env=branch??DEFAULT_ENV2,tenantApiUrl=buildTenantApiUrl2(link.projectId,env,link.tenantApiBaseUrl);return{env,tenantApiUrl,source:branch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,env}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidEnv2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_api();init_config();init_git();init_project_context();init_esm();function buildPreviewUrl(webUrl,projectId,env){return new URL(`/preview/${encodeURIComponent(projectId)}/${encodeEnvPathSegment(env)}`,webUrl).toString()}__name(buildPreviewUrl,"buildPreviewUrl");function buildProjectPreviewUrl(webUrl,projectId,env){return new URL(`/app/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(env)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose,includeAgentEnvs:opts.all});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014"})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let project=await api.getProject(ctx.projectId),created=await api.createEnv(ctx.projectId,{env:name,parentEnv}),previewUrl=project.previewEnabled===!1?null:buildPreviewUrl(loadConfig().webUrl,ctx.projectId,created.env),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,created.env),headline=`Created Branch '${created.env}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:previewUrl,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentEnv,previewUrl,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentEnv}`];return result.previewUrl&&lines.push(` Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
1187
1209
  `)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active env (\`${ctx.env}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.env}\`)`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
@@ -1268,7 +1290,7 @@ ${failure.stderr}`});break}}__name(emitPushFailure,"emitPushFailure");function e
1268
1290
  Purchase: ${formatPrice(pricing.price)} \xD7 ${effectiveYears} year${effectiveYears===1?"":"s"} = ${formatPrice(totalCents)}
1269
1291
  Renewal: ${formatPrice(pricing.renewalPrice)}/year${autoRenew===!1?" (auto-renew off)":" (auto-renews)"}`);let confirmed=await ot2({message:`Create a checkout invoice for ${domain}?`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains buy",message:"Cancelled."});return}}let purchased;try{purchased=await api.purchaseRegisteredDomain(organizationId,{domain,years:effectiveYears,autoRenew})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains buy",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError){if(err.status===403){ui.error({command:"domains buy",code:"PURCHASE_FORBIDDEN",message:"You don't have permission to buy domains for this organization.",hint:"Org admins only."});return}ui.error({command:"domains buy",code:"PURCHASE_FAILED",message:`Purchase failed: ${err.detail}`});return}throw err}ui.result({command:"domains buy",data:purchased,render:__name(()=>{let lines=[];return lines.push(""),lines.push(`Invoice created for ${purchased.domain} (${formatPrice(purchased.price)}).`),lines.push("Pay to complete registration:"),lines.push(""),lines.push(` ${purchased.checkoutUrl??"(checkout URL pending \u2014 refresh in a moment)"}`),lines.push(""),lines.push("No money moves until you complete payment in the browser."),lines.push(`Once paid, ${purchased.domain} registers automatically and shows up in \`fimo domains owned\`.`),lines.join(`
1270
1292
  `)},"render")}),options.open&&purchased.checkoutUrl&&await open_default(purchased.checkoutUrl).catch(()=>{});let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&await pollPurchasePayment(api,organizationId,purchased,timeoutMs)}__name(domainsBuyCommand,"domainsBuyCommand");async function pollPurchasePayment(api,organizationId,initial,timeoutMs){let start=Date.now(),sp=spinner(`Waiting for payment (status: ${initial.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="owned")return sp.succeed(`Registered \u2014 ${current.domain} is now yours.`),current;if(current.status==="registration_failed"||current.status==="payment_failed")return sp.fail(`${current.status==="payment_failed"?"Payment":"Registration"} failed for ${current.domain}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await api.refreshRegisteredDomainPayment(organizationId,current.id),sp.update(`Waiting (status: ${current.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current}}return sp.fail("Timed out. Run `fimo domains owned` later to check status."),current}__name(pollPurchasePayment,"pollPurchasePayment");async function domainsOwnedCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),organizationId=resolveOrgId(options),domains2;try{domains2=await api.listOwnedRegisteredDomains(organizationId)}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains owned",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError&&err.status===403){ui.error({command:"domains owned",code:"OWNED_DOMAINS_FORBIDDEN",message:"You don't have access to this organization's domains.",hint:"Org admins only."});return}throw err}let statusFilter=options.status?.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0),limit=options.limit?parseInt(options.limit,10):null,filtered=domains2;if(statusFilter&&statusFilter.length>0&&(filtered=filtered.filter(d3=>statusFilter.includes(d3.status.toLowerCase()))),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains owned",message:"No domains registered through Fimo yet.",hint:"Try `fimo domains search <keyword>`."});return}ui.result({command:"domains owned",data:{domains:filtered,total:filtered.length},render:__name(()=>{let nameW=Math.max(8,...filtered.map(d3=>d3.domain.length)),statusW=Math.max(8,...filtered.map(d3=>d3.status.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("STATUS",statusW)} EXPIRES`);for(let d3 of filtered){let expires=d3.expirationDate?new Date(d3.expirationDate).toISOString().slice(0,10):"\u2014";lines.push(` ${pad(d3.domain,nameW)} ${pad(d3.status,statusW)} ${expires}`)}return lines.join(`
1271
- `)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_api();init_project_context();init_project();import fs33 from"node:fs";import path32 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path32.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs33.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}},DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index2){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index2+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index2+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index2){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index2+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(api,projectId,typeName,field,inputs){let byLocale=new Map;for(let[index2,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index2)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await api.listEntries(projectId,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(api,projectId,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await api.bulkCreateEntries(projectId,typeName,pending);created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(api,projectId,typeName,field,pending),absent=pending.filter((input,index2)=>{let key=identityKey(identityValue(input,field,index2),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(api,projectId,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(api,projectId,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index2,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index2),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await api.bulkUpdateEntries(projectId,typeName,{updates});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(api,projectId,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(api,projectId,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env});let params={};options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let result=await api.listEntries(ctx.projectId,typeName,Object.keys(params).length>0?params:void 0);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesListCommand,"entriesListCommand");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,env:ctx.env});let data2=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),result=await api.createEntry(ctx.projectId,typeName,data2);ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let data2=parseJsonObject(options.body),result=await api.updateEntry(ctx.projectId,typeName,id,options.locale,data2);ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,env:ctx.env});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await api.queryEntries(ctx.projectId,sql);ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_create",{projectId:ctx.projectId,env:ctx.env}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)));if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await api.bulkCreateEntries(ctx.projectId,typeName,entries2);ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index2)=>parseEntryInput(entry,index2)):[],identityCounts=new Map;if(options.upsertBy)for(let[index2,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index2),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,parseChunkSize(options.chunkSize)),receipts=[],data2=[];for(let[index2,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(api,ctx.projectId,typeName,options.upsertBy,chunk,index2+1,identityCounts));continue}let result2=await api.bulkCreateEntries(ctx.projectId,typeName,chunk);data2.push(...result2.data),receipts.push({chunk:index2+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data:data2,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env});let usesBatchInput=!!(options.file||options.stdin),payload;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");payload={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body:parseBulkJsonObject(options.body)}}let result=await api.bulkUpdateEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,env:ctx.env}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},...options.locale?{locale:options.locale}:{}},result=await api.bulkDeleteEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_api();init_config();init_auth_errors();init_project();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group project Branches into deployment Environments").addHelpText("after",`
1293
+ `)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_api();init_project_context();init_project();import fs33 from"node:fs";import path32 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path32.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs33.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}},DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index2){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index2+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index2+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index2){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index2+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(api,projectId,typeName,field,inputs){let byLocale=new Map;for(let[index2,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index2)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await api.listEntries(projectId,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(api,projectId,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await api.bulkCreateEntries(projectId,typeName,pending);created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(api,projectId,typeName,field,pending),absent=pending.filter((input,index2)=>{let key=identityKey(identityValue(input,field,index2),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(api,projectId,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(api,projectId,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index2,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index2),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await api.bulkUpdateEntries(projectId,typeName,{updates});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(api,projectId,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(api,projectId,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env});let params={};options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let result=await api.listEntries(ctx.projectId,typeName,Object.keys(params).length>0?params:void 0);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesListCommand,"entriesListCommand");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,env:ctx.env});let data2=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),result=await api.createEntry(ctx.projectId,typeName,data2);ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let data2=parseJsonObject(options.body),result=await api.updateEntry(ctx.projectId,typeName,id,options.locale,data2);ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,env:ctx.env});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await api.queryEntries(ctx.projectId,sql);ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_create",{projectId:ctx.projectId,env:ctx.env}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),chunkSize=parseChunkSize(options.chunkSize);if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await api.bulkCreateEntries(ctx.projectId,typeName,entries2);ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index2)=>parseEntryInput(entry,index2)):[],identityCounts=new Map;if(options.upsertBy)for(let[index2,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index2),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,chunkSize),receipts=[],data2=[];for(let[index2,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(api,ctx.projectId,typeName,options.upsertBy,chunk,index2+1,identityCounts));continue}let result2=await api.bulkCreateEntries(ctx.projectId,typeName,chunk);data2.push(...result2.data),receipts.push({chunk:index2+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data:data2,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env});let usesBatchInput=!!(options.file||options.stdin),payload;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");payload={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body:parseBulkJsonObject(options.body)}}let result=await api.bulkUpdateEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,env:ctx.env}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},...options.locale?{locale:options.locale}:{}},result=await api.bulkDeleteEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_api();init_config();init_auth_errors();init_project();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group project Branches into deployment Environments").addHelpText("after",`
1272
1294
  Environments group Branches. Production is the deployed snapshot published from main.
1273
1295
  Automatic previews receives every unclaimed Branch, including main.
1274
1296