fimo 2.15.0-staging.3 → 2.15.0-staging.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -3,7 +3,7 @@ import { createRequire as __fimoCreateRequire } from 'node:module';
3
3
  const require = __fimoCreateRequire(import.meta.url);
4
4
  var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a2,b)=>(typeof require<"u"?require:a2)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);import{z}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[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(data,matchingSchema):data}if(schema instanceof z.ZodObject){if(typeof data!="object")return data;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data,key)){let fieldSchema=shape[key],fieldValue2=data[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data))key in shape||(result[key]=value);return result}return data}function createObjectDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,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(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,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","PAYG","Starter","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_UPLOAD_FILE_SIZE_BYTES,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_UPLOAD_FILE_SIZE_BYTES=50*MB,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 isProcessControlEnvKey(key){return PROCESS_CONTROL_ENV_KEYS.has(key)||PROCESS_CONTROL_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h2=2166136261;for(let i2=0;i2<s.length;i2++)h2^=s.charCodeAt(i2),h2=Math.imul(h2,16777619);return(h2>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId2,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId2}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_ANALYTICS_ENV_KEYS,FIMO_SITE_URL_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,PROCESS_CONTROL_ENV_KEYS,PROCESS_CONTROL_ENV_PREFIXES,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,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_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_SITE_URL_ENV_KEYS=["FIMO_SITE_URL","VITE_FIMO_SITE_URL","NEXT_PUBLIC_FIMO_SITE_URL","PUBLIC_FIMO_SITE_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_PREVIEW_PARENT_ORIGIN","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,...FIMO_SITE_URL_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],PROCESS_CONTROL_ENV_KEYS=new Set(["PATH","HOME","SHELL","BASH_ENV","ENV","PROMPT_COMMAND","USER","TMPDIR","HOST","HOSTNAME","PORT","NODE_ENV","NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_TLS_REJECT_UNAUTHORIZED","SSL_CERT_FILE","CURL_CA_BUNDLE","PYTHONPATH","LD_PRELOAD","LD_LIBRARY_PATH","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","FIMO_VALIDATION_BUILD","FIMO_SKIP_VERSION_CHECK","FIMO_EDITING_METADATA","FIMO_AGENT_TMP_DIR"]),PROCESS_CONTROL_ENV_PREFIXES=["GIT_","NPM_CONFIG_","PNPM_","YARN_","COREPACK_","BUN_","DENO_"];__name(isProcessControlEnvKey,"isProcessControlEnvKey");BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});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:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z9}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=z9.preprocess(referenceValuePreprocess,z9.object({documentId:z9.uuid()})),ReferenceInputValueSchema=z9.preprocess(referenceValuePreprocess,z9.union([z9.object({documentId:z9.uuid()}),z9.object({slug:z9.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=z9.preprocess(polymorphicReferenceValuePreprocess,z9.object({contentType:z9.string().min(1),documentId:z9.uuid()})),PolymorphicReferenceInputValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.union([z9.object({contentType:z9.string().min(1),documentId:z9.uuid()}),z9.object({contentType:z9.string().min(1),slug:z9.string().min(1)})]))}});import{z as z10}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path52){let conditionPath=[...path52,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path52)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z10.union([z10.object({field:z10.string().min(1),equals:z10.union([z10.string(),z10.number(),z10.boolean()])}).strict(),z10.object({field:z10.string().min(1),in:z10.array(z10.union([z10.string(),z10.number(),z10.boolean()])).min(1)}).strict()]),commonFieldShape={label:z10.string().min(1).optional(),description:z10.string().optional(),group:z10.union([z10.string().min(1),z10.array(z10.string().min(1)).min(1)]).optional(),editable:z10.boolean().optional(),required:z10.boolean().optional(),default:z10.unknown().optional(),showIf:z10.union([showIfClauseSchema,z10.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z10.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=z10.object({...commonFieldShape,type:z10.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z10.number().optional(),max:z10.number().optional(),minLength:z10.number().int().nonnegative().optional(),maxLength:z10.number().int().nonnegative().optional(),regex:z10.string().optional(),multiple:z10.boolean().optional(),allowedMimeTypes:z10.array(z10.string()).optional(),options:z10.array(z10.string().min(1)).min(1).optional(),unique:z10.boolean().optional(),i18n:z10.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=z10.object({...commonFieldShape,type:z10.literal("reference"),target:z10.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z10.array(z10.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z10.boolean().optional(),i18n:z10.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=z10.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z10.record(z10.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=z10.object({uid:z10.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z10.string().min(1),description:z10.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z10.object({fields:blockFieldsSchema}).strict(),blocksSchema=z10.object({oneOf:z10.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z10.object({...commonFieldShape,type:z10.literal("blocks"),min:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z10.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=z10.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z11}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,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","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","site_onboarding_refusal_lift","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_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_trace_budget_wrap_up_read","ops_context_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_memory_health_read","ops_routine_metrics_read","ops_agent_proposals_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_move_to_free","ops_billing_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_agent_runtime_attach","ops_billing_database_compute_attach","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_billing_legacy_premium_comp","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_signal_case_decision","ops_watch_save","ops_watch_report","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_sandbox_read","ops_sandbox_logs_read","ops_sandbox_exec","ops_sandbox_operation","ops_agent_branch_discard","admin_resource_read","merge_force","ops_operation_plan","project_sync","project_thumbnail_regenerate","project_delete","project_import","organization_delete","credits_topup","credits_burn","user_session_revoke","user_ban","user_unban","user_impersonate","user_role_change","user_sessions_revoke","user_delete","platform_pool_change","platform_maintenance_change","platform_sync","platform_tenant_schema_sync","integration_event_replay","ops_billing_dispatch_retry","ops_billing_plan_projection_reconcile","ops_agent_chat_create","ops_pylon_issue_change","ops_pylon_note_create","ops_pylon_reply_preview","ops_pylon_reply_approve","ops_pylon_reply_send","admin_playground_run","ops_find","ops_project_health_read","ops_migrations_read","ops_operational_read","ops_billing_report_read","ops_users_read","ops_organizations_read","ops_merges_read","ops_platform_read","ops_watch_read","ops_notification_read","ops_audit_read"],AuditActionSchema=z11.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z11.enum(AUDIT_OUTCOMES)}});import{z as z12}from"zod";var ORGANIZATION_FEATURES,AGENT_PLANS,AgentPlanSchema,OrganizationFeatureSchema,OrganizationFeaturesDTOSchema,OrganizationFeaturesDTO,OrganizationFeatureStateDTOSchema,OrganizationFeatureSetSchema,init_organization_features_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization-features.dto.js"(){"use strict";init_create_dto();ORGANIZATION_FEATURES=["routine_planner","pro_agents","code_sync"],AGENT_PLANS=["free","starter","pro"],AgentPlanSchema=z12.enum(AGENT_PLANS),OrganizationFeatureSchema=z12.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z12.object({features:z12.record(OrganizationFeatureSchema,z12.boolean()),lockedByPlan:z12.array(OrganizationFeatureSchema),agentPlan:AgentPlanSchema}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z12.object({feature:OrganizationFeatureSchema,enabled:z12.boolean(),default:z12.boolean(),lockedByPlan:z12.boolean(),override:z12.boolean().nullable(),reason:z12.string().nullable(),updatedBy:z12.string().nullable(),updatedAt:z12.string().datetime().nullable()}),OrganizationFeatureSetSchema=z12.object({state:z12.enum(["on","off","default"]),reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1)})}});import{z as z13}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_SUPPORT_PRESET,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,OpsAgentTraceCostliestInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OPS_MEMORY_HEALTH_MAX_WINDOW_MS,OpsMemoryHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OPS_ROUTINE_METRICS_MAX_WINDOW_MS,OpsRoutineMetricsGroupBySchema,OpsRoutineMetricsSortBySchema,OpsRoutineMetricsInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OpsBillingAgentRuntimeAttachInputSchema,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,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_organization_features_dto();init_env();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:project:agents:write","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:organization:features: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","ops:users:read","ops:users:write","ops:organizations:read","ops:organizations:write","ops:merges:read","ops:merges:write","ops:platform:read","ops:platform:write","ops:project:admin","ops:credits:write"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_SUPPORT_PRESET=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:users:read","ops:organizations:read","ops:merges:read","ops:platform:read","ops:billing:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:audit:read","ops:notification:preview"],OPS_PERMISSION_PRESETS={support:OPS_SUPPORT_PRESET,engineer:[...OPS_SUPPORT_PRESET,"ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:customers:write","ops:billing:write","ops:organization:features:write","ops:known-issues:write","ops:validations:write","ops:merges:write","ops:platform:write","ops:users:write"],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"}),OpsAgentTraceCostliestInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date(),limit:z13.coerce.number().int().min(1).max(50).default(25),reason:z13.string().trim().min(1).max(1e3)}).superRefine((input,ctx)=>{input.until<input.since&&ctx.addIssue({code:"custom",path:["until"],message:"until must be at or after since"}),input.until.getTime()-input.since.getTime()>744*60*60*1e3&&ctx.addIssue({code:"custom",path:["since"],message:"window must not exceed 31 days"})}),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","branch","project","day"]),OpsAgentHealthInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),branch:BranchSchema.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"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z13.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z13.strictObject({organizationId:z13.string().trim().min(1).max(255).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),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"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),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"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),OPS_MEMORY_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsMemoryHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(200),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"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_MEMORY_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"memory health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z13.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,limit:z13.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,sample:z13.coerce.number().int().min(1).max(25).default(10)})),OPS_ROUTINE_METRICS_MAX_WINDOW_MS=2160*60*60*1e3,OpsRoutineMetricsGroupBySchema=z13.enum(["routine","plan","day","project"]),OpsRoutineMetricsSortBySchema=z13.enum(["total","jev","runs"]),OpsRoutineMetricsInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),plan:AgentPlanSchema.optional(),routine:z13.string().trim().min(1).max(64).optional(),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total"),burstMinutes:z13.coerce.number().int().min(1).max(120).default(10),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_ROUTINE_METRICS_MAX_WINDOW_MS,{path:["since"],message:"routine metrics windows cannot exceed 90 days"}),OpsChatHistoryJudgeCalibrationInputSchema=z13.strictObject({reason:z13.string().trim().min(1).max(1e3)}),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().default(()=>new Date),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),correlateInvocations:z13.boolean().default(!1),correlationLimit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),organizationIds:z13.array(z13.string().min(1)).min(1).max(100).optional(),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50)}),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}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z13.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z13.strictObject({projectId:z13.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z13.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z13.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z13.strictObject({completeAggregate:z13.boolean(),truncated:z13.boolean().nullable(),sampled:z13.boolean().nullable(),pagination:z13.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z13.literal(!1),providerAsOf:z13.null(),projectFilter:z13.literal("exact properties.projectId equality"),environmentFilterSupported:z13.literal(!1),excludesMissingProjectId:z13.literal(!0),transport:z13.literal("server"),consentCoverage:z13.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z13.literal(!1)}),OpsPosthogCountsSchema=z13.array(z13.strictObject({event:z13.enum(OPS_POSTHOG_EVENTS),captureCount:z13.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i2)=>entry.event===OPS_POSTHOG_EVENTS[i2])),OpsPosthogMilestonesResponseSchema=z13.strictObject({schemaVersion:z13.literal(1),questionId:z13.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z13.uuid().nullable(),projectEnvironment:z13.literal("mixed_or_unrecorded"),window:z13.strictObject({from:z13.iso.datetime(),to:z13.iso.datetime(),bounds:z13.literal("[from,to)")}).nullable(),source:z13.literal("posthog"),sourceStatus:z13.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z13.iso.datetime(),auditId:z13.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3),limit:z13.number().int().min(1).max(100).default(25),checkProvider:z13.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z13.object({branch:z13.string().trim().min(1).max(255),canaryPath:z13.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z13.iso.datetime({offset:!0}),until:z13.iso.datetime({offset:!0}),reason:z13.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z14}from"zod";function resolveOpsTime(value,now=new Date){let relative3=RELATIVE_WINDOW.exec(value.trim());if(relative3){let amount=Number(relative3[1]),unit=relative3[2];return new Date(now.getTime()-amount*UNIT_MS[unit]).toISOString()}return new Date(value).toISOString()}function opsHoursSince(value,now=new Date){let start=Date.parse(resolveOpsTime(value,now));return Math.max(1,Math.ceil((now.getTime()-start)/UNIT_MS.h))}var RELATIVE_WINDOW,time,opsArgs,OPS_STANDARD_ARG_KEYS,UNIT_MS,init_args=__esm({"../../packages/api-contracts/dist/esm/ops/args.js"(){"use strict";RELATIVE_WINDOW=/^(\d+)(m|h|d|w)$/,time=z14.string().trim().min(1).max(64).refine(value=>RELATIVE_WINDOW.test(value)||!Number.isNaN(Date.parse(value)),{message:"Expected an ISO timestamp or a relative window such as 30m, 24h, 7d or 2w"}),opsArgs={project:z14.uuid().describe("Fimo project id"),org:z14.string().trim().min(1).max(255).describe("Organization id"),user:z14.string().trim().min(1).max(255).describe("User id"),env:z14.string().trim().min(1).max(255).describe("Project environment (branch), e.g. main or prod"),since:time.describe("Start of the window: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:time.describe("End of the window: ISO timestamp or relative (defaults to now)"),limit:z14.coerce.number().int().min(1).max(1e3).describe("Maximum results"),cursor:z14.string().trim().min(1).max(2e3).describe("Continue from a previous page"),query:z14.string().trim().min(1).max(200).describe("Free-text search"),reason:z14.string().trim().min(1).max(1e3).describe("Why this is being read or changed; stored in the audit log"),output:z14.string().trim().min(1).max(4096).describe("Write the result to this local file")},OPS_STANDARD_ARG_KEYS=Object.keys(opsArgs),UNIT_MS={m:6e4,h:36e5,d:864e5,w:6048e5};__name(resolveOpsTime,"resolveOpsTime");__name(opsHoursSince,"opsHoursSince")}});import{z as z15}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,ConflictTargetCommitSchema,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=z15.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z15.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z15.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z15.object({verb:SurfaceDeltaVerbSchema,key:z15.string(),detail:z15.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z15.record(z15.string(),z15.unknown()).optional()}),PerSurfaceDeltaSchema=z15.object({surface:SurfaceNameSchema,status:z15.enum(["ok","timed_out","failed","unchanged"]),durationMs:z15.number().int().nonnegative().optional(),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative(),items:z15.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z15.boolean().optional(),error:z15.string().optional()}),CrossSurfaceFindingSchema=z15.object({id:z15.string(),kind:z15.string(),description:z15.string(),severity:z15.enum(["warning","error"]),source:z15.object({surface:SurfaceNameSchema,key:z15.string()}),target:z15.object({surface:SurfaceNameSchema,key:z15.string()}),actions:z15.array(z15.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z15.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z15.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z15.coerce.date(),surfaces:z15.array(PerSurfaceDeltaSchema),agents:z15.array(z15.object({id:z15.string(),name:z15.string(),status:z15.enum(["active","paused","failed"]),lastRunAt:z15.coerce.date().nullable()})).optional(),crossSurface:z15.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z15.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(PerSurfaceDeltaSchema),crossSurface:z15.array(CrossSurfaceFindingSchema).optional(),fingerprint:z15.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z15.object({path:z15.string(),state:z15.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z15.string(),additions:z15.number().int().nonnegative(),deletions:z15.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z15.object({oid:z15.string().optional(),content:z15.string().optional(),truncated:z15.boolean(),binary:z15.boolean()}),CodeConflictDetailSchema=z15.object({path:z15.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z15.string(),targetTipSha:z15.string(),mergeBaseSha:z15.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z15.object({id:z15.string(),slug:z15.string(),contentType:z15.string(),data:z15.record(z15.string(),z15.unknown()),updatedAt:z15.coerce.date()}),ContentRowDiffSchema=z15.object({collection:z15.string(),rowId:z15.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z15.object({name:z15.string(),label:z15.string(),isSingleton:z15.boolean(),description:z15.string().nullable().default(null),fields:z15.record(z15.string(),z15.unknown())}),SchemaTypeDiffSchema=z15.object({typeName:z15.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z15.object({id:z15.string(),name:z15.string(),type:z15.enum(["file","folder"]),mimeType:z15.string().nullable(),storageKey:z15.string().nullable(),url:z15.string().nullable(),fileSize:z15.number().nullable(),width:z15.number().nullable(),height:z15.number().nullable(),altText:z15.string().nullable(),caption:z15.string().nullable(),createdAt:z15.coerce.date(),updatedAt:z15.coerce.date()}),AssetDiffSchema=z15.object({assetId:z15.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z15.object({locale:z15.string(),key:z15.string(),parent:z15.string().nullable(),child:z15.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z15.object({formName:z15.string(),label:z15.string().nullable(),schemaFingerprint:z15.string(),fields:z15.record(z15.string(),z15.unknown()),settings:z15.record(z15.string(),z15.unknown()).optional()}),FormSchemaDiffSchema=z15.object({formName:z15.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=z15.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z15.object({sha:z15.string(),subject:z15.string(),body:z15.string().optional(),author:z15.string(),date:z15.string()}),ConflictSchema=z15.object({surface:SurfaceNameSchema,key:z15.string(),kind:ConflictKindSchema.optional(),description:z15.string(),parentValue:z15.unknown().optional(),childValue:z15.unknown().optional(),conflictingFields:z15.array(z15.string()).optional(),code:z15.object({path:z15.string(),unresolvable:z15.boolean().optional(),reason:z15.string().optional(),targetCommits:z15.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z15.object({field:z15.string(),choice:z15.enum(["parent","child","pick","ai-pick"]),pickedValue:z15.unknown().optional(),aiSessionId:z15.string().optional()}),ConflictResolutionSchema=z15.object({surface:SurfaceNameSchema,key:z15.string(),choice:z15.enum(["parent","child","pick"]),pickedValue:z15.unknown().optional(),fieldPicks:z15.array(FieldPickSchema).optional()}),MergeResultSchema=z15.object({ok:z15.boolean(),mergeId:z15.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z15.array(z15.object({surface:SurfaceNameSchema,count:z15.number().int().nonnegative()})),conflicts:z15.array(ConflictSchema).optional(),summary:z15.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z15.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z15.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z15.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z15.boolean().optional()}),ResolvedStrategySchema=z15.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z15.boolean()}),MergeRequestSchema=z15.object({from:BranchSchema,allowDirectMerge:z15.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z15.object({mergeId:z15.string().uuid(),streamUrl:z15.string(),strategy:ResolvedStrategySchema,acceptedAt:z15.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z15.object({mergeId:z15.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z15.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z15.array(ConflictSchema),draftResolutions:z15.array(ConflictResolutionSchema),lastEditedBy:z15.string().nullable(),lastEditedAt:z15.coerce.date().nullable(),initiator:z15.object({userId:z15.string().nullable(),role:z15.string().nullable(),agentName:z15.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z15.object({resolutions:z15.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z15.object({mergeId:z15.string().uuid(),draftResolutions:z15.array(ConflictResolutionSchema),lastEditedAt:z15.coerce.date(),lastEditedBy:z15.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z15.object({mergeId:z15.string().uuid(),resolutions:z15.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z15.object({mergeId:z15.string().uuid()}),PublishReleaseRequestSchema=z15.object({version:z15.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z15.string().max(2e4).optional()}),PublishReleaseResultSchema=z15.object({releaseTag:z15.string(),sha:z15.string(),publishedAt:z15.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z16}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,ProposalTextSchema,ProposalEntryInputSchema,ProposalShowItemSchema,ContentProposalInputSchema,SessionProposalInputSchema,ProposeInputSchema,StoredProposalEntrySchema,ProposalMetaSchema,ProposalListInputSchema,ProposalDecideInputSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,ProposedSessionSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentBranchClassificationSchema=z16.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z16.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z16.object({sessionId:z16.uuid(),branch:z16.string().min(1),targetBranch:z16.string().min(1),revision:z16.string().min(1),fingerprint:z16.string().min(1),source:z16.enum(["studio","slack","mcp"]),threadId:z16.uuid().nullable(),invocationId:z16.uuid().nullable(),conversationBranch:z16.string().nullable(),capturedAt:z16.string(),surfaces:z16.array(PerSurfaceDeltaSchema).optional(),counts:z16.record(z16.string(),z16.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z16.strictObject({sessionId:z16.uuid(),summary:z16.string().trim().min(1).max(240),targetBranch:z16.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z16.object({requested:z16.literal(!0),alreadyRequested:z16.boolean(),reviewId:z16.uuid(),reviewUrl:z16.url(),status:z16.literal("pending"),sessionId:z16.uuid(),branch:z16.string(),targetBranch:z16.string(),revision:z16.string(),savedRevision:z16.string(),fingerprint:z16.string(),visibility:z16.literal("user-visible"),retention:z16.literal("durable"),expiresAt:z16.null(),merged:z16.literal(!1),published:z16.literal(!1),links:z16.object({preview:z16.url(),changes:z16.url(),conversation:z16.url().nullable()})}),ProposalTextSchema={title:z16.string().trim().min(1).max(80),summary:z16.string().trim().min(1).max(1e3),note:z16.string().trim().min(1).max(2e3).optional()},ProposalEntryInputSchema=z16.strictObject({collection:z16.string().trim().min(1).max(80),id:z16.string().trim().min(1).max(120).optional(),locale:z16.string().trim().min(1).max(20).optional(),fields:z16.record(z16.string(),z16.unknown())}),ProposalShowItemSchema=z16.union([z16.strictObject({page:z16.string().trim().startsWith("/").max(500),note:z16.string().trim().min(1).max(300)}),z16.strictObject({entry:z16.strictObject({collection:z16.string().trim().min(1).max(80),id:z16.string().trim().min(1).max(120)}),note:z16.string().trim().min(1).max(300)})]),ContentProposalInputSchema=z16.strictObject({...ProposalTextSchema,revise:z16.uuid().optional(),entries:z16.array(ProposalEntryInputSchema).min(1).max(20)}),SessionProposalInputSchema=z16.strictObject({...ProposalTextSchema,sessionId:z16.uuid(),show:z16.array(ProposalShowItemSchema).min(1).max(10)}),ProposeInputSchema=z16.strictObject({target:z16.string().trim().min(1).optional(),proposals:z16.array(z16.union([ContentProposalInputSchema,SessionProposalInputSchema])).min(1).max(20)}),StoredProposalEntrySchema=z16.object({collection:z16.string(),documentId:z16.string(),locale:z16.string(),action:z16.enum(["create","update"]),fields:z16.record(z16.string(),z16.unknown()),base:z16.record(z16.string(),z16.unknown()).optional()}),ProposalMetaSchema=z16.object({form:z16.enum(["content","session"]),title:z16.string(),note:z16.string().optional(),target:z16.string(),threadId:z16.uuid().nullable(),invocationId:z16.uuid().nullable(),show:z16.array(ProposalShowItemSchema).optional(),editedAt:z16.string().optional()}),ProposalListInputSchema=z16.strictObject({state:z16.enum(["open","decided","all"]).default("open"),scope:z16.enum(["chat","project"]).default("chat"),limit:z16.number().int().min(1).max(50).default(20),cursor:z16.string().max(200).optional()}),ProposalDecideInputSchema=z16.strictObject({id:z16.uuid(),decision:z16.enum(["accept","discard"]),target:z16.string().trim().min(1).optional()}),AgentBranchProposalDTOSchema=z16.object({id:z16.uuid(),envId:z16.uuid(),sessionId:z16.uuid().nullable(),skillName:z16.string().min(1),classification:AgentBranchClassificationSchema,rationale:z16.string().nullable(),summary:z16.string().nullable(),surfaceDeltas:z16.record(z16.string(),z16.unknown()),review:WorkSessionReviewSchema.optional(),proposal:ProposalMetaSchema.optional(),entries:z16.array(StoredProposalEntrySchema).optional(),createdAt:z16.coerce.date(),decidedAt:z16.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z16.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z16.object({path:z16.enum(["review-merged","review-discarded"]),acceptCurrent:z16.boolean().optional(),target:z16.string().trim().min(1).optional()}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z16.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z16.object({code:z16.literal("merge_conflict"),message:z16.string(),conflicts:z16.record(z16.string(),z16.number().int().nonnegative())}),ProposedSessionSchema=z16.object({proposalId:z16.uuid(),title:z16.string(),form:z16.literal("session"),sessionId:z16.uuid(),reviewUrl:z16.url(),links:WorkSessionReviewResultSchema.shape.links})}});import{z as z17}from"zod";var OPS_AGENT_PROPOSALS_MAX_WINDOW_MS,OpsAgentProposalStateSchema,OpsAgentProposalTypeSchema,OpsAgentProposalsInputSchema,OpsAgentProposalSchema,OpsAgentProposalsResponseDTO,init_ops_agent_proposals_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-proposals.dto.js"(){"use strict";init_ops();init_create_dto();init_agent_proposal_dto();OPS_AGENT_PROPOSALS_MAX_WINDOW_MS=2160*60*60*1e3,OpsAgentProposalStateSchema=z17.enum(["waiting","approved","discarded","auto-merged"]),OpsAgentProposalTypeSchema=z17.enum(["content","session"]),OpsAgentProposalsInputSchema=z17.strictObject({projectId:z17.uuid().optional(),since:z17.coerce.date(),until:z17.coerce.date().default(()=>new Date),state:z17.enum([...OpsAgentProposalStateSchema.options,"decided"]).optional(),type:OpsAgentProposalTypeSchema.optional(),limit:z17.coerce.number().int().min(1).max(200).default(50),cursor:z17.string().trim().min(1).max(500).optional(),reason:z17.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_AGENT_PROPOSALS_MAX_WINDOW_MS,{path:["since"],message:"agent proposal windows cannot exceed 90 days"}),OpsAgentProposalSchema=z17.object({id:z17.string(),projectId:z17.string(),type:OpsAgentProposalTypeSchema.nullable(),state:OpsAgentProposalStateSchema,decidedPath:z17.string().nullable(),createdAt:z17.string(),editedAt:z17.string().nullable(),decidedAt:z17.string().nullable(),decidedBy:z17.object({userId:z17.string(),kind:z17.enum(["person","agent","schedule","cli","service"])}).nullable(),origin:z17.object({agent:z17.string(),threadId:z17.string().nullable(),threadKind:z17.string().nullable(),parentThreadId:z17.string().nullable(),invocationId:z17.string().nullable(),workSessionId:z17.string().nullable(),source:z17.string().nullable()}),target:z17.string().nullable(),title:z17.string().nullable(),summary:z17.string().nullable(),show:z17.array(ProposalShowItemSchema).nullable(),entries:z17.array(StoredProposalEntrySchema.pick({collection:!0,documentId:!0,locale:!0,action:!0}).extend({fields:z17.array(z17.string())})).nullable()}),OpsAgentProposalsResponseDTO=createDTO(z17.object({backendProfile:OpsBackendProfileSchema,source:z17.literal("agent_branch_proposals"),window:z17.object({since:z17.string(),until:z17.string()}),projectId:z17.string().nullable(),proposals:z17.object({items:z17.array(OpsAgentProposalSchema),nextCursor:z17.string().nullable()})}))}});import{z as z18}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=z18.iso.datetime({offset:!0}).pipe(z18.coerce.date()),OpsRecentChatInputSchema=z18.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z18.string().trim().min(1).max(255).optional(),limit:z18.coerce.number().int().min(1).max(200).default(100),cursor:z18.string().trim().min(1).max(2e3).optional(),slim:z18.boolean().default(!0),reason:z18.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=z18.object({id:z18.string(),threadId:z18.string(),threadKind:z18.string(),providerMessageId:z18.string().nullable(),invocationId:z18.string().nullable(),env:z18.string().nullable(),role:z18.string(),parts:z18.array(z18.record(z18.string(),z18.unknown())),metadata:z18.object({status:z18.string().optional(),traceUrl:z18.string().optional(),externalFileChanges:z18.array(z18.unknown()).optional(),userView:z18.object({view:z18.object({at:z18.string(),tab:z18.string().optional(),title:z18.string().optional(),locale:z18.string().optional(),range:z18.string().optional(),unsaved:z18.boolean().optional()}).optional(),tabs:z18.array(z18.object({id:z18.string(),at:z18.string()})).optional()}).optional()}),stats:z18.object({toolCount:z18.number().int().nonnegative(),failedToolCount:z18.number().int().nonnegative()}),createdAt:z18.iso.datetime({offset:!0}),project:z18.object({id:z18.string(),name:z18.string(),displayName:z18.string().nullable(),organizationId:z18.string().nullable()})}),OpsRecentChatResponseSchema=z18.object({target:z18.object({backendProfile:OpsBackendProfileSchema,projectEnv:z18.string().nullable()}),window:z18.object({from:z18.iso.datetime({offset:!0}),to:z18.iso.datetime({offset:!0})}),messages:z18.object({items:z18.array(OpsRecentChatMessageSchema),nextCursor:z18.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});var init_types=__esm({"../../packages/api-contracts/dist/esm/ops/types.js"(){"use strict"}});function compact(value){return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0))}function time2(value){return value===void 0?void 0:resolveOpsTime(value)}function seg(value){return encodeURIComponent(value)}var init_shared=__esm({"../../packages/api-contracts/dist/esm/ops/commands/shared.js"(){"use strict";init_args();__name(compact,"compact");__name(time2,"time");__name(seg,"seg")}});import{z as z19}from"zod";var invocation,span,OpsChatViewSchema,OpsChatViewsInputSchema,viewIds,ending,toolCallRow,appCallRow,turnRow,turnSlice,viewEnvelope,OpsChatViewsResponseDTO,agentCommands,init_agent=__esm({"../../packages/api-contracts/dist/esm/ops/commands/agent.js"(){"use strict";init_ops_agent_proposals_dto();init_ops_chat_dto();init_ops();init_create_dto();init_args();init_types();init_shared();invocation=z19.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z19.string().trim().min(1).max(255).describe("Braintrust span id"),OpsChatViewSchema=z19.enum(["tool-calls","app-calls","turns","slices"]),OpsChatViewsInputSchema=OpsRecentChatInputSchema.safeExtend({view:OpsChatViewSchema}),viewIds=z19.object({threadId:z19.string(),invocationId:z19.string().nullable(),projectId:z19.string(),messageId:z19.string()}),ending={terminal:z19.string(),terminalReason:z19.string().nullable()},toolCallRow=viewIds.extend({tool:z19.string(),subcommand:z19.string().nullable(),state:z19.string().nullable(),failed:z19.boolean(),errorSignature:z19.string().nullable(),position:z19.number().int().nonnegative(),recoveredNext:z19.boolean().nullable()}),appCallRow=viewIds.extend({routineId:z19.string().nullable(),via:z19.string(),integrationId:z19.string().nullable(),appTool:z19.string().nullable(),withApproval:z19.boolean(),outcome:z19.enum(["ok","failed","approval_required","blocked","pending"]),errorSignature:z19.string().nullable(),position:z19.number().int().nonnegative()}),turnRow=viewIds.extend({...ending,userMessageId:z19.string().nullable(),failureCategory:z19.enum(["expected_billing_stop","expected_model_refusal","expected_cancellation","workspace_failure","provider_model_failure","unknown_failure"]).nullable(),changes:z19.string().nullable(),mergeState:z19.string().nullable(),validation:z19.string().nullable(),publication:z19.string().nullable(),stepCount:z19.number().int().nonnegative(),toolCount:z19.number().int().nonnegative(),failedToolCount:z19.number().int().nonnegative(),hasTextReply:z19.boolean(),fimoAuthored:z19.boolean().nullable()}),turnSlice=viewIds.extend({...ending,previousUserAsk:z19.string().max(300),previousAgentWords:z19.string().max(500),userMessage:z19.string().max(1500),agentReply:z19.string().max(1305),failedToolCalls:z19.array(z19.object({tool:z19.string(),errorSignature:z19.string()})).max(6)}),viewEnvelope=z19.object({target:z19.object({backendProfile:OpsBackendProfileSchema,projectEnv:z19.string().nullable()}),window:z19.object({from:z19.iso.datetime({offset:!0}),to:z19.iso.datetime({offset:!0})})}),OpsChatViewsResponseDTO=createDTO(z19.discriminatedUnion("view",[viewEnvelope.extend({view:z19.literal("tool-calls"),messages:z19.object({items:z19.array(toolCallRow),nextCursor:z19.string().nullable()})}),viewEnvelope.extend({view:z19.literal("app-calls"),messages:z19.object({items:z19.array(appCallRow),nextCursor:z19.string().nullable()})}),viewEnvelope.extend({view:z19.literal("turns"),messages:z19.object({items:z19.array(turnRow),nextCursor:z19.string().nullable()})}),viewEnvelope.extend({view:z19.literal("slices"),messages:z19.object({items:z19.array(turnSlice),nextCursor:z19.string().nullable()})})])),agentCommands=[{id:"agent.chats.views",summary:"Read tool calls, app calls, turn outcomes or customer-text slices from a bounded chat window",permission:"ops:project:chat:read",effect:"read",input:z19.object({view:OpsChatViewSchema,since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional(),limit:opsArgs.limit.max(200).default(100).describe("Source messages per page; each may produce several view rows"),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional().describe("Private JSON file; required for slices")}),request:__name(input=>({method:"POST",path:"/chat/messages/views",body:compact({view:input.view,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"agent.chats.recent",summary:"Read recent chat messages across every project in a time window",permission:"ops:project:chat:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional().describe("Only messages from this environment"),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z19.boolean().default(!1).describe("Include complete message parts instead of the slim transcript"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat/messages/recent",body:compact({from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"agent.chats.create",summary:"Create an agent chat with routines in a customer project, as the organization owner. Validate the spec and confirm intent first: routines run and spend credits",permission:"ops:project:agents:write",effect:"write",risk:"low",input:z19.object({project:opsArgs.project,spec:z19.record(z19.string(),z19.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{id:"agent.proposals",summary:"List agent proposals as stored: type, state, who decided, where they came from, title and summary (customer text)",permission:"ops:project:chat:read",effect:"read",input:z19.object({since:opsArgs.since.describe("Proposals made since: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:opsArgs.until.optional(),project:opsArgs.project.optional(),state:z19.enum([...OpsAgentProposalStateSchema.options,"decided"]).optional().describe("Only this state; decided is every state but waiting"),type:OpsAgentProposalTypeSchema.optional().describe("Only content or session proposals"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-proposals",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,state:input.state,type:input.type,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"agent.traces.list",summary:"List agent runs for a project, organization or thread, with cost and status",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z19.uuid().optional().describe("Chat thread id"),agent:z19.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z19.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z19.boolean().default(!1).describe("Only runs that recorded a Braintrust root span"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/list",body:compact({projectId:input.project,organizationId:input.org,threadId:input.thread,agentKey:input.agent,status:input.status,since:time2(input.since),minCostUsd:input.minCost,tracedOnly:input.tracedOnly,limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.costliest",summary:"Rank agent runs across projects by recorded cost, without content (maximum 31 days and 50 runs)",permission:"ops:project:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.describe("Inclusive window end: ISO timestamp or relative (required)"),limit:opsArgs.limit.max(50).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/costliest",body:{since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.budget",summary:"List chats whose runs crossed the context budget and had to wrap up (content-free)",permission:"ops:braintrust:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.optional(),limit:opsArgs.limit.max(25).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/budget-wrap-up",body:compact({since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.spans",summary:"List the spans of one agent run",permission:"ops:braintrust:read",effect:"read",input:z19.object({invocation,limit:opsArgs.limit.max(500).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans`,body:{limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.span",summary:"Read one span body (input and output) of an agent run",permission:"ops:braintrust:read",effect:"read",input:z19.object({invocation,span,maxChars:z19.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z19.boolean().default(!1).describe("Return the end of an over-long body instead of the start"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}`,body:{maxChars:input.maxChars,edge:input.tail?"end":"start",reason:input.reason}}),"request")},{id:"agent.traces.messages",summary:"Read the conversation the model saw in one LLM span",permission:"ops:braintrust:read",effect:"read",input:z19.object({invocation,span,message:z19.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z19.coerce.number().int().min(500).max(2e5).default(2e4),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}/messages`,body:compact({messageIndex:input.message,maxChars:input.maxChars,reason:input.reason})}),"request")},{id:"agent.traces.stats",summary:"Aggregate agent step latency, tokens and cost by model, provider, span or type",permission:"ops:braintrust:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z19.coerce.number().positive().optional().describe("Only steps at least this many seconds slow"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/stats",body:compact({since:time2(input.since),until:time2(input.until),groupBy:input.groupBy,spanType:input.spanType,slowerThanSeconds:input.slowerThan,limit:input.limit,reason:input.reason})}),"request")}]}});import{z as z20}from"zod";var assistantCommands,init_assistant=__esm({"../../packages/api-contracts/dist/esm/ops/commands/assistant.js"(){"use strict";init_args();init_types();init_shared();assistantCommands=[{id:"assistant.threads.list",summary:"List your admin assistant threads, newest activity first",permission:"ops:platform:read",effect:"read",input:z20.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z20.coerce.number().int().min(1).max(100).optional().describe("Maximum results"),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/assistant/threads",query:{q:input.query,limit:input.limit,cursor:input.cursor}}),"request")},{id:"assistant.threads.get",summary:"Read one admin assistant thread with every message",permission:"ops:platform:read",effect:"read",input:z20.object({thread:z20.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z21}from"zod";var day,billingCommands,init_billing=__esm({"../../packages/api-contracts/dist/esm/ops/commands/billing.js"(){"use strict";init_args();init_types();init_shared();day=z21.iso.date().describe("UTC day, YYYY-MM-DD"),billingCommands=[{id:"billing.move-to-free",summary:"Move one organization to Free through its existing cancellation flow, with customer consent",permission:"ops:billing:write",effect:"write",risk:"high",consent:!0,input:z21.object({org:opsArgs.org})},{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z21.object({customer:z21.string().trim().min(1).max(255).describe("Hyperline customer id"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/customers/${seg(input.customer)}`,query:{reason:input.reason}}),"request")},{id:"billing.org",summary:"Read an organization's billing state: subscription, plan projection, credits and wallet",permission:"ops:billing:read",effect:"read",input:z21.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"billing.bandwidth-contract",summary:"Read an organization's hosting bandwidth contract and current usage",permission:"ops:billing:read",effect:"read",input:z21.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}/bandwidth-contract`,query:{reason:input.reason}}),"request")},{id:"billing.ledger",summary:"Read an organization's credit ledger: holds, settlements, grants or usage events",permission:"ops:billing:read",effect:"read",input:z21.object({org:opsArgs.org,kind:z21.enum(["holds","settlements","grants","usage-events"]),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/ledger",query:compact({organizationId:input.org,kind:input.kind,since:time2(input.since),limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"referrals",summary:"List referral claims with the credit ledger rows each paid; --unpaid finds bonuses never paid",permission:"ops:billing:read",effect:"read",input:z21.object({user:opsArgs.user.optional().describe("Referred or referring user id"),org:opsArgs.org.optional().describe("Either user's default organization"),since:opsArgs.since.optional(),unpaid:z21.boolean().optional().describe("Only referrals with an owed, unpaid credit"),side:z21.enum(["referred","referrer"]).optional().describe("Only this side unpaid (the referrer is owed once the referral is activated)"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/referrals",query:compact({userId:input.user,organizationId:input.org,since:time2(input.since),unpaid:input.unpaid,side:input.side,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z21.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z21.iso.datetime({offset:!0}).optional().describe("Reuse evaluatedAt when resuming a scan"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/plan-projections/report",query:compact({reason:input.reason,at:input.at??new Date().toISOString(),cursor:input.cursor})}),"request")},{id:"billing.plans.reconcile",summary:"Repair organizations' local plan projections from Hyperline",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({orgs:z21.array(opsArgs.org).min(1).max(100).describe("Organization ids")})},{id:"billing.legacy-premium.report",summary:"Report legacy Premium organizations and where each stands in the Pro transition",permission:"ops:billing:read",effect:"read",input:z21.object({org:opsArgs.org.optional(),limit:opsArgs.limit.max(200).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/legacy-premium-report",query:compact({reason:input.reason,org:input.org,limit:input.limit})}),"request")},{id:"billing.legacy-premium.enroll",summary:"Record the approved Pro offer for one legacy Premium organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({org:opsArgs.org,deadline:z21.string().trim().min(1).max(64).describe("Decision date exactly 90 calendar days from today")})},{id:"billing.legacy-premium.comp",summary:"Accept an internal organization's Pro offer on its behalf, free through a 100% coupon",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({org:opsArgs.org,coupon:z21.string().trim().min(1).max(64).describe("Hyperline coupon id: 100% off every product")})},{id:"billing.legacy-premium.notify",summary:"Send the due legacy Premium transition notices for one organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({org:opsArgs.org})},{id:"billing.entitlements.sync",summary:"Reconcile subscription entitlement properties in Hyperline with Fimo's plans (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({batchSize:z21.coerce.number().int().min(1).max(100).default(50),concurrency:z21.coerce.number().int().min(1).max(10).default(2),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.agent-runtime.attach",summary:"Attach the Agent runtime product to PAYG and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({orgs:z21.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z21.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.database-compute.attach",summary:"Attach the Database compute product to PAYG, Starter and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({orgs:z21.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z21.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.dispatches.list",summary:"List billing usage dispatches to Hyperline by state",permission:"ops:billing:read",effect:"read",input:z21.object({state:z21.enum(["pending","dispatched","dead-lettered","discarded"]),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/billing/dispatches",body:{state:input.state,reason:input.reason}}),"request")},{id:"billing.dispatches.discard",summary:"Discard dead-lettered billing dispatches so they are never sent",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({dispatches:z21.array(z21.uuid()).min(1).max(100).describe("Dispatch ids")})},{id:"billing.dispatches.retry",summary:"Retry a dead-lettered billing dispatch",permission:"ops:billing:write",effect:"write",risk:"low",input:z21.object({dispatch:z21.uuid().describe("Dispatch id")})},{id:"billing.cache.invalidate",summary:"Clear an organization's cached billing state so the next read goes to Hyperline",permission:"ops:billing:write",effect:"write",risk:"low",input:z21.object({org:opsArgs.org})},{id:"billing.hosting-usage.day",summary:"Read hosting usage recorded for one source, meter and day",permission:"ops:billing:read",effect:"read",input:z21.object({source:z21.string().trim().min(1).max(100),meter:z21.string().trim().min(1).max(100),day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage",query:{source:input.source,meter:input.meter,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.reconciliation",summary:"Compare a project's served traffic with the hosting usage billed for one day",permission:"ops:billing:read",effect:"read",input:z21.object({project:opsArgs.project,day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/reconciliation",query:{projectId:input.project,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.periods",summary:"List an organization's hosting billing periods",permission:"ops:billing:read",effect:"read",input:z21.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/customer-periods",query:{organizationId:input.org,reason:input.reason}}),"request")}]}});import{z as z22}from"zod";var coreCommands,init_core=__esm({"../../packages/api-contracts/dist/esm/ops/commands/core.js"(){"use strict";init_args();init_types();init_shared();coreCommands=[{id:"find",summary:"Find projects, organizations or users by name, slug, domain, email or id",permission:"ops:project:read",effect:"read",input:z22.object({query:opsArgs.query,kind:z22.enum(["project","org","user"]).optional().describe("Only this kind of record"),limit:opsArgs.limit.max(100).default(20),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/find",query:compact({q:input.query,kind:input.kind,limit:input.limit,cursor:input.cursor})}),"request"),cli:{positional:"query"}},{id:"audit.list",summary:"List audit log entries, newest first",permission:"ops:audit:read",effect:"read",input:z22.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z22.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z22.string().trim().min(1).max(64).optional().describe("Audit action, e.g. project_takedown"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"GET",path:"/audit",query:compact({projectId:input.project,organizationId:input.org,actor:input.actor,action:input.action,since:time2(input.since),limit:input.limit})}),"request")}]}});import{z as z23}from"zod";var window2,healthCommands,init_health=__esm({"../../packages/api-contracts/dist/esm/ops/commands/health.js"(){"use strict";init_organization_features_dto();init_ops();init_args();init_types();init_shared();window2={since:opsArgs.since,until:opsArgs.until.optional()},healthCommands=[{id:"health.overview",summary:"Platform health brief: Sentry, logs, agents, publishing and support in one window",permission:"ops:project:read",effect:"read",input:z23.object({...window2,project:opsArgs.project.optional().describe("Narrow every source that can be narrowed to one project"),limit:opsArgs.limit.max(100).default(25).describe("Maximum findings per source"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.agents",summary:"Agent run outcomes, cost and duration grouped by agent, status, branch, project or day",permission:"ops:project:read",effect:"read",input:z23.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z23.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z23.boolean().default(!1).describe("Count sub-steps too"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,branch:input.env,agentKey:input.agent,groupBy:input.groupBy,includeChildren:input.includeChildren,limit:input.limit,reason:input.reason})}),"request")},{id:"health.context",summary:"Context-window pressure and compaction facts for agent turns",permission:"ops:project:read",effect:"read",input:z23.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(500),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/context-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.memory",summary:"Agent memory health: threads and routines with missing or stale memory",permission:"ops:project:read",effect:"read",input:z23.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/memory-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.providers",summary:"Model provider errors grouped by signature, optionally correlated to agent runs",permission:"ops:braintrust:read",effect:"read",input:z23.object({...window2,model:z23.string().trim().min(1).max(200).optional(),provider:z23.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z23.string().trim().min(1).max(64).optional().describe("Page boundary: nextBefore from the previous page"),limit:opsArgs.limit.max(1e3).default(500).describe("Error spans to scan per page"),correlate:z23.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z23.coerce.number().int().min(1).max(100).default(25),sampleChars:z23.coerce.number().int().min(200).max(2e4).default(1200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-provider-errors",body:compact({since:time2(input.since),until:time2(input.until),model:input.model,provider:input.provider,spanType:input.spanType,before:input.before,limit:input.limit,sampleChars:input.sampleChars,correlateInvocations:input.correlate||void 0,correlationLimit:input.correlate?input.correlationLimit:void 0,reason:input.reason})}),"request")},{id:"health.chat-history.summary",summary:"How often agents call the chatHistory tool and whether it finds what they need",permission:"ops:project:read",effect:"read",input:z23.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat-history/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,reason:input.reason})}),"request")},{id:"health.chat-history.calls",summary:"List chatHistory tool calls; --with-content adds the surrounding messages (needs chat read)",permission:"ops:project:read",effect:"read",input:z23.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z23.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:input.withContent?"/chat-history/calls/content":"/chat-history/calls",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.chat-history.judge",summary:"Have a model judge a sample of chatHistory calls; --calibrate runs the labelled benchmark",permission:"ops:project:chat:read",effect:"read",input:z23.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z23.coerce.number().int().min(1).max(25).default(10),calibrate:z23.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>input.calibrate?{method:"POST",path:"/chat-history/judge/calibration",body:{reason:input.reason}}:{method:"POST",path:"/chat-history/judge",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,sample:input.sample,reason:input.reason})},"request")},{id:"health.data-usage",summary:"Data-provider usage (search, scraping, enrichment) grouped by operation, provider, day, org or agent",permission:"ops:project:read",effect:"read",input:z23.object({...window2,org:opsArgs.org.optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/data-usage",body:compact({since:time2(input.since),until:time2(input.until),organizationId:input.org,groupBy:input.groupBy,limit:input.limit,reason:input.reason})}),"request")},{id:"health.routines",summary:"Routine runs, event bursts, Jev trigger calls and cost, by routine, plan, day or project",permission:"ops:project:read",effect:"read",input:z23.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z23.string().trim().min(1).max(64).optional().describe("Template routine key, or custom"),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total").describe("Rank buckets by total cost, Jev's trigger cost, or runs"),burstMinutes:z23.coerce.number().int().min(1).max(120).default(10).describe("An event this many minutes or less after the routine's previous one is a burst"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/routine-metrics",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,plan:input.plan,routine:input.routine,groupBy:input.groupBy,sortBy:input.sortBy,burstMinutes:input.burstMinutes,reason:input.reason})}),"request")},{id:"health.analytics",summary:"Whether a project's website analytics are arriving (content-free counts, max 7 days)",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z23.string().max(300).optional().describe("Exact test path ending in ?fimo_monitor=<UUID>"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/analytics-health`,body:compact({branch:input.env,canaryPath:input.canaryPath,since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason})}),"request")},{id:"health.session",summary:"A project's work-session and database-branch health: cleanup due, unresolved allocations, capacity",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project,checkProvider:z23.boolean().default(!1).describe("Include one bounded read-only Neon inventory page"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/session-health`,body:{reason:input.reason,limit:input.limit,checkProvider:input.checkProvider}}),"request")},{id:"health.sandbox",summary:"A project environment's sandbox and preview status",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project,env:opsArgs.env.default("main"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/sandbox/status`,body:{projectEnv:input.env,reason:input.reason}}),"request")},{id:"health.schedules",summary:"Failed scheduled runs and webhook deliveries",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z23.uuid().optional().describe("Schedule id"),run:z23.uuid().optional().describe("Schedule run id (needs --project)"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/schedules/failures",body:compact({projectId:input.project,projectEnv:input.env,scheduleId:input.schedule,runId:input.run,since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"health.integrations",summary:"Failing integration connections and inbound events",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/integrations/failures",body:compact({projectId:input.project,reason:input.reason})}),"request")},{id:"health.domains",summary:"Custom domains with DNS, SSL or provider problems",permission:"ops:project:read",effect:"read",input:z23.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/domains/problems",body:compact({projectId:input.project,organizationId:input.org,reason:input.reason})}),"request")}]}});import{z as z24}from"zod";var mergeCommands,init_merge=__esm({"../../packages/api-contracts/dist/esm/ops/commands/merge.js"(){"use strict";init_args();init_types();init_shared();mergeCommands=[{id:"merge.list",summary:"List merges, newest first; --stuck lists only merges that stopped progressing",permission:"ops:merges:read",effect:"read",input:z24.object({project:opsArgs.project.optional(),stuck:z24.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z24.string().trim().min(1).max(64).optional().describe("Only merges in this status"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/merges",query:compact({projectId:input.project,stuck:input.stuck||void 0,status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"merge.get",summary:"Show one merge with its steps, conflicts and release",permission:"ops:merges:read",effect:"read",input:z24.object({merge:z24.uuid().describe("Merge id")}),request:__name(input=>({method:"GET",path:`/merges/${seg(input.merge)}`}),"request")},{id:"merge.unwind",summary:"Force-unwind a stuck merge: reset the target branch to its pre-merge head and reopen the merge",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({merge:z24.uuid().describe("Merge id")})},{id:"merge.fail",summary:"Force-fail a stuck merge without touching the target branch",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({merge:z24.uuid().describe("Merge id")})}]}});var MONITORING_SEVERITIES,init_admin_monitoring_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin-monitoring.dto.js"(){"use strict";MONITORING_SEVERITIES=["critical","high","medium","low"]}});import{z as z25}from"zod";var OPS_SIGNAL_CASE_STATES,OpsSignalCaseStateSchema,OpsSignatureHashSchema,OPS_WATCH_STATES,OPS_WATCH_CLOSED_STATES,OPS_WATCH_CADENCES,OPS_WATCH_RESULTS,OPS_WATCH_MODELS,OPS_WATCH_EFFORTS,OpsWatchStateSchema,OpsWatchCadenceSchema,OpsWatchResultSchema,OpsWatchModelSchema,OpsWatchEffortSchema,OpsWatchSlugSchema,day2,watchText,watchRef,monitorCommands,init_monitor=__esm({"../../packages/api-contracts/dist/esm/ops/commands/monitor.js"(){"use strict";init_admin_monitoring_dto();init_args();init_types();init_shared();OPS_SIGNAL_CASE_STATES=["open","accepted","snoozed","dismissed","resolved"],OpsSignalCaseStateSchema=z25.enum(OPS_SIGNAL_CASE_STATES),OpsSignatureHashSchema=z25.string().trim().regex(/^[0-9a-f]{16}$/,"Expected a 16-character signature hash"),OPS_WATCH_STATES=["active","paused","met","missed","stopped"],OPS_WATCH_CLOSED_STATES=["met","missed","stopped"],OPS_WATCH_CADENCES=["daily","nightly","weekly","monthly"],OPS_WATCH_RESULTS=["on_track","problem","unknown"],OPS_WATCH_MODELS=["claude-opus-5-5","claude-fable-5-1","claude-sonnet-5-5","claude-haiku-5-5","gpt-6-astra","gpt-5.6-sol","gpt-5.6-luna"],OPS_WATCH_EFFORTS=["low","medium","high","xhigh","max"],OpsWatchStateSchema=z25.enum(OPS_WATCH_STATES),OpsWatchCadenceSchema=z25.enum(OPS_WATCH_CADENCES),OpsWatchResultSchema=z25.enum(OPS_WATCH_RESULTS),OpsWatchModelSchema=z25.enum(OPS_WATCH_MODELS),OpsWatchEffortSchema=z25.enum(OPS_WATCH_EFFORTS),OpsWatchSlugSchema=z25.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Expected a kebab-case slug").max(80),day2=z25.iso.date(),watchText=__name(max=>z25.string().trim().min(1).max(max),"watchText"),watchRef=z25.string().trim().min(1).max(80).describe("Watch slug or id"),monitorCommands=[{id:"monitor.checks.list",summary:"List staff checks with their schedule, action and last run",permission:"ops:investigations:read",effect:"read",input:z25.object({}),request:__name(()=>({method:"GET",path:"/monitor/checks"}),"request")},{id:"monitor.checks.try",summary:"Run one code check over a window, read-only, and show what it would open; nothing is stored (Jev and external checks are refused)",permission:"ops:investigations:read",effect:"read",input:z25.object({check:z25.string().trim().min(1).max(160).describe("Check id, e.g. agents/tools/errors/tool-failure-rate"),since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/monitor/checks/try",body:compact({checkId:input.check,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"monitor.cases.list",summary:"List cases opened by staff checks, newest activity first",permission:"ops:investigations:read",effect:"read",input:z25.object({state:OpsSignalCaseStateSchema.optional().describe("Only cases in this state"),check:z25.string().trim().min(1).max(160).optional().describe("Only cases from this check id, or from every check under a prefix ending in /"),minSeverity:z25.enum(MONITORING_SEVERITIES).optional().describe("Only cases at least this severe: critical, high, medium or low"),hash:OpsSignatureHashSchema.optional().describe("Only cases about this error signature hash: in the fingerprint or the evidence of the last 7 days"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional().describe("Continue from the nextCursor of a previous page")}),request:__name(input=>({method:"POST",path:"/monitor/cases",body:compact({state:input.state,checkId:input.check,minSeverity:input.minSeverity,signatureHash:input.hash,limit:input.limit,cursor:input.cursor})}),"request")},{id:"monitor.signature.get",summary:"Resolve an error signature hash from case evidence to its tool, normalized error text, reach and example chats (window up to 7d)",permission:"ops:project:chat:read",effect:"read",input:z25.object({hash:OpsSignatureHashSchema.describe("Signature hash, e.g. from a case evidence signatureHash or topSignatures"),since:opsArgs.since.default("24h"),until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/monitor/signatures",body:compact({hash:input.hash,since:time2(input.since),until:time2(input.until),reason:input.reason})}),"request")},{id:"monitor.cases.get",summary:"Read one case with its latest observations (ids and numbers only)",permission:"ops:investigations:read",effect:"read",input:z25.object({case:z25.uuid().describe("Case id")}),request:__name(input=>({method:"GET",path:`/monitor/cases/${seg(input.case)}`}),"request")},{id:"monitor.cases.update",summary:"Decide on a case: accept with a ceiling, snooze until a date, dismiss, resolve, or reopen",permission:"ops:investigations:write",effect:"write",risk:"low",input:z25.object({case:z25.uuid().describe("Case id"),state:OpsSignalCaseStateSchema.optional(),decisionReason:z25.string().trim().min(1).max(2e3).optional().describe("Why this decision; required to accept, snooze or dismiss. Shown on the finding"),ceiling:z25.number().nonnegative().optional().describe("For accepted: reopen above this metric"),snoozedUntil:z25.iso.datetime().optional().describe("For snoozed: reopen after this time"),linearIssue:z25.string().trim().regex(/^[A-Z]+-\d+$/).optional(),prUrl:z25.url().optional()})},{id:"monitor.watches.list",summary:"List watches with their model, effort, schedule, last result and next due time",permission:"ops:investigations:read",effect:"read",input:z25.object({state:z25.enum(["open","closed","all"]).default("open").describe("open: active and paused (default)")}),request:__name(input=>({method:"GET",path:"/monitor/watches",query:{state:input.state}}),"request")},{id:"monitor.watches.due",summary:"The active watches whose next run is due, each with its questions, reads, model and effort; `final` marks the run after the end date",permission:"ops:investigations:read",effect:"read",input:z25.object({}),request:__name(()=>({method:"GET",path:"/monitor/watches/due"}),"request")},{id:"monitor.watches.get",summary:"Read one watch with its definition and its latest runs",permission:"ops:investigations:read",effect:"read",input:z25.object({watch:watchRef}),request:__name(input=>({method:"GET",path:`/monitor/watches/${seg(input.watch)}`}),"request")},{id:"monitor.watches.save",summary:"Create a watch, or update the watch with this slug: its questions, reads, schedule, end date, model and effort, or pause, resume or stop it",permission:"ops:investigations:write",effect:"write",risk:"low",cli:{fileArgs:["change","rightAndWrong","ifWrong"]},input:z25.object({slug:OpsWatchSlugSchema.describe("Stable name, e.g. fimo-3175-app-calls"),title:watchText(240).optional().describe("The question in plain words. Required to create"),change:watchText(4e3).optional().describe('What changes for users and in which PR, or "standing" and the recurring question. Required to create'),questions:z25.array(watchText(1e3)).min(1).max(20).optional().describe("The calls to judge, asked both ways (repeatable). Required to create"),reads:z25.array(watchText(1e3)).min(1).max(20).optional().describe("What the run reads or needs (repeatable). Required to create"),rightAndWrong:watchText(4e3).optional().describe("What each verdict means, one example of each"),metWhen:watchText(1e3).optional().describe("For a temporary watch: when it is met"),ifWrong:watchText(4e3).optional().describe("The files a fix would change, and the eval or test that proves it"),cadence:OpsWatchCadenceSchema.optional().describe("Required to create"),startsOn:day2.optional().describe("First day it can run, YYYY-MM-DD (default today)"),endsOn:day2.optional().describe("Last day for a temporary watch, YYYY-MM-DD; without it the watch is standing"),standing:z25.boolean().optional().describe("Remove the end date: the watch runs until someone stops it"),model:OpsWatchModelSchema.optional().describe("The model that runs it (default claude-opus-5-5)"),effort:OpsWatchEffortSchema.optional().describe("Its reasoning effort (default high; max is Claude only)"),linearIssue:z25.string().trim().regex(/^[A-Z]+-\d+$/).optional().describe("The issue that owns the watch"),prUrls:z25.array(z25.url()).max(20).optional().describe("The PRs it watches (repeatable)"),state:z25.enum(["active","paused","stopped"]).optional().describe("Pause or resume it, or stop it with --close-reason"),closeReason:watchText(2e3).optional().describe("Why it stopped"),nextDueAt:z25.iso.datetime().optional().describe("Make it due at this time instead of its next slot")})},{id:"monitor.watches.report",summary:"Write one watch run's result: on_track, problem or unknown, with counts and alert ids; a final run closes it met or missed",permission:"ops:investigations:write",effect:"write",risk:"low",cli:{fileArgs:["summary"]},input:z25.object({watch:watchRef,result:OpsWatchResultSchema,summary:watchText(4e3).describe("What the run found, with counts and their denominator. No customer text"),judged:z25.number().int().nonnegative().optional().describe("Cases judged"),right:z25.number().int().nonnegative().optional(),wrong:z25.number().int().nonnegative().optional(),unclear:z25.number().int().nonnegative().optional(),caseIds:z25.array(z25.uuid()).max(50).optional().describe("Alerts the run opened or linked (repeatable)"),links:z25.array(z25.url()).max(20).optional().describe("Linear issues, PRs or receipts (repeatable)"),model:OpsWatchModelSchema.optional().describe("The model that ran it (default the watch's)"),effort:OpsWatchEffortSchema.optional().describe("Its effort (default the watch's)"),costUsd:z25.number().nonnegative().optional().describe("What the run cost at list price"),close:z25.enum(OPS_WATCH_CLOSED_STATES).optional().describe("Close the watch: met, missed, or stopped (reverted or replaced)"),closeReason:watchText(2e3).optional().describe("Why it closed; required with --close")})}]}});import{z as z26}from"zod";var channel,draft,notifyCommands,init_notify=__esm({"../../packages/api-contracts/dist/esm/ops/commands/notify.js"(){"use strict";init_ops();init_args();init_types();init_shared();channel=z26.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z26.uuid().describe("Draft id"),notifyCommands=[{id:"notify.draft",summary:"Draft a customer-visible message: an email to a project owner or a reply on a Pylon ticket",permission:"ops:notification:preview",effect:"write",risk:"low",input:z26.object({channel,message:z26.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z26.email().optional().describe("email: override the recipient"),subject:z26.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z26.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z26.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z26.array(z26.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z26.array(z26.email()).max(50).optional(),bccEmails:z26.array(z26.email()).max(50).optional()}),cli:{fileArgs:["message"]}},{id:"notify.show",summary:"Show a drafted customer message and its approval state",permission:"ops:notification:preview",effect:"read",input:z26.object({channel,draft}),request:__name(input=>({method:"GET",path:input.channel==="pylon"?`/support/pylon/replies/${seg(input.draft)}`:`/notifications/${seg(input.draft)}`}),"request")},{id:"notify.approve",summary:"Approve a drafted customer message (a person must approve before it can be sent)",permission:"ops:notification:approve",effect:"write",risk:"low",humanOnly:!0,input:z26.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z26.object({channel,draft})}]}});function normalizeSentryIssueReference(reference){let trimmed=reference.trim();if(SENTRY_ISSUE_ID_PATTERN.test(trimmed))return trimmed;let url;try{url=new URL(trimmed)}catch{throw new Error("Expected a Sentry issue id or /issues/<id>/ URL")}let segments=url.pathname.split("/").filter(Boolean),issuesIndex=segments.lastIndexOf("issues"),issueId=issuesIndex>=0&&issuesIndex===segments.length-2?segments[issuesIndex+1]:void 0;if(!issueId||!SENTRY_ISSUE_ID_PATTERN.test(issueId))throw new Error("Expected a Sentry issue id or /issues/<id>/ URL");return issueId}function collectTraceIds(value,candidates,depth=0){if(!(depth>32)){if(typeof value=="string"){TRACE_ID_PATTERN.test(value.trim())&&candidates.add(value.trim().toLowerCase());return}if(Array.isArray(value)){for(let item of value)collectTraceIds(item,candidates,depth+1);return}if(typeof value=="object"&&value!==null)for(let item of Object.values(value))collectTraceIds(item,candidates,depth+1)}}function normalizeTempoTraceReference(reference){let trimmed=reference.trim();if(TRACE_ID_PATTERN.test(trimmed))return trimmed.toLowerCase();let url;try{url=new URL(trimmed)}catch{throw new Error("Expected an exact 32-character trace id or a Grafana trace URL")}let candidates=new Set;for(let segment of url.pathname.split("/"))collectTraceIds(segment,candidates);for(let value of url.searchParams.values()){collectTraceIds(value,candidates);try{collectTraceIds(JSON.parse(value),candidates)}catch{continue}}if(candidates.size!==1)throw new Error(candidates.size===0?"Grafana URL did not contain a trace id":"Grafana URL contained multiple trace ids");return[...candidates][0]}var SENTRY_ISSUE_ID_PATTERN,TRACE_ID_PATTERN,init_references2=__esm({"../../packages/api-contracts/dist/esm/ops/references.js"(){"use strict";SENTRY_ISSUE_ID_PATTERN=/^[a-zA-Z0-9-]{1,100}$/,TRACE_ID_PATTERN=/^[a-fA-F0-9]{32}$/;__name(normalizeSentryIssueReference,"normalizeSentryIssueReference");__name(collectTraceIds,"collectTraceIds");__name(normalizeTempoTraceReference,"normalizeTempoTraceReference")}});import{z as z27}from"zod";function parseWhere(values){if(!(!values||values.length===0))return Object.fromEntries(values.map(value=>{let separator=value.indexOf("=");if(separator<1)throw new Error("--where expects key=value");return[value.slice(0,separator),value.slice(separator+1)]}))}var issue,logFilters,observeCommands,init_observe=__esm({"../../packages/api-contracts/dist/esm/ops/commands/observe.js"(){"use strict";init_args();init_references2();init_types();init_shared();issue=z27.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z27.array(z27.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z27.string().min(1).max(500).optional().describe("Plain-text line filter"),limit:opsArgs.limit.max(1e3).default(100),reason:opsArgs.reason,output:opsArgs.output.optional()},observeCommands=[{id:"observe.logs.query",summary:"Query a project's production logs in a time window",permission:"ops:logs:read",effect:"read",input:z27.object({...logFilters,since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}),"request")},{id:"observe.logs.around",summary:"Read a project's production logs a few minutes either side of a moment",permission:"ops:logs:read",effect:"read",input:z27.object({...logFilters,at:z27.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z27.coerce.number().int().min(1).max(120).default(5).describe("Minutes before and after")}),request:__name(input=>{let at=Date.parse(input.at);return{method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:new Date(at-input.minutes*6e4).toISOString(),to:new Date(at+input.minutes*6e4).toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}},"request")},{id:"observe.traces.get",summary:"Read one Grafana Tempo trace (id or Grafana URL) for a project",permission:"ops:traces:read",effect:"read",input:z27.object({trace:z27.string().trim().min(1).max(4e3).describe("32-character trace id or Grafana trace URL"),project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/traces/${normalizeTempoTraceReference(input.trace)}`,body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"observe.sentry.issues",summary:"Search Sentry issues, for one project or every project",permission:"ops:sentry:read",effect:"read",input:z27.object({project:opsArgs.project.optional(),search:z27.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z27.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z27.enum(["date","new","freq","user","trends"]).optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/sentry/issues",body:compact({projectId:input.project,query:input.search,statsPeriod:input.period,sort:input.sort,limit:input.limit,reason:input.reason})}),"request")},{id:"observe.sentry.issue",summary:"Read one Sentry issue",permission:"ops:sentry:read",effect:"read",input:z27.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.event",summary:"Read one full Sentry event",permission:"ops:sentry:read",effect:"read",input:z27.object({event:z27.string().trim().min(1).max(100).describe("Sentry event id"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/events/${seg(input.event)}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.latest-event",summary:"Read the latest full event of a Sentry issue",permission:"ops:sentry:read",effect:"read",input:z27.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}/events/latest`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.resolve",summary:"Mark a Sentry issue resolved",permission:"ops:sentry:write",effect:"write",risk:"low",input:z27.object({issue})},{id:"observe.posthog.milestones",summary:"Count a project's PostHog lifecycle milestones (create, deploy, first publish) in a window",permission:"ops:posthog:read",effect:"read",input:z27.object({project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/posthog/milestones",body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")}]}});import{z as z28}from"zod";var orgCommands,init_org=__esm({"../../packages/api-contracts/dist/esm/ops/commands/org.js"(){"use strict";init_organization_features_dto();init_args();init_types();init_shared();orgCommands=[{id:"org.get",summary:"Show an organization: plan, members, projects and subscription summary",permission:"ops:organizations:read",effect:"read",input:z28.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"org.features.list",summary:"List an organization's features and any staff overrides",permission:"ops:customers:read",effect:"read",input:z28.object({org:opsArgs.org}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}/features`}),"request")},{id:"org.features.set",summary:"Force an organization feature on or off, or clear the override",permission:"ops:organization:features:write",effect:"write",risk:"low",humanOnly:!0,input:z28.object({org:opsArgs.org,feature:z28.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z28.enum(["on","off","default"]).describe("on, off, or default to clear the override")})},{id:"org.takedown",summary:"Take every project of an organization off Fimo domains and block publishing",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z28.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z28.object({org:opsArgs.org})},{id:"org.delete",summary:"Delete an organization and everything it owns permanently",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z28.object({org:opsArgs.org})},{id:"org.credits.topup",summary:"Grant credits to an organization, free or as a recorded purchase",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z28.object({org:opsArgs.org,credits:z28.coerce.number().int().positive().describe("Number of credits"),type:z28.enum(["free","purchase"]).default("free"),amountCents:z28.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z28.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z28.string().trim().optional().describe("Note shown with the grant")})},{id:"org.credits.burn-zombies",summary:"Burn credits held by abandoned (zombie) holds of one organization since a date",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z28.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z29}from"zod";var OPS_PLATFORM_DASHBOARDS,platformCommands,init_platform=__esm({"../../packages/api-contracts/dist/esm/ops/commands/platform.js"(){"use strict";init_args();init_types();init_shared();OPS_PLATFORM_DASHBOARDS=["agents","money","projects","automation","growth","platform","usage","stats"],platformCommands=[{id:"platform.metrics",summary:"Read an admin dashboard as data: agents, money, projects, automation, growth, platform, usage or stats",permission:"ops:platform:read",effect:"read",input:z29.object({dashboard:z29.enum(OPS_PLATFORM_DASHBOARDS),since:opsArgs.since.default("7d"),until:opsArgs.until.optional()}),request:__name(input=>({method:"GET",path:"/platform/metrics",query:compact({dashboard:input.dashboard,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"platform.pool.status",summary:"Show the warm sandbox pool: size, target, and projects waiting in it",permission:"ops:platform:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/platform/pool"}),"request")},{id:"platform.pool.refill",summary:"Top the warm sandbox pool up to its target size",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({})},{id:"platform.pool.flush",summary:"Delete warm sandboxes from the pool, all of them or only the listed ones (new projects start cold until it refills)",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({pooled:z29.array(z29.uuid()).min(1).max(500).optional().describe("Only these pooled project ids; omit to flush all")})},{id:"platform.maintenance.status",summary:"Show whether maintenance mode is on and its message",permission:"ops:platform:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/platform/maintenance"}),"request")},{id:"platform.maintenance.enable",summary:"Turn maintenance mode on: Studio shows the message and refuses work",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({message:z29.string().max(500).optional().describe("Message shown to users")})},{id:"platform.maintenance.disable",summary:"Turn maintenance mode off",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({})},{id:"platform.maintenance.message",summary:"Change the maintenance message without toggling maintenance mode",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({message:z29.string().max(500).describe("Message shown to users")})},{id:"platform.sync-all",summary:"Re-sync every project's database records from its repository",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({})},{id:"platform.sync-tenant-schemas",summary:"Apply pending tenant schema migrations to every project database",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z29.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z29.object({event:z29.string().trim().min(1).max(255).describe("Inbound event id")})},{id:"platform.onboardings.list",summary:"List site onboardings (start from an existing website) with their status",permission:"ops:platform:read",effect:"read",input:z29.object({status:z29.string().trim().min(1).max(64).optional(),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/onboardings",query:compact({status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.onboardings.get",summary:"Show one project's site onboarding: questions, answers, refusal and timeline",permission:"ops:platform:read",effect:"read",input:z29.object({project:opsArgs.project,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/platform/onboardings/${seg(input.project)}`,query:{reason:input.reason}}),"request")},{id:"platform.onboardings.lift-refusal",summary:"Lift a site onboarding's Terms refusal so the project can continue",permission:"ops:platform:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project})},{id:"platform.unclaimed.list",summary:"List unclaimed projects (created without an account) and their claim state",permission:"ops:platform:read",effect:"read",input:z29.object({since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/unclaimed",query:compact({since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.resources.resolve",summary:"Resolve any id, URL, email or domain to the Fimo record it names",permission:"ops:platform:read",effect:"read",input:z29.object({query:z29.string().trim().min(1).max(512).describe("Id, URL, email or domain")}),request:__name(input=>({method:"GET",path:"/platform/resources/resolve",query:{q:input.query}}),"request"),cli:{positional:"query"}}]}});import{z as z30}from"zod";function files(project,action,env){return`/projects/${seg(project)}/files/${action}?projectEnv=${seg(env)}`}var envMain,projectCommands,init_project=__esm({"../../packages/api-contracts/dist/esm/ops/commands/project.js"(){"use strict";init_args();init_types();init_shared();envMain=opsArgs.env.default("main");__name(files,"files");projectCommands=[{id:"project.get",summary:"Inspect a project: owner, environments, domains, publications, recent runs and logs",permission:"ops:project:read",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,since:opsArgs.since.default("24h"),limit:opsArgs.limit.max(500).default(100).describe("Maximum log entries")}),request:__name(input=>({method:"GET",path:`/projects/${seg(input.project)}/inspect`,query:{projectEnv:input.env,hours:Math.min(168,opsHoursSince(input.since)),logLimit:input.limit}}),"request")},{id:"project.list",summary:"List projects across organizations, newest first: search by name or organization, or find those at their database limit (database quota reached)",permission:"ops:project:read",effect:"read",input:z30.object({query:opsArgs.query.optional().describe("Project name, display name, id or organization name"),databaseQuota:z30.enum(["blocked","refused"]).optional().describe("blocked: the database refuses queries now because the plan's quota is used up; refused: refused at any time, recovered ones included"),since:opsArgs.since.optional().describe("Created since: ISO timestamp or relative (30m, 24h, 7d, 2w)"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/projects",query:compact({search:input.query,databaseQuota:input.databaseQuota,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"project.snapshot",summary:"Download a zip snapshot of a project's source and content",permission:"ops:project:snapshot",effect:"read",input:z30.object({project:opsArgs.project,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/snapshot`,body:{reason:input.reason}}),"request")},{id:"project.chat",summary:"Read a project's agent chat transcript (the most recently active chat unless --thread is set)",permission:"ops:project:chat:read",effect:"read",input:z30.object({project:opsArgs.project,thread:z30.uuid().optional().describe("One chat or routine run thread id"),env:opsArgs.env.optional().describe("Only turns that targeted this environment"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z30.boolean().default(!1).describe("Include tool inputs, outputs and other message parts"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/chat/messages`,body:compact({projectEnv:input.env,threadId:input.thread,from:time2(input.since),to:time2(input.until),limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"project.files.read",summary:"Read one source file from a project environment",permission:"ops:project:snapshot",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,path:z30.string().trim().min(1).max(1024).describe("File path relative to the project root"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:files(input.project,"read",input.env),body:{path:input.path,reason:input.reason}}),"request")},{id:"project.files.glob",summary:"List source file paths in a project environment",permission:"ops:project:snapshot",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,pattern:z30.string().min(1).max(300).optional().describe("Glob pattern, e.g. src/**/*.tsx"),limit:opsArgs.limit.max(2e3).default(2e3),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"glob",input.env),body:compact({pattern:input.pattern,limit:input.limit,reason:input.reason})}),"request")},{id:"project.files.grep",summary:"Search source files in a project environment with a regular expression",permission:"ops:project:snapshot",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,pattern:z30.string().min(1).max(200).describe("Regular expression"),include:z30.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z30.boolean().default(!1),limit:opsArgs.limit.max(200).default(100).describe("Maximum matches"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"grep",input.env),body:compact({pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.limit,reason:input.reason})}),"request")},{id:"project.files.package-manager",summary:"Report which package manager a project declares and which lockfiles it has",permission:"ops:project:snapshot",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"package-manager",input.env),body:{reason:input.reason}}),"request")},{id:"project.files.write",summary:"Create or replace one source file in a project environment (commits to its branch)",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project,env:envMain,path:z30.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z30.string().max(256*1024).describe("The exact desired file contents"),overwrite:z30.boolean().default(!1).describe("Allow replacing an existing file")}),cli:{fileArgs:["content"]}},{id:"project.runtime.bump",summary:"Pin the project's fimo runtime packages to an exact version, install, and restart the dev server",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project,env:envMain,version:z30.string().trim().min(1).max(64).describe("Exact target version, e.g. 0.11.0")})},{id:"project.preview.restart",summary:"Restart the project's preview dev server",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z30.object({project:opsArgs.project,env:envMain})},{id:"project.publish",summary:"Publish the customer's site on their behalf. Only when a Fimo admin explicitly asks for it; never on an agent's own initiative",permission:"ops:project:publish",effect:"write",risk:"high",humanOnly:!0,consent:!0,input:z30.object({project:opsArgs.project,env:opsArgs.env.optional().describe("Source environment; defaults to the project's publish source")})},{id:"project.domain.refresh",summary:"Refresh a custom domain's provider and SSL state",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z30.object({project:opsArgs.project,domain:z30.uuid().describe("Project domain id")})},{id:"project.migrations.dry-run",summary:"Plan a source migration for one project without changing it",permission:"ops:project:read",effect:"read",input:z30.object({project:opsArgs.project,env:envMain,migration:z30.string().trim().min(1).max(120).optional().describe("Migration id (default: the current one)"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/migrations/projects/${seg(input.project)}/dry-run`,body:compact({migrationId:input.migration,projectEnv:input.env,reason:input.reason})}),"request")},{id:"project.sync",summary:"Re-sync a project's database records from its repository",permission:"ops:project:operate",effect:"write",risk:"low",input:z30.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z30.object({project:opsArgs.project,type:z30.enum(["dev","published"]).default("dev").describe("dev (the preview) or published (the live site)")})},{id:"project.version.restore",summary:"Restore a project environment to an earlier version (overwrites the current state)",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project,env:envMain,version:z30.string().trim().min(1).max(255).describe("Version id to restore")})},{id:"project.takedown",summary:"Take a project off Fimo domains and block it from publishing",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project})},{id:"project.restore",summary:"Lift a project takedown so it can serve and publish again",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project})},{id:"project.transfer",summary:"Move a project to another organization",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project,toOrg:opsArgs.org.describe("Destination organization id")})},{id:"project.delete",summary:"Delete a project and its resources permanently",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z30.object({project:opsArgs.project})}]}});import{z as z31}from"zod";var sandboxArg,OPS_SANDBOX_STATUSES,OPS_SANDBOX_OWNERS,OPS_SANDBOX_EXEC_MAX_TIMEOUT_SECONDS,sandboxCommands,init_sandbox=__esm({"../../packages/api-contracts/dist/esm/ops/commands/sandbox.js"(){"use strict";init_args();init_types();init_shared();sandboxArg=z31.string().trim().regex(/^[a-z0-9][a-z0-9-]{0,62}$/,"Expected a sandbox name: lowercase letters, digits and hyphens").describe("Sandbox name, as `sandbox list` shows it"),OPS_SANDBOX_STATUSES=["DEPLOYED","DEPLOYING","FAILED","DELETING","TERMINATED","UPLOADING","BUILDING","DEACTIVATING","DEACTIVATED","ARCHIVING","ARCHIVED","UNARCHIVING"],OPS_SANDBOX_OWNERS=["all","owned","unowned","pool"],OPS_SANDBOX_EXEC_MAX_TIMEOUT_SECONDS=300,sandboxCommands=[{id:"sandbox.list",summary:"List provider sandboxes with the project and Branch that own them, newest first; unowned ones are labelled, never guessed",permission:"ops:platform:read",effect:"read",input:z31.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),status:z31.enum(OPS_SANDBOX_STATUSES).optional().describe("Only sandboxes in this provider status"),owner:z31.enum(OPS_SANDBOX_OWNERS).default("all").describe("owned: a project Branch here; pool: the warm pool; unowned: neither"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/sandboxes",query:compact({projectId:input.project,projectEnv:input.env,status:input.status,owner:input.owner,limit:input.limit,cursor:input.cursor})}),"request")},{id:"sandbox.get",summary:"Show one sandbox: the provider's status, lifecycle events and infrastructure errors, and the project and Branch it belongs to",permission:"ops:platform:read",effect:"read",input:z31.object({sandbox:sandboxArg,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/sandboxes/${seg(input.sandbox)}`,query:{reason:input.reason}}),"request")},{id:"sandbox.logs",summary:"Read a sandbox's process output, newest lines last, redacted and bounded; only sandboxes a project here owns",permission:"ops:logs:read",effect:"read",input:z31.object({sandbox:sandboxArg,process:z31.string().trim().regex(/^[\w.-]{1,128}$/,"Expected a process name").optional().describe("Only this process, e.g. start-dev-server or install-dependencies"),since:opsArgs.since.default("24h").describe("Processes that started after this or are still running (lines carry no timestamps)"),limit:opsArgs.limit.max(1e3).default(200).describe("Newest lines kept per process"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/sandboxes/${seg(input.sandbox)}/logs`,body:compact({process:input.process,since:time2(input.since),limit:input.limit,reason:input.reason})}),"request")},{id:"sandbox.exec",summary:"Run one shell command in a sandbox a project here owns, with a time limit; the audit row keeps the exact command, never its output",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z31.object({sandbox:sandboxArg,command:z31.string().trim().min(1).max(4e3).describe("Shell command, run with `sh -c` in the project directory"),timeout:z31.coerce.number().int().min(1).max(OPS_SANDBOX_EXEC_MAX_TIMEOUT_SECONDS).default(30).describe("Seconds before the command is killed")})},{id:"sandbox.restart",summary:"Restart the Fimo dev server in a sandbox a project here owns; files and other processes are kept. The plan lists the sandbox's open work",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z31.object({sandbox:sandboxArg})},{id:"sandbox.kill",summary:"Delete a sandbox a project here owns; its Branch gets a new one from Git. Refused while it holds unsaved work unless --discard-unsaved",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z31.object({sandbox:sandboxArg,discardUnsaved:z31.boolean().default(!1).describe("Delete even though the plan shows unsaved work or a running agent on it")})}]}});import{z as z32}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=z32.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z32.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z32.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z32.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z32.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z32.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z32.enum(["user","agent","system"]),SupportReportTagSchema=z32.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z32.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z32.object({organization:z32.object({id:z32.string().trim().min(1).max(255),name:z32.string().trim().max(240).optional()}),project:z32.object({id:z32.uuid(),name:z32.string().trim().max(240).optional(),createdAt:z32.coerce.date().optional()}).optional(),environment:z32.string().trim().max(255).optional(),clientVersion:z32.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z32.object({message:z32.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z32.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z32.string().trim().max(200).optional(),limit:z32.coerce.number().int().min(1).max(100).default(50),offset:z32.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z32.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z32.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z32.uuid().nullable().optional(),note:z32.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=z32.object({message:z32.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z32.object({kind:SupportReportLinkKindSchema,label:z32.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z32.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z32.object({kind:SupportReportActorKindSchema,id:z32.string().nullable(),name:z32.string().nullable()}),SupportReportLinkDTOSchema=z32.object({id:z32.uuid(),kind:SupportReportLinkKindSchema,label:z32.string(),url:SupportReportHttpUrlSchema,externalId:z32.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z32.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z32.object({id:z32.uuid(),kind:SupportReportEventKindSchema,body:z32.string().nullable(),metadata:z32.record(z32.string(),z32.unknown()),actor:SupportReportActorDTOSchema,createdAt:z32.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z32.object({id:z32.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z32.array(z32.string()),source:SupportReportSourceSchema,message:z32.string(),reporter:z32.object({id:z32.string().nullable(),name:z32.string().nullable(),email:z32.string().nullable()}),organization:z32.object({id:z32.string().nullable(),name:z32.string()}),project:z32.object({id:z32.uuid().nullable(),name:z32.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z32.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z32.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z32.string().nullable(),deliveredAt:z32.coerce.date().nullable()}).nullable(),duplicateOfReportId:z32.uuid().nullable(),resolvedAt:z32.coerce.date().nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z32.string().nullable(),clientVersion:z32.string().nullable(),links:z32.array(SupportReportLinkDTOSchema),events:z32.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z32.object({reports:z32.array(SupportReportSummaryDTOSchema),total:z32.number().int().nonnegative(),statusCounts:z32.object({new:z32.number().int().nonnegative(),in_progress:z32.number().int().nonnegative(),waiting:z32.number().int().nonnegative(),resolved:z32.number().int().nonnegative(),duplicate:z32.number().int().nonnegative(),irrelevant:z32.number().int().nonnegative(),ignored:z32.number().int().nonnegative()}),limit:z32.number().int().positive(),offset:z32.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z32.object({id:z32.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z32.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z33}from"zod";var report,pylonIssue,supportCommands,init_support=__esm({"../../packages/api-contracts/dist/esm/ops/commands/support.js"(){"use strict";init_support_report_dto();init_ops();init_args();init_types();init_shared();report=z33.uuid().describe("Support report id"),pylonIssue=OpsPylonIssueIdSchema.describe("Pylon issue id"),supportCommands=[{id:"support.reports.list",summary:"List Fimo support reports, newest first",permission:"ops:support:read",effect:"read",input:z33.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z33.string().trim().min(1).max(50).optional(),search:z33.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z33.coerce.number().int().min(0).default(0),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/reports",query:compact({reason:input.reason,status:input.status,category:input.category,source:input.source,tag:input.tag,query:input.search,limit:input.limit,offset:input.offset})}),"request")},{id:"support.reports.get",summary:"Read one support report with its messages, links and context",permission:"ops:support:read",effect:"read",input:z33.object({report,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:`/support/reports/${seg(input.report)}`,query:{reason:input.reason}}),"request")},{id:"support.reports.claim",summary:"Claim a support report (mark it in progress), optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({report,note:z33.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.update",summary:"Change a support report's status, category, tags or duplicate link, optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z33.array(z33.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z33.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z33.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.note",summary:"Add an internal message to a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({report,message:z33.string().trim().min(1).max(2e4)}),cli:{fileArgs:["message"]}},{id:"support.reports.link",summary:"Link a support report to a Linear issue, Pylon ticket, project, Sentry issue or other URL",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({report,kind:SupportReportLinkKindSchema,label:z33.string().trim().min(1).max(240),url:z33.url({protocol:/^https?$/}).max(2e3),externalId:z33.string().trim().min(1).max(255).optional()})},{id:"support.reports.unlink",summary:"Remove a link from a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({report,link:z33.uuid().describe("Link id")})},{id:"support.intake",summary:"Show the support intake receipt: reports received and delivered in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z33.object({since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/support/intake/status",query:{since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"support.pylon.list",summary:"List Pylon support tickets in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z33.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z33.enum(["open","closed","all"]).default("open"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/pylon/issues",query:compact({since:time2(input.since),until:time2(input.until)??new Date().toISOString(),state:input.state,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"support.pylon.thread",summary:"Read the full message thread of a Pylon ticket",permission:"ops:support:read",effect:"read",input:z33.object({issue:pylonIssue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/support/issues/${seg(input.issue)}/thread`,body:{reason:input.reason}}),"request")},{id:"support.pylon.resolve",summary:"Close a Pylon ticket",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({issue:pylonIssue})},{id:"support.pylon.note",summary:"Add an internal note to a Pylon ticket (not visible to the customer)",permission:"ops:support:write",effect:"write",risk:"low",input:z33.object({issue:pylonIssue,message:z33.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z34}from"zod";var userCommands,init_user=__esm({"../../packages/api-contracts/dist/esm/ops/commands/user.js"(){"use strict";init_args();init_types();init_shared();userCommands=[{id:"user.get",summary:"Show a user: profile, role, organizations, recent sessions and usage",permission:"ops:users:read",effect:"read",input:z34.object({user:opsArgs.user,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/users/${seg(input.user)}`,query:{reason:input.reason}}),"request")},{id:"user.sessions",summary:"List sign-in sessions, for one user or across the platform",permission:"ops:users:read",effect:"read",input:z34.object({user:opsArgs.user.optional(),active:z34.boolean().optional().describe("Only sessions that have not expired or been revoked"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/sessions",query:compact({userId:input.user,active:input.active,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"user.session.revoke",summary:"Revoke one sign-in session",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z34.object({session:z34.string().trim().min(1).max(255).describe("Session id")})},{id:"user.ban",summary:"Ban a user from signing in and sign them out of every session; --reason is stored as the ban reason",permission:"ops:users:write",effect:"write",risk:"high",humanOnly:!0,input:z34.object({user:opsArgs.user,expires:z34.enum(["1d","7d","30d"]).optional().describe("Lift the ban after this long; permanent when omitted")})},{id:"user.unban",summary:"Lift a ban so the user can sign in again",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z34.object({user:opsArgs.user})}]}});import{z as z35}from"zod";var evidence,versions,detectionQueries,watchCommands,init_watch=__esm({"../../packages/api-contracts/dist/esm/ops/commands/watch.js"(){"use strict";init_ops();init_args();init_types();init_shared();evidence=z35.array(z35.record(z35.string(),z35.unknown())).max(100),versions=z35.array(z35.string().trim().min(1).max(120)).max(100),detectionQueries=z35.array(z35.string().trim().min(1).max(2e3)).max(50),watchCommands=[{id:"watch.list",summary:"List watched projects and why each is watched",permission:"ops:customers:read",effect:"read",input:z35.object({}),request:__name(()=>({method:"GET",path:"/customers"}),"request")},{id:"watch.add",summary:"Watch a project (or update why it is watched)",permission:"ops:customers:write",effect:"write",risk:"low",input:z35.object({project:opsArgs.project,importance:z35.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z35.string().trim().max(120).optional(),packageManager:z35.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z35.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z35.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z35.object({project:opsArgs.project}),request:__name(input=>({method:"GET",path:`/customers/${seg(input.project)}/validations`}),"request")},{id:"watch.validations.record",summary:"Record the outcome of validating a release, migration or change against a watched project",permission:"ops:validations:write",effect:"write",risk:"low",input:z35.object({project:opsArgs.project,change:z35.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z35.string().trim().min(1).max(1e4),evidence:evidence.default([])}),cli:{fileArgs:["evidence"]}},{id:"watch.investigations.list",summary:"List open and recent investigations",permission:"ops:investigations:read",effect:"read",input:z35.object({}),request:__name(()=>({method:"GET",path:"/investigations"}),"request")},{id:"watch.investigations.create",summary:"Open an investigation into a problem on a project",permission:"ops:investigations:write",effect:"write",risk:"low",input:z35.object({project:opsArgs.project,title:z35.string().trim().min(1).max(240),userReport:z35.string().trim().max(1e4).optional().describe("The customer's own words")})},{id:"watch.investigations.update",summary:"Update an investigation's status, hypothesis, outcome or evidence",permission:"ops:investigations:write",effect:"write",risk:"low",input:z35.object({investigation:z35.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z35.string().trim().max(1e4).optional(),outcome:z35.string().trim().max(1e4).optional(),evidence:evidence.optional()}),cli:{fileArgs:["evidence"]}},{id:"watch.known-issues.list",summary:"List known issues and their detection queries",permission:"ops:known-issues:read",effect:"read",input:z35.object({}),request:__name(()=>({method:"GET",path:"/known-issues"}),"request")},{id:"watch.known-issues.create",summary:"Record a known issue with how to detect it and any workaround",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z35.object({fingerprint:z35.string().trim().min(1).max(240),title:z35.string().trim().min(1).max(240),description:z35.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z35.string().trim().min(1).max(64).optional(),workaround:z35.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.default("open")}),cli:{fileArgs:["detectionQueries"]}},{id:"watch.known-issues.update",summary:"Update a known issue",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z35.object({knownIssue:z35.uuid().describe("Known issue id"),title:z35.string().trim().min(1).max(240).optional(),description:z35.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z35.string().trim().min(1).max(64).optional(),workaround:z35.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.optional()}),cli:{fileArgs:["detectionQueries"]}}]}});var OPS_COMMANDS,BY_ID,OPS_OPERATION_IDS,init_commands=__esm({"../../packages/api-contracts/dist/esm/ops/commands/index.js"(){"use strict";init_agent();init_agent();init_assistant();init_billing();init_core();init_health();init_merge();init_monitor();init_monitor();init_notify();init_observe();init_org();init_platform();init_platform();init_project();init_sandbox();init_sandbox();init_support();init_user();init_watch();OPS_COMMANDS=[...coreCommands,...projectCommands,...orgCommands,...userCommands,...mergeCommands,...agentCommands,...healthCommands,...billingCommands,...platformCommands,...sandboxCommands,...observeCommands,...supportCommands,...watchCommands,...monitorCommands,...notifyCommands,...assistantCommands],BY_ID=new Map(OPS_COMMANDS.map(command=>[command.id,command])),OPS_OPERATION_IDS=OPS_COMMANDS.filter(command=>command.effect==="write").map(command=>command.id)}});var CHAT_TAB_ADDRESS_FORMS,CHAT_TAB_ADDRESS_HELP,init_chat_tabs=__esm({"../../packages/api-contracts/dist/esm/types/chat-tabs.js"(){"use strict";CHAT_TAB_ADDRESS_FORMS=[["page:<path>","the preview at that page, or part of it: page:/pricing#faq"],["entry:<type>/<id>","an entry; #<field group> opens that group: entry:posts/abc#seo"],["collection:<type>","a content type's entries"],["form:<id>","a form's submissions"],["submission:<form>/<id>","one submission"],["content:<section>","collections, singles, forms, labels, pages or pages/<id>"],["assets","the media library; assets:<folder> opens a folder"],["analytics","the analytics dashboard"],["settings","project settings; settings:<path> opens a page: settings:domains, settings:schedules/<id>"]],CHAT_TAB_ADDRESS_HELP=CHAT_TAB_ADDRESS_FORMS.map(([form,shows])=>`${form}: ${shows}`).join(`
5
5
  `)}});import{z as z36}from"zod";var SitePagePathSchema,CHAT_SETTINGS_PAGES,proposal,ChatPagePlaceSchema,ChatEntryPlaceSchema,ChatAssetPlaceSchema,ChatRoutinePlaceSchema,ChatSettingsPlaceSchema,ChatAgentPlaceSchema,ChatPlaceSchema,init_chat_place=__esm({"../../packages/api-contracts/dist/esm/types/chat-place.js"(){"use strict";init_chat_tabs();SitePagePathSchema=z36.string().trim().max(200).regex(/^\/(?!\/)/,"A page starts with one /."),CHAT_SETTINGS_PAGES=["general","knowledge","domains","seo","integrations","languages","code-sync","advanced","models","environments","variables","secrets","schedules","webhooks"],proposal=z36.uuid().optional(),ChatPagePlaceSchema=z36.object({kind:z36.literal("page"),path:SitePagePathSchema,proposal}),ChatEntryPlaceSchema=z36.object({kind:z36.literal("entry"),collection:z36.string().min(1).max(80),entryId:z36.string().min(1).max(120),proposal}),ChatAssetPlaceSchema=z36.object({kind:z36.literal("asset"),assetId:z36.string().min(1).max(120),proposal}),ChatRoutinePlaceSchema=z36.object({kind:z36.literal("routine"),routineId:z36.string().min(1).max(120)}),ChatSettingsPlaceSchema=z36.object({kind:z36.literal("settings"),page:z36.enum(CHAT_SETTINGS_PAGES),proposal}),ChatAgentPlaceSchema=z36.object({kind:z36.literal("agent"),agentId:z36.string().min(1).max(120)}),ChatPlaceSchema=z36.discriminatedUnion("kind",[ChatPagePlaceSchema,ChatEntryPlaceSchema,ChatAssetPlaceSchema,ChatRoutinePlaceSchema,ChatSettingsPlaceSchema,ChatAgentPlaceSchema])}});function partsAfterReplyStart(parts){let start=parts.map(part=>part?.type).lastIndexOf(START_REPLY_PART_TYPE);return parts.slice(start+1)}var START_REPLY_PART_TYPE,init_chat_reply=__esm({"../../packages/api-contracts/dist/esm/types/chat-reply.js"(){"use strict";START_REPLY_PART_TYPE="tool-start_reply";__name(partsAfterReplyStart,"partsAfterReplyStart")}});import{z as z37}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[]}}function authorKindOf(message){return message.author?.kind??message.metadata?.__fimoChat?.author?.kind}function parseChatFormToolPart(part){let candidate=part,isRender=BLOCK_RENDER_PART_TYPES.includes(candidate?.type);if(!isRender&&candidate?.type!==BLOCK_UPDATE_PART_TYPE||typeof candidate.toolCallId!="string")return null;let isPending=isRender&&(candidate.state==="call"||candidate.state==="input-available"),isAccepted=candidate.state==="output-available"&&candidate.output?.rendered===!0;if(!isPending&&!isAccepted)return null;let acceptedBlock2=candidate.output?.block,proposedBlock=candidate.input?.block,parsed=FormBlockSchema.safeParse(isAccepted&&acceptedBlock2!==void 0?acceptedBlock2:proposedBlock);return parsed.success?{toolCallId:candidate.toolCallId,block:parsed.data,status:isPending?"pending":"accepted"}:null}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,AgentBlockSchema,PreviewBlockSchema,SearchImageUrlSchema,SearchPreviewBlockSchema,HandoffBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,FormChoicesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,CHAT_FORM_INTERNAL_NOTE_MAX,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,BLOCK_RENDER_PART_TYPES,BLOCK_UPDATE_PART_TYPE,BLOCK_CLOSE_PART_TYPE,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";init_chat_place();init_chat_reply();BlockSayActionSchema=z37.object({kind:z37.literal("say"),label:z37.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z37.string().min(1).max(500).optional(),message:z37.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z37.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z37.discriminatedUnion("command",[z37.object({kind:z37.literal("app"),command:z37.literal("publish")}).strict(),z37.object({kind:z37.literal("app"),command:z37.literal("connect"),integrationKey:z37.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z37.object({fallback:z37.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z37.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z37.literal("choices"),text:z37.string().max(500).optional(),actions:z37.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z37.discriminatedUnion("kind",[ChatPagePlaceSchema,ChatEntryPlaceSchema,ChatAssetPlaceSchema,ChatRoutinePlaceSchema,ChatSettingsPlaceSchema,z37.object({kind:z37.literal("url"),url:z37.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z37.literal("table"),columns:z37.array(z37.object({label:z37.string().min(1).max(24)})).min(2).max(4),rows:z37.array(z37.object({cells:z37.array(z37.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z37.literal("cards"),layout:z37.enum(["rail","stack"]).optional(),items:z37.array(z37.object({title:z37.string().min(1).max(60),subtitle:z37.string().min(1).max(120).optional(),imageUrl:z37.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z37.literal("entry"),label:z37.string().min(1).max(80),collection:z37.string().min(1).max(80),entryId:z37.string().min(1).max(120),path:z37.string().min(1).max(120).optional()}),DraftsBlockSchema=BlockBaseSchema.extend({type:z37.literal("drafts"),items:z37.array(z37.object({label:z37.string().trim().min(1).max(80),collection:z37.string().min(1).max(80).optional(),entryId:z37.string().min(1).max(120).optional(),reviewId:z37.uuid().optional(),routineId:z37.string().min(1).max(120).optional()}).refine(item=>!item.entryId||item.reviewId&&item.collection,{message:"A row that opens an entry names its collection, entryId and the proposal id from propose."})).min(1).max(20)}),AssetsBlockSchema=BlockBaseSchema.extend({type:z37.literal("assets"),items:z37.array(z37.object({url:z37.url({protocol:/^https$/}).max(2e3),alt:z37.string().min(1).max(120),label:z37.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z37.literal("callout"),title:z37.string().min(1).max(80),text:z37.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z37.literal("stat"),items:z37.array(z37.object({label:z37.string().min(1).max(24),value:z37.string().min(1).max(16),delta:z37.string().min(1).max(12).optional(),tone:z37.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z37.literal("chart"),unit:z37.string().min(1).max(12).optional(),kind:z37.enum(["bars","columns"]).optional(),max:z37.number().finite().positive().max(1e9).optional(),highlight:z37.string().min(1).max(12).optional(),points:z37.array(z37.object({label:z37.string().min(1).max(12),value:z37.number().finite().min(0).max(1e9),note:z37.string().min(1).max(80).optional()})).min(2).max(12)}).superRefine(({highlight,max,points},ctx)=>{highlight!==void 0&&!points.some(point=>point.label===highlight)&&ctx.addIssue({code:"custom",path:["highlight"],message:"The highlighted point must be one of the labels."}),max!==void 0&&points.some(point=>point.value>max)&&ctx.addIssue({code:"custom",path:["max"],message:"No value can be above the scale's max."})}),BeforeAfterBlockSchema=BlockBaseSchema.extend({type:z37.literal("before_after"),title:z37.string().min(1).max(80),meta:z37.string().min(1).max(80).optional(),rows:z37.array(z37.object({label:z37.string().min(1).max(24),before:z37.string().max(600),after:z37.string().max(600),showLength:z37.boolean().optional()}).refine(row2=>row2.before.trim()!==""||row2.after.trim()!=="",{message:"A row needs the current words, the new words, or both."})).min(1).max(6)}),AgentBlockSchema=BlockBaseSchema.extend({type:z37.literal("agent"),agentId:z37.string().uuid(),view:z37.enum(["compact","full"]).optional()}),PreviewBlockSchema=BlockBaseSchema.extend({type:z37.literal("preview"),path:SitePagePathSchema.optional(),detail:z37.string().trim().min(1).max(80).optional()}),SearchImageUrlSchema=z37.url({protocol:/^https$/}).max(2e3),SearchPreviewBlockSchema=BlockBaseSchema.extend({type:z37.literal("search_preview"),url:z37.string().trim().min(1).max(200),pageTitle:z37.string().trim().min(1).max(200),description:z37.string().trim().min(1).max(500),siteName:z37.string().trim().min(1).max(60).optional(),faviconUrl:SearchImageUrlSchema.optional(),breadcrumbs:z37.array(z37.string().trim().min(1).max(40)).min(1).max(4).optional(),date:z37.string().trim().min(1).max(24).optional(),imageUrl:SearchImageUrlSchema.optional(),video:z37.object({duration:z37.string().trim().min(1).max(8),moments:z37.number().int().min(1).max(20).optional()}).optional(),rating:z37.object({value:z37.number().min(0).max(5),count:z37.string().trim().min(1).max(16).optional()}).optional(),attributes:z37.array(z37.string().trim().min(1).max(40)).min(1).max(4).optional(),prosCons:z37.array(z37.string().trim().min(1).max(48)).min(1).max(4).optional(),readMore:z37.boolean().optional(),sitelinks:z37.array(z37.object({title:z37.string().trim().min(1).max(60),description:z37.string().trim().min(1).max(120).optional(),path:SitePagePathSchema.optional()})).min(1).max(6).optional(),sitelinksLayout:z37.enum(["rows","chips"]).optional(),query:z37.string().trim().min(1).max(80).optional()}),HandoffBlockSchema=BlockBaseSchema.extend({type:z37.literal("handoff"),task:z37.string().trim().min(1).max(1e3).optional()}),ChatDisplayBlockSchema=z37.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema,HandoffBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z37.literal("text"),placeholder:z37.string().min(1).max(120).optional(),multiline:z37.boolean().optional()}).strict(),ChatFormStepIdSchema=z37.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z37.object({id:ChatFormStepIdSchema,token:z37.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z37.string().trim().min(1).max(60),reason:z37.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z37.literal("capabilities"),items:z37.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block2,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block2.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block2.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block2.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),FormChoicesBlockSchema=ChoicesBlockSchema.extend({actions:z37.array(BlockActionSchema).min(2,"A choices step needs 2 to 8 options.").max(8,"A choices step needs 2 to 8 options.")}),ChatFormBodySchema=z37.discriminatedUnion("type",[FormChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z37.object({id:ChatFormStepIdSchema.optional(),question:z37.string().min(1).max(500),header:z37.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z37.boolean().optional(),recommended:z37.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===!1&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}).transform(step=>({...step,multiSelect:step.multiSelect??step.body.type==="capabilities"})),CHAT_FORM_INTERNAL_NOTE_MAX=1e3,FormBlockSchema=BlockBaseSchema.extend({type:z37.literal("form"),steps:z37.array(ChatFormStepSchema).min(1).max(4),internalNote:z37.string().trim().min(1).max(CHAT_FORM_INTERNAL_NOTE_MAX).optional()}),ChatBlockSchema=z37.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema,HandoffBlockSchema,AgentBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z37.object({block:ChatBlockSchema});__name(authorKindOf,"authorKindOf");BLOCK_RENDER_PART_TYPES=["tool-ui","tool-block_render"],BLOCK_UPDATE_PART_TYPE="tool-block_update",BLOCK_CLOSE_PART_TYPE="tool-block_close";__name(parseChatFormToolPart,"parseChatFormToolPart");ChatFormAnswerItemSchema=z37.object({stepId:ChatFormStepIdSchema.optional(),header:z37.string().min(1).max(25),question:z37.string().min(1).max(500),answer:z37.string().min(1),selectedLabels:z37.array(z37.string().min(1).max(120)).max(8),freeText:z37.string(),skipped:z37.boolean()}),ChatFormAnswerMetadataSchema=z37.object({toolCallId:z37.string().max(255).optional(),shortTitle:z37.string().max(80).optional(),questions:z37.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z37.object({version:z37.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z37.object({version:z37.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z37.string().min(1).max(255),partial:z37.boolean().optional()})}});import{z as z38}from"zod";function waitingBlockType(block2){return block2.type==="form"?"form":block2.type==="callout"&&block2.action.command==="connect"?"connect":null}function waitingBlockTitle(block2){return block2.type==="callout"?block2.title:block2.title??(block2.steps.length===1?block2.steps[0].question:block2.fallback)}function acceptedBlock(part){let output=part.output,parsed=ChatBlockSchema.safeParse(output?.block);return part.state==="output-available"&&output?.rendered===!0&&parsed.success?parsed.data:null}function renderedWaitingBlock(part){let candidate=part;if(!BLOCK_RENDER_PART_TYPES.includes(candidate?.type)||typeof candidate.toolCallId!="string")return null;let form=parseChatFormToolPart(part);if(form)return form.status==="accepted"?{toolCallId:form.toolCallId,block:form.block}:null;let block2=acceptedBlock(candidate);return block2&&waitingBlockType(block2)==="connect"?{toolCallId:candidate.toolCallId,block:block2}:null}function formStepIds(block2){if(block2.type!=="form")return null;let ids=block2.steps.map(step=>step.id);return ids.every(id=>id!==void 0)&&new Set(ids).size===ids.length?ids:null}function reportSource(metadata){let report2=metadata;if(report2?.kind!=="report"||typeof report2.routine?.id!="string"||typeof report2.routine.name!="string")return null;let{threadId,messageId}=report2.run??{};return{routine:{id:report2.routine.id,name:report2.routine.name},...typeof threadId=="string"&&typeof messageId=="string"?{run:{threadId,messageId}}:{}}}function reportSourcesByInvocation(messages){let reports=new Map;for(let message of messages){let source=message.role==="user"&&message.invocationId?reportSource(message.metadata):null;source&&reports.set(message.invocationId,[...reports.get(message.invocationId)??[],source])}return reports}function singleSource(sources){let[first]=sources;return!first||sources.some(source=>source.routine.id!==first.routine.id)?null:sources.length===1?first:{routine:first.routine}}function iso(createdAt){return createdAt===void 0?null:new Date(createdAt).toISOString()}function answeredStepIds(answer){let ids=(answer.questions??[]).flatMap(question=>typeof question?.stepId=="string"?[question.stepId]:[]);return ids.length>0?ids:null}function settleStatus(state,lastClose,answerOrder){state.questions.some(question=>question.status==="waiting")?(state.status="waiting",state.closed=null):state.questions.some(question=>question.status==="closed")?(state.status="closed",state.closed=lastClose??state.closed):(state.status="done",state.closed=null);let first=state.questions.flatMap(question=>question.settled?.kind==="answer"?[question.settled.messageId]:[]).sort((left,right)=>(answerOrder.get(left)??0)-(answerOrder.get(right)??0))[0];state.answerMessageId=state.status==="done"?first??null:null}function getBlockStates(messages){let blocks=new Map,byVersion=new Map,lastClose=new Map,answerOrder=new Map,reports=reportSourcesByInvocation(messages),legacyAnswers=new Map;for(let message of messages){let answer=message.metadata?.questionAnswer;message.role==="user"&&authorKindOf(message)!=="system"&&answer?.toolCallId&&legacyAnswers.set(answer.toolCallId,[...legacyAnswers.get(answer.toolCallId)??[],{answer,messageId:message.id}])}let settleAnswer=__name((state,answer,messageId)=>{if(!state.tracked){var _state;state.status="done",state.closed=null,(_state=state).answerMessageId??(_state.answerMessageId=messageId);return}let named=answeredStepIds(answer),settled=!1;for(let question of state.questions)(named?named.includes(question.id):question.status==="waiting")&&question.settled?.kind!=="answer"&&(question.status="answered",question.settled={kind:"answer",messageId},settled=!0);settled&&(answerOrder.has(messageId)||answerOrder.set(messageId,answerOrder.size),settleStatus(state,lastClose.get(state)??null,answerOrder))},"settleAnswer"),deferred=[],early=new Map,receiveAnswer=__name((state,pending)=>{state.tracked?deferred.push({...pending,state}):settleAnswer(state,pending.answer,pending.messageId)},"receiveAnswer"),addVersion=__name((toolCallId,state)=>{if(byVersion.set(toolCallId,state),!state.tracked)for(let pending of legacyAnswers.get(toolCallId)??[])settleAnswer(state,pending.answer,pending.messageId);for(let pending of early.get(toolCallId)??[])receiveAnswer(state,pending);early.delete(toolCallId)},"addVersion");for(let[index,message]of messages.entries()){if(message.role==="user"){let answer=message.metadata?.questionAnswer;if(!answer?.toolCallId||authorKindOf(message)==="system")continue;let pending={answer,messageId:message.id,index},answered=byVersion.get(answer.toolCallId);answered?receiveAnswer(answered,pending):early.set(answer.toolCallId,[...early.get(answer.toolCallId)??[],pending]);continue}if(message.role!=="assistant")continue;let asked=__name(toolCallId=>({toolCallId,messageId:message.id,invocationId:message.invocationId??null,at:iso(message.createdAt)}),"asked");for(let part of message.parts??[]){let rendered=renderedWaitingBlock(part);if(rendered&&!blocks.has(rendered.toolCallId)){let sources=reports.get(message.invocationId??"")??[],ids=formStepIds(rendered.block),state={id:rendered.toolCallId,type:waitingBlockType(rendered.block),status:"waiting",versions:[{toolCallId:rendered.toolCallId,messageId:message.id,block:rendered.block}],messageId:message.id,askedAt:iso(message.createdAt),source:singleSource(sources),sources,closed:null,answerMessageId:null,tracked:ids!==null,questions:(ids??[]).map(id=>({id,status:"waiting",asked:asked(rendered.toolCallId),settled:null}))};blocks.set(state.id,state),addVersion(state.id,state);continue}let candidate=part;if(!(candidate?.state!=="output-available"||typeof candidate.toolCallId!="string")){if(candidate.type===BLOCK_UPDATE_PART_TYPE){let update=BlockUpdateResultSchema.safeParse(candidate.output),state=update.success?blocks.get(update.data.id):void 0;if(!update.success||state?.status!=="waiting"||waitingBlockType(update.data.block)!==state.type)continue;let block2=update.data.block,ids=formStepIds(block2);if(state.type==="form"&&(state.tracked||ids!==null)){let known=new Map(state.questions.map(question=>[question.id,question]));if(!ids||ids.some(id=>known.has(id)&&known.get(id).status!=="waiting"))continue;for(let question of state.questions)question.status==="waiting"&&!ids.includes(question.id)&&(question.status="removed",question.settled={kind:"update",toolCallId:candidate.toolCallId,messageId:message.id});for(let id of ids)known.has(id)||state.questions.push({id,status:"waiting",asked:asked(candidate.toolCallId),settled:null});state.tracked=!0}state.versions.push({toolCallId:candidate.toolCallId,messageId:message.id,block:block2,reason:update.data.reason}),addVersion(candidate.toolCallId,state)}else if(candidate.type===BLOCK_CLOSE_PART_TYPE){let close=BlockCloseResultSchema.safeParse(candidate.output);if(!close.success)continue;let{closed:_,ids,stepIds,...closed}=close.data;for(let id of ids){let state=blocks.get(id);if(state?.status!=="waiting")continue;if(!state.tracked){state.status="closed",state.closed=closed;continue}let named=ids.length===1?stepIds:void 0;for(let question of state.questions)question.status==="waiting"&&(!named||named.includes(question.id))&&(question.status="closed",question.settled={kind:"close",toolCallId:candidate.toolCallId,messageId:message.id,outcome:closed.outcome,...closed.messageId?{answerMessageId:closed.messageId}:{}});lastClose.set(state,closed),settleStatus(state,closed,answerOrder)}}}}}for(let{state,answer,messageId}of deferred.sort((left,right)=>left.index-right.index))settleAnswer(state,answer,messageId);return[...blocks.values()]}var BLOCK_CLOSE_OUTCOMES,BlockUpdateResultSchema,BlockCloseResultSchema,init_chat_block_state=__esm({"../../packages/api-contracts/dist/esm/types/chat-block-state.js"(){"use strict";init_chat_block();BLOCK_CLOSE_OUTCOMES=["answered_in_chat","done","no_longer_needed"];__name(waitingBlockType,"waitingBlockType");__name(waitingBlockTitle,"waitingBlockTitle");BlockUpdateResultSchema=z38.object({rendered:z38.literal(!0),id:z38.string().min(1),block:ChatBlockSchema,reason:z38.string().optional()}),BlockCloseResultSchema=z38.object({closed:z38.literal(!0),ids:z38.array(z38.string().min(1)).min(1),outcome:z38.enum(BLOCK_CLOSE_OUTCOMES),reason:z38.string(),messageId:z38.string().optional(),stepIds:z38.array(ChatFormStepIdSchema).min(1).optional()});__name(acceptedBlock,"acceptedBlock");__name(renderedWaitingBlock,"renderedWaitingBlock");__name(formStepIds,"formStepIds");__name(reportSource,"reportSource");__name(reportSourcesByInvocation,"reportSourcesByInvocation");__name(singleSource,"singleSource");__name(iso,"iso");__name(answeredStepIds,"answeredStepIds");__name(settleStatus,"settleStatus");__name(getBlockStates,"getBlockStates")}});import{z as z39}from"zod";var AdminTargetSchema,AdminToneSchema,AdminStatusSchema,AdminLinkSchema,AdminActionSchema,BlockBaseSchema2,AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,AdminActionsBlockSchema,AdminHandoffBlockSchema,AdminChatBlockSchema,AdminChatBlockToolInputSchema,init_admin_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/admin-chat-block.js"(){"use strict";init_chat_block();AdminTargetSchema=z39.union([z39.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z39.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z39.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z39.object({label:z39.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z39.object({label:z39.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z39.discriminatedUnion("kind",[BlockSayActionSchema,z39.object({kind:z39.literal("open"),label:z39.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z39.object({kind:z39.literal("op"),label:z39.string().trim().min(1).max(32),operation:z39.string().min(1).max(80),input:z39.record(z39.string(),z39.unknown())}).strict(),z39.object({kind:z39.literal("impersonate"),label:z39.string().trim().min(1).max(32),userId:z39.string().min(1).max(120)}).strict(),z39.object({kind:z39.literal("studio"),label:z39.string().trim().min(1).max(32),projectId:z39.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z39.object({fallback:z39.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z39.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z39.literal("record"),kind:z39.string().trim().min(1).max(24),name:z39.string().trim().min(1).max(80),id:z39.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z39.array(z39.object({label:z39.string().trim().min(1).max(24),value:z39.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z39.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z39.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z39.literal("cards"),items:z39.array(z39.object({name:z39.string().trim().min(1).max(60),subtitle:z39.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z39.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z39.literal("table"),columns:z39.array(z39.object({label:z39.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z39.array(z39.object({cells:z39.array(z39.string().max(80)).min(2).max(3),tone:AdminToneSchema.optional(),target:AdminTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),AdminTimelineBlockSchema=BlockBaseSchema2.extend({type:z39.literal("timeline"),events:z39.array(z39.object({at:z39.string().trim().min(1).max(16),label:z39.string().trim().min(1).max(80),detail:z39.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z39.literal("stats"),items:z39.array(z39.object({label:z39.string().min(1).max(24),value:z39.string().min(1).max(16),delta:z39.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z39.literal("excerpt"),source:z39.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z39.discriminatedUnion("kind",[z39.object({kind:z39.literal("lines"),lines:z39.array(z39.object({text:z39.string().max(200),highlight:z39.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z39.object({kind:z39.literal("message"),author:z39.string().trim().min(1).max(60),at:z39.string().max(24).optional(),text:z39.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z39.literal("media"),items:z39.array(z39.object({url:z39.url({protocol:/^https$/}).max(2e3),alt:z39.string().min(1).max(120),label:z39.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z39.literal("actions"),actions:z39.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z39.literal("handoff"),prompt:z39.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z39.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z39.object({block:AdminChatBlockSchema})}});import{z as z40}from"zod";var CHAT_PORTRAIT_SHAPES,CHAT_PORTRAIT_EYES,CHAT_PORTRAIT_MOUTHS,CHAT_PORTRAIT_COLORS,ChatPortraitSchema,init_chat_portrait=__esm({"../../packages/api-contracts/dist/esm/types/chat-portrait.js"(){"use strict";CHAT_PORTRAIT_SHAPES=["pebble","bean","cloud","drop","potato","mochi","bun","pillow"],CHAT_PORTRAIT_EYES=["dot","caret","ring","shut","small","squint"],CHAT_PORTRAIT_MOUTHS=["smile","grin","o","w"],CHAT_PORTRAIT_COLORS=["red","orange","amber","lime","emerald","teal","sky","blue","indigo","violet","fuchsia","pink"],ChatPortraitSchema=z40.object({shape:z40.enum(CHAT_PORTRAIT_SHAPES),eyes:z40.enum(CHAT_PORTRAIT_EYES),mouth:z40.enum(CHAT_PORTRAIT_MOUTHS),color:z40.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z41}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineDescriptionSchema,ChatRoutineModelSchema,ChatRoutineWaitMinutesSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,AgentHoursUsageDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z41.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z41.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z41.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z41.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z41.string().trim().min(1).max(2e4),ChatRoutineDescriptionSchema=z41.string().trim().min(1).max(500),ChatRoutineModelSchema=z41.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z41.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z41.object({text:z41.string(),title:z41.string(),explanation:z41.string(),watches:z41.array(z41.object({url:z41.string(),health:z41.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z41.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z41.object({text:z41.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z41.object({manual:z41.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z41.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z41.object({message:z41.string().trim().min(1).max(2e4),decision:z41.boolean().optional(),incomplete:z41.boolean().optional(),remaining:z41.number().int().min(0).optional()}).refine(report2=>!(report2.decision===!0&&report2.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}).refine(report2=>!(report2.incomplete===!0&&(report2.remaining??0)>0),{message:"A run that could not check has nothing left to continue: set incomplete or remaining, not both."}),ChatRoutineDTOSchema=z41.object({id:z41.string().uuid(),threadId:z41.string().uuid(),runThreadId:z41.string().uuid(),name:z41.string(),description:z41.string().nullable(),instructions:z41.string(),template:z41.object({key:z41.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z41.string(),modelIsDefault:z41.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z41.boolean(),nextRunAt:z41.string().nullable(),lastRunAt:z41.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string()}),ChatRoutineListDTOSchema=z41.object({routines:z41.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z41.object({usedMs:z41.number().int().min(0),includedMs:z41.number().int().min(0),periodStart:z41.string(),periodEnd:z41.string(),stopsAtIncluded:z41.boolean(),canStart:z41.boolean(),canPayOverage:z41.boolean(),overageRateMicrosPerHour:z41.number().int().nullable(),billedMs:z41.number().int().min(0),billedMicros:z41.number().int().min(0)}),ChatRoutineCreateSchema=z41.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable().optional(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional(),waitMinutes:ChatRoutineWaitMinutesSchema.optional()}),ChatRoutineUpdateSchema=z41.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z41.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z41.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown","routine_needs_pro","routine_is_default"]),ChatRoutineRefusalDTOSchema=z41.object({message:z41.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z41.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z41.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z41.object({kind:z41.enum(["person","agent"]),name:z41.string().nullable()}),ChatRoutineRunDTOSchema=z41.object({messageId:z41.string().uuid(),invocationId:z41.string().uuid().nullable(),startedAt:z41.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z41.string().nullable(),events:z41.number().int().min(1),durationMs:z41.number().int().min(0).nullable(),credits:z41.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z41.object({runs:z41.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z41.object({message:z41.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z41.object({kind:z41.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z41.string().uuid().nullable()})}});import{z as z42}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,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,PublishUpgradeRequiredSchema,ProjectLatestPublicationAttemptSchema,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_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5.5","anthropic/claude-opus-5","anthropic/claude-sonnet-5.5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","anthropic/claude-haiku-5.5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","openai/gpt-6.1-sol","openai/gpt-6-sol","openai/gpt-6-luna","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z42.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z42.string(),displayName:z42.string().nullable(),subdomain:z42.string().nullable().optional(),subdomainUpdatedAt:z42.date().nullable().optional(),organizationId:z42.string().nullable(),createdBy:z42.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z42.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z42.string(),thumbnailUrl:z42.string().nullable(),publishedThumbnailUrl:z42.string().nullable(),category:z42.string().nullable(),snapshotUrl:z42.string().startsWith("/").optional(),appUrl:z42.string().nullable(),lastPublishedAt:z42.coerce.date(),databaseQuotaIncidentId:z42.uuid().nullable().optional(),databaseQuotaLastObservedAt:z42.coerce.date().nullable().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z42.object({name:z42.string().optional(),enabledChatModels:z42.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z42.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z42.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z42.object({id:z42.uuid(),name:z42.string(),displayName:z42.string().nullable(),thumbnailUrl:z42.string().nullable(),category:z42.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),avatar:z42.string().nullable(),color:z42.object({bg:z42.string(),text:z42.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z42.object({path:z42.string(),content:z42.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z42.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z42.object({id:z42.string(),messageId:z42.string(),versionId:z42.string().nullable(),role:ProjectChatMessageRole,parts:z42.array(z42.any()),createdAt:z42.coerce.date()}),MessageUserMetadataSchema=z42.object({id:z42.string(),name:z42.string().nullable().optional(),image:z42.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z42.number(),metadata:z42.object({user:MessageUserMetadataSchema,changeManifest:z42.array(z42.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z42.object({versionId:z42.uuid(),commitHash:z42.string(),name:z42.string(),description:z42.string().nullable(),kind:z42.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z42.object({versionCount:z42.number().int().nonnegative(),snapshotBytes:z42.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z42.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z42.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z42.object({content:z42.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z42.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z42.object({success:z42.boolean(),message:z42.string().optional(),warning:z42.string().optional(),durationMs:z42.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z42.object({code:z42.literal("PUBLISH_UPGRADE_REQUIRED"),message:z42.string(),currentVersion:z42.number().int().positive(),targetVersion:z42.literal(4)}),ProjectLatestPublicationAttemptSchema=z42.object({publicationId:z42.uuid(),status:z42.enum(["queued","building","published","failed","canceled"]),failureCode:z42.string().nullable(),sourceBranch:z42.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z42.object({isPublished:z42.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z42.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z42.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z42.object({label:z42.string().trim().min(1).max(120).optional(),notes:z42.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z42.object({success:z42.boolean(),message:z42.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z42.boolean(),publicationId:z42.string().optional(),url:z42.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z43}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,CHAT_SEARCH_MAX_LIMIT,ChatSearchQuerySchema,ChatSearchHitDTOSchema,ChatSearchResultDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatInstructionsSchema,ProjectChatDTOSchema,ProjectChatListDTOSchema,ProjectChatCreatedDTOSchema,ProjectChatTitleSchema,ProjectChatCreateSchema,ProjectChatUpdateSchema,ChatTemplateRoutineScheduleDTOSchema,ChatTemplateRoutineDTOSchema,ChatTemplateDTOSchema,ChatTemplateListDTOSchema,ProjectChatStateSchema,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_chat_portrait();init_create_dto();init_response();init_chat_routine_dto();init_organization_features_dto();init_project_dto();ChatMessageListDTOSchema=z43.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z43.object({items:z43.array(ProjectMessagePublicDTOSchema),nextCursor:z43.string().nullable()}),ChatLiveTurnDTOSchema=z43.object({invocationId:z43.string(),step:z43.enum(["preparing","working","compacting","merging"]),startedAt:z43.string(),continuesInvocationId:z43.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z43.object({threadId:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z43.object({kind:z43.enum(["person","agent","routine","system"]),id:z43.string().nullable()}),ChatThreadMessageDTOSchema=z43.object({id:z43.string(),role:z43.enum(["user","assistant"]),parts:z43.array(z43.unknown()),metadata:z43.record(z43.string(),z43.unknown()).nullable(),versionId:z43.string().nullable().optional(),createdAt:z43.date().transform(value=>value.toISOString()),providerMessageId:z43.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z43.string().nullable().optional(),invocationStatus:z43.string().nullable().optional(),invocationTerminalReason:z43.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z43.object({id:z43.string(),parts:z43.array(z43.unknown()),metadata:z43.record(z43.string(),z43.unknown()).nullable(),providerMessageId:z43.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z43.boolean(),queuedAt:z43.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z43.object({type:z43.literal("merge_conflict"),merge:z43.object({mergeId:z43.string().uuid(),projectId:z43.string(),fromBranch:z43.string(),toBranch:z43.string()}),publishAfterMerge:z43.boolean()}),ChatThreadMessagesPageDTOSchema=z43.object({threadId:z43.string().nullable(),title:z43.string().nullable(),messages:z43.array(ChatThreadMessageDTOSchema),nextCursor:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z43.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z43.boolean().optional(),queueWaitUntil:z43.string().nullable().optional()}),CHAT_SEARCH_MAX_LIMIT=50,ChatSearchQuerySchema=z43.object({projectId:z43.string(),query:z43.string().trim().min(1).max(500),chatId:z43.string().uuid().optional(),after:z43.iso.datetime({offset:!0}).optional(),before:z43.iso.datetime({offset:!0}).optional(),limit:z43.coerce.number().int().min(1).max(CHAT_SEARCH_MAX_LIMIT).default(10)}).strict(),ChatSearchHitDTOSchema=z43.object({chatId:z43.string().uuid(),chatTitle:z43.string().nullable(),messageId:z43.string().uuid(),role:z43.string(),authorKind:ChatMessageAuthorDTOSchema.shape.kind,createdAt:z43.string(),snippet:z43.string()}),ChatSearchResultDTOSchema=z43.object({hits:z43.array(ChatSearchHitDTOSchema)}),ChatReplayOutcomeDTOSchema=z43.object({kind:z43.literal("replay"),threadId:z43.string(),userMessageId:z43.string()}),ChatQueuedOutcomeDTOSchema=z43.object({kind:z43.literal("queued"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string().optional()}),ChatBusyOutcomeDTOSchema=z43.object({kind:z43.literal("busy"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string().optional()}),ChatRefusedOutcomeDTOSchema=z43.object({kind:z43.literal("refused"),threadId:z43.string(),userMessageId:z43.string(),refusedInvocationId:z43.string(),terminalReason:z43.string()}),ChatNonStreamingOutcomeDTOSchema=z43.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z43.enum(["chat","agent","routine","task","draft"]),ProjectChatCreatableKindSchema=z43.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z43.object({quietRuns:z43.number().int().nonnegative(),since:z43.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z43.string().nullable(),nextRunAt:z43.string().nullable(),wakesOnChanges:z43.boolean()}),ProjectChatDescriptionSchema=z43.string().trim().max(2e3),ProjectChatInstructionsSchema=z43.string().trim().max(8e3),ProjectChatDTOSchema=z43.object({id:z43.string().uuid(),kind:ProjectChatKindSchema,title:z43.string().nullable(),description:z43.string().nullable(),instructions:z43.string().nullable(),liveAt:z43.string().nullable(),template:z43.string().nullable(),parentThreadId:z43.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z43.string(),lastMessageAt:z43.string().nullable(),preview:z43.string().nullable(),running:z43.boolean(),awaitingAnswer:z43.boolean(),unread:z43.boolean(),pinned:z43.boolean(),archived:z43.boolean(),muted:z43.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z43.object({chats:z43.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z43.object({id:z43.string().uuid()}),ProjectChatTitleSchema=z43.string().trim().min(1).max(120),ProjectChatCreateSchema=z43.object({id:z43.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z43.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema,setup:z43.literal(!0),locale:z43.string().trim().min(2).max(16)}).partial().refine(create=>create.template===void 0||create.kind===void 0&&create.title===void 0&&create.description===void 0,"A template brings its own kind, title and description").refine(create=>create.setup===void 0||create.kind==="agent","Only an agent is set up in its chat"),ProjectChatUpdateSchema=z43.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,instructions:ProjectChatInstructionsSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.instructions!==void 0||update.portrait!==void 0,"Set a title, a description, instructions or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z43.object({cron:z43.string()}),ChatTemplateRoutineDTOSchema=z43.object({name:z43.string(),description:z43.string(),instructions:z43.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z43.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z43.object({id:z43.string(),name:z43.string(),summary:z43.string(),description:z43.string(),greeting:z43.string(),starters:z43.array(z43.string()),portrait:ChatPortraitSchema,plans:z43.array(AgentPlanSchema),routines:z43.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z43.object({templates:z43.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z43.object({read:z43.boolean(),pinned:z43.boolean(),archived:z43.boolean(),muted:z43.boolean()}).partial().refine(state=>Object.keys(state).length>0,"Set at least one of read, pinned, archived or muted"),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema)}});import{z as z44}from"zod";var ADMIN_ASSISTANT_BASE_PATH,ADMIN_ASSISTANT_PATHS,ADMIN_ASSISTANT_MESSAGE_MAX_CHARS,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS,ADMIN_ASSISTANT_REQUEST_MAX_BYTES,AdminAssistantFormResponseSchema,AdminAssistantOutgoingMessageSchema,AdminAssistantSendRequestSchema,AdminAssistantSendOutcomeSchema,AdminAssistantStreamHeadSchema,AdminAssistantThreadSummarySchema,AdminAssistantThreadListQuerySchema,AdminAssistantThreadListResponseSchema,AdminAssistantThreadResponseSchema,AdminAssistantLiveTurnResponseSchema,AdminAssistantAbortResponseSchema,AdminAssistantThreadUpdateSchema,AdminAssistantThreadDeleteResponseSchema,init_admin_assistant=__esm({"../../packages/api-contracts/dist/esm/types/admin-assistant.js"(){"use strict";init_chat_dto();init_chat_block();ADMIN_ASSISTANT_BASE_PATH="/api/ops/assistant",ADMIN_ASSISTANT_PATHS={chat:`${ADMIN_ASSISTANT_BASE_PATH}/chat`,threads:`${ADMIN_ASSISTANT_BASE_PATH}/threads`,thread:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}`,"thread"),live:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/live`,"live"),stream:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/stream`,"stream"),abort:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/abort`,"abort")},ADMIN_ASSISTANT_MESSAGE_MAX_CHARS=2e4,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS=4e3,ADMIN_ASSISTANT_REQUEST_MAX_BYTES=256*1024,AdminAssistantFormResponseSchema=ChatFormResponseSchema.extend({questions:z44.array(ChatFormAnswerItemSchema.extend({answer:z44.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z44.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z44.object({id:z44.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z44.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z44.object({threadId:z44.string().uuid().optional(),message:AdminAssistantOutgoingMessageSchema,formResponse:AdminAssistantFormResponseSchema.optional()}).strict().superRefine((body,context)=>{body.message.text.trim().length===0&&!body.formResponse&&context.addIssue({code:"custom",path:["message","text"],message:"A message cannot be empty."})}),AdminAssistantSendOutcomeSchema=z44.discriminatedUnion("kind",[z44.object({kind:z44.literal("replay"),threadId:z44.string(),userMessageId:z44.string()}),z44.object({kind:z44.literal("queued"),threadId:z44.string(),userMessageId:z44.string(),blockingRootId:z44.string().optional()}),z44.object({kind:z44.literal("busy"),threadId:z44.string(),userMessageId:z44.string(),blockingRootId:z44.string().optional()}),z44.object({kind:z44.literal("refused"),threadId:z44.string(),userMessageId:z44.string(),refusedInvocationId:z44.string(),terminalReason:z44.string()})]),AdminAssistantStreamHeadSchema=z44.object({kind:z44.literal("turn"),threadId:z44.string(),userMessageId:z44.string(),invocationId:z44.string()}),AdminAssistantThreadSummarySchema=z44.object({id:z44.string().uuid(),title:z44.string().nullable(),lastMessageAt:z44.string().nullable(),createdAt:z44.string()}),AdminAssistantThreadListQuerySchema=z44.object({q:z44.string().trim().max(200).optional(),cursor:z44.string().max(500).optional(),limit:z44.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z44.object({threads:z44.array(AdminAssistantThreadSummarySchema),nextCursor:z44.string().nullable()}),AdminAssistantThreadResponseSchema=z44.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z44.string().nullable()}),messages:z44.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z44.object({threadId:z44.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z44.object({aborted:z44.boolean()}),AdminAssistantThreadUpdateSchema=z44.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z44.object({deleted:z44.literal(!0)})}});import{z as z45}from"zod";function normalizeStoredBlock(block2){if(typeof block2!="object"||block2===null||Array.isArray(block2))return block2;let{type,...rest}=block2;if(typeof type!="string")return block2;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block2}function normalizeStoredBlocks(blocks){return Array.isArray(blocks)?blocks.map(normalizeStoredBlock):blocks}function normalizeStoredDocument(document){if(typeof document!="object"||document===null||Array.isArray(document))return document;let source=document;return{...source,brief:normalizeStoredBlocks(source.brief),details:normalizeStoredBlocks(source.details)}}function derivedBlockBody(block2){let lines=[];switch(block2.type){case"text":lines.push(block2.text);break;case"metric":for(let item of block2.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block2.points.map(point=>`${point.label}: ${formatReportValue(point.value,block2.unit)}`).join(", ")),block2.caption&&lines.push(block2.caption);break;case"list":for(let item of block2.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(block2.columns.map(column=>column.label).join(" | "));for(let row2 of block2.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block2.caption&&lines.push(block2.caption);break;case"media":lines.push(block2.alt),block2.caption&&lines.push(block2.caption);break;case"links":for(let item of block2.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block2.code),block2.caption&&lines.push(block2.caption);break}return lines.join(`
6
- `)}function reportSectionContentLength(blocks){return blocks.reduce((total,block2)=>total+(block2.title?.length??0)+derivedBlockBody(block2).length+(block2.fallback?.length??0),0)}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}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,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,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=z45.enum(REPORT_TONES),blockCommon={title:z45.string().trim().min(1).max(120).optional(),fallback:z45.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z45.object({type:z45.literal("text"),...blockCommon,text:z45.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=z45.object({type:z45.literal("metric"),...blockCommon,items:z45.array(z45.object({value:z45.string().trim().min(1).max(24),unit:z45.string().trim().min(1).max(12).optional(),label:z45.string().trim().min(1).max(160),note:z45.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z45.array(z45.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z45.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z45.object({type:z45.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z45.string().trim().min(1).max(12).optional(),points:z45.array(z45.object({label:z45.string().trim().min(1).max(24),value:z45.number().finite(),highlight:z45.boolean().optional()}).strict()).min(2).max(24),caption:z45.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((block2,ctx)=>{block2.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block2.kind==="composition"&&block2.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z45.object({type:z45.literal("list"),...blockCommon,items:z45.array(z45.object({tone:ReportToneSchema.optional(),label:z45.string().trim().min(1).max(24).optional(),heading:z45.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z45.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z45.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z45.object({type:z45.literal("table"),...blockCommon,columns:z45.array(z45.object({label:z45.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z45.array(z45.object({cells:z45.array(z45.object({text:z45.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block2,ctx)=>{block2.rows.forEach((row2,index)=>{row2.cells.length!==block2.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block2.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z45.object({type:z45.literal("media"),...blockCommon,assetId:z45.uuid(),alt:z45.string().trim().min(1).max(300),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z45.object({type:z45.literal("links"),...blockCommon,items:z45.array(z45.object({label:z45.string().trim().min(1).max(120),url:z45.url({protocol:/^https$/}).max(2e3),description:z45.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z45.object({type:z45.literal("code"),...blockCommon,language:z45.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z45.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z45.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z45.object({title:z45.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z45.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z45.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=z45.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z45.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z45.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z46}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=z46.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z46.object({dev:z46.string().trim().min(1).optional(),build:z46.string().trim().min(1).optional(),install:z46.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z46.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z46.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z46.object({type:z46.enum(["header","cookie","query","host"]),key:z46.string().min(1).optional(),value:z46.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:z46.array(FimoHostingConditionSchema).min(1).optional(),missing:z46.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z46.object({source:z46.string().min(1),destination:z46.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z46.object({source:z46.string().min(1),destination:z46.string().min(1),permanent:z46.boolean().optional(),statusCode:z46.union([z46.literal(301),z46.literal(302),z46.literal(307),z46.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z46.object({source:z46.string().min(1),headers:z46.array(z46.object({key:z46.string().min(1),value:z46.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z46.object({rewrites:z46.array(FimoHostingRewriteSchema).optional(),redirects:z46.array(FimoHostingRedirectSchema).optional(),headers:z46.array(FimoHostingHeaderSchema).optional(),cleanUrls:z46.boolean().optional(),trailingSlash:z46.boolean().optional()}).strict(),FimoAppConfigSchema=z46.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 isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52,params){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param)&&params?.[param]?.type!=="external")}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";__name(isEntryParamBinding,"isEntryParamBinding");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")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z47}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,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();ProjectBranchStatusSchema=z47.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z47.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z47.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z47.string().nullable(),deletedAt:z47.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z47.object({id:z47.union([z47.literal(PREVIEW_ENVIRONMENT_KEY),z47.uuid()]),name:z47.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z47.object({sessionId:z47.uuid(),name:z47.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z47.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z47.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z47.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z47.object({surface:z47.enum(["code","schemas","content","translations","assets","forms"]),status:z47.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z47.number().int().nonnegative(),conflictCount:z47.number().int().nonnegative()}),BranchDiffResultSchema=z47.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z47.coerce.date(),surfaces:z47.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z48}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=z48.object({projectId:z48.uuid(),name:z48.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z48.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z48.literal("production"),sourceBranch:BranchSchema,isPublished:z48.boolean(),url:z48.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z48.literal(PREVIEW_ENVIRONMENT_KEY),kind:z48.literal("preview"),matchedBranchCount:z48.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z48.literal("custom"),matchedBranchCount:z48.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z48.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z48.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z48.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z48.object({deletedId:z48.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z49}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectVariableBaseSchema,ProjectVariableDTOSchema,ProjectVariableDTO,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=z49.object({kind:z49.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z49.object({kind:z49.enum(["variable","secret"]),value:z49.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z49.string().min(1).max(255),exposure:z49.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z49.object({kind:z49.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),key:z49.string(),kind:z49.literal("secret"),exposure:z49.literal("private"),environment:EnvironmentKeySchema,maskedValue:z49.string().optional(),createdAt:z49.date().transform(value=>value.toISOString()),updatedAt:z49.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),key:z49.string(),kind:z49.literal("variable"),environment:EnvironmentKeySchema,managed:z49.boolean(),createdAt:z49.date().transform(value=>value.toISOString()),updatedAt:z49.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z49.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z49.literal("public"),value:z49.string()}),ProjectVariableBaseSchema.extend({exposure:z49.literal("private"),maskedValue:z49.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z49.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z50}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=z50.object({success:z50.literal(!0),downloadUrl:z50.string(),expiresAt:z50.string(),fileSize:z50.number(),duration:z50.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z50.object({success:z50.literal(!0),projectId:z50.string(),projectName:z50.string(),displayName:z50.string(),projectUrl:z50.string(),duration:z50.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z50.object({contentTypes:z50.number(),entries:z50.number(),assets:z50.number(),translations:z50.number(),forms:z50.number(),codeFiles:z50.number(),assetFiles:z50.number()}),ImportPreviewSurfaceDTOSchema=z50.object({name:z50.string(),included:z50.boolean(),count:z50.number().optional(),note:z50.string().optional()}),ImportPreviewDTOSchema=z50.object({projectName:z50.string(),displayName:z50.string().nullable(),category:z50.string().nullable(),exportedAt:z50.string(),version:z50.string(),envScope:z50.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z50.array(ImportPreviewSurfaceDTOSchema),fileSize:z50.number(),fileName:z50.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z50.object({success:z50.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z51}from"zod";var AgentSessionStatusSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,SessionErrorCodeSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentSessionStatusSchema=z51.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z51.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z51.object({capturedAt:z51.coerce.date(),fingerprint:z51.string().min(1).max(256),counts:z51.object({code:z51.number().int().nonnegative(),content:z51.number().int().nonnegative(),schemas:z51.number().int().nonnegative(),labels:z51.number().int().nonnegative(),assets:z51.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z51.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z51.object({diff:DiffReportSchema,code:z51.array(CodeFileDiffSchema.extend({raw:z51.string().max(24576)})).max(200),schemas:z51.array(SchemaTypeDiffSchema).max(200),content:z51.array(z51.object({key:z51.string().min(1).max(512),collection:z51.string().min(1).max(256),slug:z51.string().max(512).optional(),verb:z51.enum(["added","modified","deleted"]),fields:z51.array(z51.object({name:z51.string().min(1).max(256),before:z51.unknown().optional(),after:z51.unknown().optional()})).max(20)})).max(200),labels:z51.array(z51.object({key:z51.string().min(1).max(512),locale:z51.string().min(1).max(64).optional(),before:z51.unknown().nullable(),after:z51.unknown().nullable()})).max(200),assets:z51.array(z51.object({key:z51.string().min(1).max(512),name:z51.string().min(1).max(512),verb:z51.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z51.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z52}from"zod";var AskDraftChangeRequestSchema,RewriteDraftWordsRequestSchema,DraftChangeStateQuerySchema,DraftChangeStateSchema,ApproveProposalRequestSchema,ProposalApprovalStateQuerySchema,init_draft_change_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/draft-change.dto.js"(){"use strict";AskDraftChangeRequestSchema=z52.object({projectId:z52.uuid(),reviewId:z52.uuid(),entryId:z52.string().min(1).max(120),contentTypeName:z52.string().min(1).max(120),field:z52.string().min(1).max(120),quote:z52.string().min(1).max(2e4).optional(),locale:z52.string().min(1).max(35).optional(),message:z52.string().trim().min(1).max(4e3),providerMessageId:z52.string().min(1).max(200)}),RewriteDraftWordsRequestSchema=AskDraftChangeRequestSchema.extend({format:z52.enum(["rich","plain"]),words:z52.string().min(1).max(4e4),surroundingText:z52.string().max(2e4).optional()}),DraftChangeStateQuerySchema=z52.object({projectId:z52.uuid(),reviewId:z52.uuid()}),DraftChangeStateSchema=z52.object({busy:z52.boolean(),reply:z52.string().nullable()}),ApproveProposalRequestSchema=z52.object({projectId:z52.uuid(),proposalId:z52.uuid(),providerMessageId:z52.string().min(1).max(200),message:z52.string().trim().min(1).max(200),threadId:z52.uuid().optional()}),ProposalApprovalStateQuerySchema=z52.object({projectId:z52.uuid(),proposalId:z52.uuid(),threadId:z52.uuid().optional()})}});import{z as z53}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=z53.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z53.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=z53.object({description:z53.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z53.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z53.array(z53.uuid()).optional()}),AgentQuestionSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),threadId:z53.uuid(),invocationId:z53.uuid(),agentKey:z53.string().min(1).max(120),anchorEnv:z53.string().min(1).max(64),retainedEnv:z53.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z53.string().min(1).nullable(),continuationInvocationId:z53.uuid().nullable(),askedAt:z53.coerce.date(),expiresAt:z53.coerce.date(),closedAt:z53.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z53.object({questionId:z53.uuid(),invocationId:z53.uuid(),askedAt:z53.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z53.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z53.object({question:AgentQuestionSchema,continuationInvocationId:z53.uuid(),deduped:z53.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z54}from"zod";var AgentQuestionFollowUpRequestSchema,AgentQuestionFollowUpSchema,AgentQuestionFollowUpDTO,init_agent_question_follow_up_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question-follow-up.dto.js"(){"use strict";init_create_dto();AgentQuestionFollowUpRequestSchema=z54.object({projectId:z54.uuid(),agentId:z54.uuid(),recipientEmail:z54.email().max(320)}).strict(),AgentQuestionFollowUpSchema=z54.object({projectId:z54.uuid(),agentId:z54.uuid(),eligible:z54.boolean(),reason:z54.enum(["ready","no_pending_questions","incomplete_coverage","unavailable"]),agentPendingQuestions:z54.number().int().nonnegative().nullable(),projectPendingQuestions:z54.number().int().nonnegative().nullable(),agentLegacyPendingForms:z54.number().int().nonnegative().nullable(),projectLegacyPendingForms:z54.number().int().nonnegative().nullable(),agentPendingCoverage:z54.enum(["complete","partial","unknown"]),projectPendingCoverage:z54.enum(["complete","partial","unknown"]),snapshotAt:z54.iso.datetime().nullable()}),AgentQuestionFollowUpDTO=createDTO(AgentQuestionFollowUpSchema)}});import{z as z55}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,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=z55.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z55.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z55.enum(["secret_text"]),IntegrationCredentialUsageSchema=z55.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z55.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z55.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z55.object({mode:IntegrationAuthModeSchema,label:z55.string().min(1),description:z55.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z55.object({id:z55.string().min(1),label:z55.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z55.boolean()}),IntegrationToolDefinitionDTOSchema=z55.object({key:z55.string().min(1),name:z55.string().min(1),description:z55.string().min(1),effect:IntegrationToolEffectSchema,input:z55.record(z55.string(),z55.unknown()).optional()}),IntegrationRecipeDTOSchema=z55.object({title:z55.string().min(1),description:z55.string().min(1),command:z55.string().min(1).optional()}),IntegrationInfoDTOSchema=z55.object({key:z55.string().min(1),name:z55.string().min(1),summary:z55.string().min(1),type:z55.enum(["native","mcp"]).optional(),url:z55.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z55.array(IntegrationAuthModeDTOSchema),credentials:z55.array(IntegrationCredentialDefinitionDTOSchema),tools:z55.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z55.enum(["available","unavailable"]).optional(),connectionCapabilities:z55.object({customIdentityCreation:z55.boolean()}).optional(),recipes:z55.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z55.object({projectId:z55.uuid(),integrationKey:z55.string().min(1),name:z55.string().min(1),summary:z55.string().min(1),installed:z55.boolean(),enabled:z55.boolean(),setupState:z55.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z55.string().nullable(),connectionId:z55.uuid().nullable().optional(),connectionAlias:z55.string().min(1).nullable().optional(),connectionStatus:z55.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z55.array(z55.string()),installedAt:z55.coerce.date().nullable(),updatedAt:z55.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z55.object({id:z55.uuid(),projectId:z55.uuid(),integrationKey:z55.string().min(1),enabled:z55.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z55.string(),connectionId:z55.uuid().nullable().optional(),connectionAlias:z55.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z55.array(z55.string()),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z55.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z55.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z55.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z55.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z55.object({id:z55.uuid(),organizationId:z55.string().min(1),integrationKey:z55.string().min(1),registrationId:z55.uuid().nullable(),alias:z55.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z55.string().min(1),externalAccountName:z55.string().nullable(),externalBotUserId:z55.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z55.array(z55.string()),connectedAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z55.boolean(),isDefault:z55.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z55.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z55.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z55.record(McpHeaderNameSchema,z55.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z55.object({alias:z55.string().min(1).max(120).optional(),token:z55.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z55.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=z55.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z55.object({displayName:z55.string().trim().min(1).max(35),backgroundColor:z55.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z55.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z55.discriminatedUnion("mode",[z55.object({mode:z55.literal("personal"),alias:z55.string().min(1).max(120),token:z55.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z55.boolean().optional()}),z55.object({mode:z55.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z55.boolean().optional(),registrationId:z55.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),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=z55.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z55.union([z55.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z55.object({type:z55.literal("mcp"),name:z55.string().trim().min(1).max(120),url:z55.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z55.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z55.string().min(1).optional(),integrationId:z55.string().min(2).max(80).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=z55.object({integrationKey:z55.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z55.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z55.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z55.literal("oauth"),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()})]),ReusableMcpServerAuthKindSchema=z55.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z55.object({id:z55.uuid(),name:z55.string().min(1),host:z55.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z55.string().min(1),availability:z55.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z55.object({query:z55.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z55.object({serverId:z55.uuid()}),LinearOAuthApplicationDistributionSchema=z55.enum(["private","public"]),OrganizationLinearAppDTOSchema=z55.object({id:z55.uuid(),displayName:z55.string().min(1),description:z55.string().nullable(),iconUrl:z55.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z55.enum(["active","revoked","disconnected"]),connectionIds:z55.array(z55.uuid()),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z55.object({appName:z55.string().trim().min(2).max(80),description:z55.string().trim().max(1e3).optional(),iconUrl:z55.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z55.object({projectId:z55.uuid(),registrationId:z55.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z55.object({integrationKey:z55.string().min(1),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z55.discriminatedUnion("mode",[z55.object({mode:z55.literal("personal"),integrationKey:z55.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z55.object({mode:z55.literal("oauth"),integrationKey:z55.string().min(1),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()})]),BindProjectChannelRequestSchema=z55.object({ref:z55.string().min(1),connectionAlias:z55.string().min(1).optional(),agentName:z55.string().min(1).max(160).nullable().optional(),force:z55.boolean().optional()}),ListProjectChannelsQuerySchema=z55.object({integrationKey:z55.string().min(1)}),SearchProjectChannelsQuerySchema=z55.object({integrationKey:z55.string().min(1),connectionAlias:z55.string().min(1),query:z55.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z55.object({id:z55.uuid(),projectId:z55.uuid(),integrationKey:z55.string().min(1),connectionId:z55.uuid(),externalWorkspaceId:z55.string().min(1),externalChannelId:z55.string().min(1),externalChannelName:z55.string().nullable(),agentName:z55.string().nullable(),enabled:z55.boolean(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z55.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z55.object({id:z55.string().min(1),name:z55.string().min(1),visibility:z55.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z55.string().min(1).nullable(),canMove:z55.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z55.object({markdown:z55.boolean().optional(),summary:z55.boolean().optional(),links:z55.boolean().optional(),branding:z55.boolean().optional(),images:z55.boolean().optional(),html:z55.union([z55.literal("cleaned"),z55.literal("raw"),z55.boolean()]).optional(),json:z55.union([z55.boolean(),z55.object({prompt:z55.string().min(1).max(1e4),schema:z55.record(z55.string(),z55.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z55.object({url:z55.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional(),waitForMs:z55.number().int().min(0).max(3e4).optional(),maxAgeMs:z55.number().int().min(0).optional(),minAgeMs:z55.number().int().min(0).optional(),storeInCache:z55.boolean().optional(),proxy:z55.enum(["basic","enhanced","auto"]).optional(),mobile:z55.boolean().optional(),location:z55.object({country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z55.array(z55.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z55.object({query:z55.string().min(1),maxResults:z55.number().int().positive().max(20).optional(),sources:z55.array(z55.enum(["web","news","images"])).min(1).max(3).optional(),categories:z55.array(z55.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z55.enum(["hour","day","week","month","year"]).optional(),location:z55.string().min(1).max(160).optional(),country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z55.object({query:z55.string().min(1).max(500),maxResults:z55.number().int().min(1).max(100).optional(),types:z55.array(z55.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z55.array(z55.string().min(1).max(512)).min(1).max(20).optional(),sources:z55.array(z55.string().min(1).max(512)).min(1).max(20).optional(),passages:z55.number().int().min(1).max(5).optional(),skills:z55.literal("only").optional(),language:z55.string().min(1).optional(),topic:z55.string().min(1).optional(),license:z55.string().min(1).optional(),minStars:z55.number().int().min(0).optional(),maxStars:z55.number().int().min(0).optional(),archived:z55.boolean().optional(),fork:z55.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z55.object({query:z55.string().min(1).max(500),maxResults:z55.number().int().min(1).max(500).optional(),authors:z55.array(z55.string().min(1)).min(1).optional(),categories:z55.array(z55.string().min(1)).min(1).optional(),from:z55.iso.date().optional(),to:z55.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z55.object({paperId:z55.string().min(1).max(512),query:z55.string().min(1).max(500).optional(),maxPassages:z55.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z55.object({paperId:z55.string().min(1).max(512),intent:z55.string().min(1).max(500),mode:z55.enum(["similar","citers","references"]).optional(),maxResults:z55.number().int().min(1).max(500).optional(),rerank:z55.boolean().optional(),anchors:z55.array(z55.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z55.object({url:z55.string().url(),search:z55.string().min(1).optional(),limit:z55.number().int().positive().max(200).optional(),includeSubdomains:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z55.object({url:z55.string().url(),limit:z55.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z55.object({text:z55.string().min(1).max(200).optional(),cron:z55.string().min(1).max(120).optional(),timezone:z55.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z55.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional(),waitForMs:z55.number().int().min(0).max(3e4).optional(),maxAgeMs:z55.number().int().min(0).optional(),minAgeMs:z55.number().int().min(0).optional(),storeInCache:z55.boolean().optional(),proxy:z55.enum(["basic","enhanced","auto"]).optional(),mobile:z55.boolean().optional(),location:z55.object({country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z55.array(z55.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z55.union([z55.object({type:z55.enum(["scrape","crawl"]).default("scrape"),urls:z55.array(z55.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z55.object({type:z55.literal("search"),queries:z55.array(z55.string().min(1).max(256)).min(1).max(12),searchWindow:z55.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z55.number().int().min(1).max(50).optional(),includeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z55.object({name:z55.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z55.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z55.string().min(1).max(2e3).optional(),judgeEnabled:z55.boolean().optional(),retentionDays:z55.number().int().min(1).max(365).optional(),notification:z55.object({email:z55.object({enabled:z55.boolean().default(!0),recipients:z55.array(z55.string().email()).min(1).max(20),includeDiffs:z55.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=z55.object({monitorId:z55.string().uuid(),name:z55.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z55.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z55.string().min(1).max(2e3).optional(),judgeEnabled:z55.boolean().optional(),retentionDays:z55.number().int().min(1).max(365).optional(),status:z55.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z55.object({monitorId:z55.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z55.string().uuid()}),RunProjectIntegrationToolRequestSchema=z55.object({tool:z55.string().min(1),input:z55.record(z55.string(),z55.unknown()),connectionAlias:z55.string().min(1).optional(),approval:z55.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z55.object({provider:z55.string().min(1),providerCredits:z55.number().nonnegative().optional(),providerCostUsd:z55.number().nonnegative().optional(),requests:z55.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z55.object({credits:z55.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),title:z55.string().optional(),statusCode:z55.number().optional(),markdown:z55.string().optional(),summary:z55.string().optional(),links:z55.array(z55.string()).optional(),images:z55.array(z55.string()).optional(),html:z55.string().optional(),json:z55.unknown().optional(),branding:z55.record(z55.string(),z55.unknown()).optional(),warning:z55.string().optional()}),FirecrawlSearchToolOutputSchema=z55.object({query:z55.string(),provider:z55.literal("firecrawl"),warning:z55.string().optional(),results:z55.array(z55.object({title:z55.string(),url:z55.string(),snippet:z55.string().optional(),content:z55.string().optional(),score:z55.number().optional(),publishedAt:z55.string().optional()}))}),FirecrawlResearchPaperSchema=z55.object({paperId:z55.string(),primaryId:z55.string().optional(),ids:z55.record(z55.string(),z55.array(z55.string())).optional(),title:z55.string().optional(),abstract:z55.string().optional(),score:z55.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z55.object({text:z55.string(),score:z55.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(z55.object({id:z55.string(),type:z55.string().min(1).optional(),url:z55.string(),title:z55.string().optional(),passages:z55.array(z55.object({text:z55.string()}).passthrough())}).passthrough()),coverage:z55.record(z55.string(),z55.string()).optional(),reranked:z55.boolean().optional(),repos:z55.array(z55.record(z55.string(),z55.unknown())).optional(),sources:z55.array(z55.record(z55.string(),z55.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),paper:z55.record(z55.string(),z55.unknown()),paperId:z55.string().optional(),query:z55.string().optional(),passages:z55.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(FirecrawlResearchPaperSchema),poolSize:z55.number().int().nonnegative(),truncated:z55.boolean(),note:z55.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),count:z55.number(),links:z55.array(z55.object({url:z55.string(),title:z55.string().optional(),description:z55.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),total:z55.number(),pages:z55.array(z55.object({url:z55.string(),title:z55.string().optional(),statusCode:z55.number().optional(),markdown:z55.string().optional(),summary:z55.string().optional(),links:z55.array(z55.string()).optional(),images:z55.array(z55.string()).optional(),html:z55.string().optional(),warning:z55.string().optional()})),warning:z55.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z55.object({cron:z55.string().optional(),text:z55.string().optional(),timezone:z55.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z55.object({id:z55.string().optional(),type:z55.enum(["scrape","crawl","search"]).optional(),urls:z55.array(z55.string()).optional(),queries:z55.array(z55.string()).optional(),searchWindow:z55.string().optional(),maxResults:z55.number().optional(),includeDomains:z55.array(z55.string()).optional(),excludeDomains:z55.array(z55.string()).optional(),scrapeOptions:z55.record(z55.string(),z55.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z55.object({id:z55.string(),name:z55.string(),status:z55.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z55.string().nullable().optional(),lastRunAt:z55.string().nullable().optional(),currentCheckId:z55.string().nullable().optional(),targets:z55.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z55.string().nullable().optional(),judgeEnabled:z55.boolean().optional(),estimatedCreditsPerMonth:z55.number().optional(),createdAt:z55.string().optional(),updatedAt:z55.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z55.object({id:z55.string(),monitorId:z55.string(),scheduledFor:z55.string().nullable().optional(),startedAt:z55.string().nullable().optional(),finishedAt:z55.string().nullable().optional(),estimatedCredits:z55.number().nullable().optional(),reservedCredits:z55.number().nullable().optional(),actualCredits:z55.number().nullable().optional(),billingStatus:z55.string().nullable().optional(),summary:z55.object({totalPages:z55.number().optional(),same:z55.number().optional(),changed:z55.number().optional(),new:z55.number().optional(),removed:z55.number().optional(),error:z55.number().optional()}).passthrough().optional(),error:z55.string().nullable().optional(),createdAt:z55.string().optional(),updatedAt:z55.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitors:z55.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),deleted:z55.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),checks:z55.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),check:FirecrawlMonitorCheckOutputSchema,next:z55.string().optional()}),FirecrawlToolKeySchema=z55.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=z55.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z55.object({projectId:z55.uuid(),integrationKey:z55.string().min(1),tool:z55.string().min(1),connectionAlias:z55.string().min(1).nullable().optional(),output:z55.record(z55.string(),z55.unknown()),executedAt:z55.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z55.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z55.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z55.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z55.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z55.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z55.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z55.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z55.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z55.array(ProjectChannelCandidateDTOSchema))}});import{z as z56}from"zod";var IntegrationIdSchema,IntegrationScopeSchema,IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema,IntegrationAuthSchema,IntegrationRecipeSchema,IntegrationSettingSchema,IntegrationToolsSchema,IntegrationSkillSchema,IntegrationManifestSchema,IntegrationPermissionDTOSchema,IntegrationSettingDefinitionDTOSchema,IntegrationKindSchema,IntegrationSummaryDTOSchema,IntegrationAccountDTOSchema,IntegrationSiteDTOSchema,OrganizationIntegrationDTOSchema,ProjectIntegrationDTOSchema,IntegrationReturnPathSchema,StartIntegrationInstallRequestSchema,StartIntegrationInstallDTOSchema,AddOrganizationMcpServerDTOSchema,ConnectIntegrationKeyRequestSchema,ReplaceIntegrationServerCredentialsRequestSchema,UpdateIntegrationSiteRequestSchema,UpdateIntegrationSitesRequestSchema,UpdateProjectIntegrationSettingsRequestSchema,IntegrationSettingOptionDTOSchema,IntegrationToolMatchDTOSchema,ProjectIntegrationGuideDTOSchema,APPROVAL_TOKEN_MAX,REQUEST_TOKEN_MAX,RunIntegrationToolRequestSchema,IntegrationApprovalCallShape,IntegrationToolRunResultDTOSchema,IntegrationApprovalPreviewRequestSchema,IntegrationApprovalPreviewDTOSchema,RoutineIntegrationApprovalSchema,IntegrationApprovalDecisionSchema,DecideIntegrationApprovalRequestSchema,IntegrationApprovalDecisionDTOSchema,IntegrationAgentAccessDTOSchema,init_integration_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration-catalog.dto.js"(){"use strict";init_integration_dto();IntegrationIdSchema=z56.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z56.strictObject({scope:z56.string().min(1),reason:z56.string().min(1).max(200)}),IntegrationOAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("oauth"),actor:z56.literal("user").default("user"),authorizationUrl:z56.url(),tokenUrl:z56.url(),revocationUrl:z56.url().optional(),userInfoUrl:z56.url().optional(),client:z56.strictObject({idEnv:z56.string().min(1),secretEnv:z56.string().min(1)}),authorizeParams:z56.record(z56.string(),z56.string()).default({}),scopes:z56.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("apiKey"),keyLabel:z56.string().min(1).max(80),placeholder:z56.string().min(1).max(40).optional(),helpUrl:z56.url()}),IntegrationProviderAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("provider")}),IntegrationMcpAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("mcp"),methods:z56.array(McpIntegrationSetupAuthSchema).min(1),scopes:z56.array(z56.string().min(1)).min(1).optional(),header:z56.object({name:z56.string().min(1).max(80),valuePrefix:z56.string().max(80)}).optional()}),IntegrationAuthSchema=z56.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z56.strictObject({title:z56.string().min(1).max(80),description:z56.string().min(1).max(300),command:z56.string().min(1).optional()}),IntegrationSettingSchema=z56.strictObject({type:z56.enum(["string","choice"]),label:z56.string().min(1).max(80),description:z56.string().min(1).max(300).optional(),required:z56.boolean().default(!1),optionsFrom:z56.strictObject({tool:z56.string().min(1)}).optional()}),IntegrationToolsSchema=z56.discriminatedUnion("source",[z56.strictObject({source:z56.literal("hosted")}),z56.strictObject({source:z56.literal("mcp"),url:z56.url()})]),IntegrationSkillSchema=z56.strictObject({name:z56.string().min(1).max(64),description:z56.string().min(1).max(300),content:z56.string().min(1)}),IntegrationManifestSchema=z56.strictObject({apiVersion:z56.literal(1),id:IntegrationIdSchema,version:z56.string().regex(/^\d+\.\d+\.\d+$/),listing:z56.strictObject({name:z56.string().min(1).max(60),description:z56.string().min(1).max(200),details:z56.string().min(1).max(1e3),icon:z56.string().min(1),category:z56.enum(["seo","ai-visibility","analytics","communication"]),publisher:z56.string().min(1).max(60),agentReads:z56.strictObject({label:z56.string().min(1).max(80),description:z56.string().min(1).max(200)}).optional()}),auth:z56.array(IntegrationAuthSchema).min(1),identity:z56.strictObject({label:z56.string().min(1)}).optional(),settings:z56.record(z56.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z56.array(IntegrationSkillSchema).default([]),recipes:z56.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z56.object({scope:z56.string(),reason:z56.string()}),IntegrationSettingDefinitionDTOSchema=z56.object({key:z56.string(),type:z56.enum(["string","choice"]),label:z56.string(),description:z56.string().nullable(),required:z56.boolean(),hasOptions:z56.boolean()}),IntegrationKindSchema=z56.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z56.object({id:z56.string(),kind:IntegrationKindSchema,integrationKey:z56.string(),host:z56.string().nullable(),apiKey:z56.object({label:z56.string(),placeholder:z56.string().nullable(),helpUrl:z56.string(),primary:z56.boolean()}).nullable(),mcp:z56.object({url:z56.string(),methods:z56.array(McpIntegrationSetupAuthSchema),header:z56.object({name:z56.string(),valuePrefix:z56.string()}).nullable()}).nullable(),name:z56.string(),description:z56.string(),details:z56.string(),icon:z56.string(),category:z56.string(),publisher:z56.string(),signInLabel:z56.string(),permissions:z56.array(IntegrationPermissionDTOSchema),readOnly:z56.boolean(),settings:z56.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z56.object({connectionId:z56.uuid(),alias:z56.string(),accountName:z56.string().nullable(),status:z56.enum(["active","revoked"]),authKind:z56.enum(["oauth","api_key"]),connectedAt:z56.coerce.date()}),IntegrationSiteDTOSchema=z56.object({projectId:z56.uuid(),projectName:z56.string(),enabled:z56.boolean(),granted:z56.boolean(),connectionId:z56.uuid().nullable(),settings:z56.record(z56.string(),z56.string()),missingSettings:z56.array(z56.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z56.boolean(),accounts:z56.array(IntegrationAccountDTOSchema),siteAccess:z56.enum(["all","selected"]),sites:z56.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z56.boolean(),enabled:z56.boolean(),granted:z56.boolean(),accountName:z56.string().nullable(),settingsValues:z56.record(z56.string(),z56.string()),missingSettings:z56.array(z56.string()),tools:z56.array(z56.object({key:z56.string(),name:z56.string(),description:z56.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z56.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z56.object({projectId:z56.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z56.object({connectUrl:z56.url().nullable(),expiresAt:z56.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z56.string()}),ConnectIntegrationKeyRequestSchema=z56.object({key:z56.string().trim().min(1).max(500),projectId:z56.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z56.object({token:z56.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z56.object({enabled:z56.boolean(),connectionId:z56.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z56.object({access:z56.enum(["all","selected"]).optional(),projectIds:z56.array(z56.uuid()).max(1e3),connectionId:z56.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z56.object({settings:z56.record(z56.string(),z56.string().max(500))}),IntegrationSettingOptionDTOSchema=z56.object({value:z56.string(),label:z56.string(),suggested:z56.boolean()}),IntegrationToolMatchDTOSchema=z56.object({integrationId:z56.string(),integrationName:z56.string(),key:z56.string(),name:z56.string(),description:z56.string(),effect:IntegrationToolEffectSchema,input:z56.record(z56.string(),z56.unknown())}),ProjectIntegrationGuideDTOSchema=z56.object({integrationId:z56.string(),name:z56.string(),description:z56.string(),content:z56.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z56.object({tool:z56.string().min(1).max(120),input:z56.record(z56.string(),z56.unknown()).default({}),approval:z56.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z56.boolean().optional()}),IntegrationApprovalCallShape={integration:z56.object({id:z56.string(),name:z56.string()}),tool:z56.object({key:z56.string(),name:z56.string(),effect:IntegrationToolEffectSchema}),input:z56.record(z56.string(),z56.unknown()),reason:z56.string(),canAlwaysAllow:z56.boolean()},IntegrationToolRunResultDTOSchema=z56.discriminatedUnion("status",[z56.object({status:z56.literal("ok"),output:z56.record(z56.string(),z56.unknown())}),z56.object({status:z56.literal("approval_required"),request:z56.string(),approveUrl:z56.string(),...IntegrationApprovalCallShape}),z56.object({status:z56.literal("blocked"),reason:z56.string()})]),IntegrationApprovalPreviewRequestSchema=z56.object({request:z56.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z56.object({...IntegrationApprovalCallShape,allowOnce:z56.boolean(),expiresAt:z56.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z56.string()}),IntegrationApprovalDecisionSchema=z56.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z56.object({request:z56.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z56.object({decision:IntegrationApprovalDecisionSchema,approval:z56.string().optional(),resumed:z56.boolean().optional()}),IntegrationAgentAccessDTOSchema=z56.object({reads:z56.object({label:z56.string(),description:z56.string()}).nullable(),tools:z56.array(z56.object({tool:z56.string(),label:z56.string(),description:z56.string(),allowed:z56.boolean()}))})}});import{z as z57}from"zod";var CodeSyncProviderSchema,CodeSyncAvailabilityDTOSchema,CodeSyncAvailabilityDTO,CodeSyncStatusSchema,CodeSyncErrorCodeSchema,CodeSyncAccountSchema,CodeSyncRepositorySchema,CodeSyncBranchStatusSchema,CodeSyncBranchDTOSchema,CodeSyncConnectionDTOSchema,CodeSyncConnectionDTO,CodeSyncDTOSchema,CodeSyncDTO,CreateCodeSyncConnectionRequestSchema,CreateCodeSyncRepositoryRequestSchema,ActivateCodeSyncConnectionRequestSchema,AuthorizeCodeSyncResponseSchema,CodeSyncJobSchema,init_code_sync_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/code-sync.dto.js"(){"use strict";init_create_dto();CodeSyncProviderSchema=z57.enum(["github"]),CodeSyncAvailabilityDTOSchema=z57.object({enabled:z57.boolean()}),CodeSyncAvailabilityDTO=createDTO(CodeSyncAvailabilityDTOSchema),CodeSyncStatusSchema=z57.enum(["connecting","choose_repository","creating","creation_unknown","access_required","checking_branches","waiting_for_code","partial","syncing","up_to_date","error","stopping"]),CodeSyncErrorCodeSchema=z57.enum(["access_required","conflict","rejected","unavailable","unsupported","limit","creation_unknown","creation_failed","authorization_expired","project_changed","configuration","source_missing","source_changed"]),CodeSyncAccountSchema=z57.object({installationId:z57.number().int().positive(),login:z57.string(),type:z57.enum(["User","Organization"])}),CodeSyncRepositorySchema=z57.object({id:z57.number().int().positive(),name:z57.string(),fullName:z57.string(),url:z57.string().url(),visibility:z57.enum(["private","public"])}),CodeSyncBranchStatusSchema=z57.enum(["pending","syncing","up_to_date","waiting_for_code","conflict","error","retired"]),CodeSyncBranchDTOSchema=z57.object({id:z57.string().uuid(),branchName:z57.string(),status:CodeSyncBranchStatusSchema,errorCode:CodeSyncErrorCodeSchema.nullable(),expectedHead:z57.string().nullable(),pendingTarget:z57.string().nullable(),lastSyncedAt:z57.string().datetime().nullable(),nextAttemptAt:z57.string().datetime()}),CodeSyncConnectionDTOSchema=z57.object({id:z57.string().uuid(),provider:CodeSyncProviderSchema,status:CodeSyncStatusSchema,repository:CodeSyncRepositorySchema.nullable(),accountLogin:z57.string().nullable(),accounts:z57.array(CodeSyncAccountSchema),installUrl:z57.string().url().nullable(),installationSettingsUrl:z57.string().url().nullable(),nextAttemptAt:z57.string().datetime(),errorCode:CodeSyncErrorCodeSchema.nullable(),branches:z57.array(CodeSyncBranchDTOSchema),counts:z57.object({total:z57.number().int().nonnegative(),upToDate:z57.number().int().nonnegative(),conflicts:z57.number().int().nonnegative(),pending:z57.number().int().nonnegative(),errors:z57.number().int().nonnegative(),waiting:z57.number().int().nonnegative()})}),CodeSyncConnectionDTO=createDTO(CodeSyncConnectionDTOSchema),CodeSyncDTOSchema=z57.object({providers:z57.array(z57.object({id:CodeSyncProviderSchema,available:z57.boolean()})),connections:z57.array(CodeSyncConnectionDTOSchema)}),CodeSyncDTO=createDTO(CodeSyncDTOSchema),CreateCodeSyncConnectionRequestSchema=z57.object({provider:CodeSyncProviderSchema}).strict(),CreateCodeSyncRepositoryRequestSchema=z57.object({installationId:z57.number().int().positive(),repositoryName:z57.string().trim().min(1).max(100).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(name=>name!=="."&&name!==".."&&!name.endsWith(".git")),visibility:z57.enum(["private","public"]).default("private")}).strict(),ActivateCodeSyncConnectionRequestSchema=z57.object({installationId:z57.number().int().positive(),repositoryId:z57.number().int().positive()}).strict(),AuthorizeCodeSyncResponseSchema=z57.object({url:z57.string().url()}),CodeSyncJobSchema=z57.object({version:z57.literal(2),connectionId:z57.string().uuid(),connectionGeneration:z57.string().uuid(),siteGeneration:z57.string().uuid()}).strict()}});import{z as z58}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,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=z58.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z58.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z58.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z58.object({userId:z58.string().min(1),name:z58.string(),email:z58.string().min(1),subscribed:z58.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z58.object({maxSubscribers:z58.number().int().positive(),subscriberCount:z58.number().int().nonnegative(),effectiveRecipientCount:z58.number().int().nonnegative(),currentUserSubscribed:z58.boolean(),candidates:z58.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z58.object({userIds:z58.array(z58.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z58.object({topic:UserManagedNotificationTopicSchema,enabled:z58.boolean(),source:z58.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z58.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z58.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z58.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z58.string().nullable(),maskedEmail:z58.string().min(1),applied:z58.boolean(),expiresAt:z58.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z58.object({scheduleId:z58.string().min(1),scheduleName:z58.string(),projectId:z58.string().min(1),projectName:z58.string(),env:z58.string().min(1)}),FollowedSchedulesSchema=z58.object({schedules:z58.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z59}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=z59.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=z59.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z59.uuid(),env:z59.string().min(1),name:z59.string().min(1),cron:z59.string().min(1),command:z59.string().min(1),secretKeys:z59.array(z59.string().min(1)),enabled:z59.boolean(),lastRunAt:z59.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z59.string().nullable(),suspendedAt:z59.coerce.date().nullable().optional(),suspensionReason:z59.string().nullable().optional(),overPolicyReasons:z59.array(z59.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z59.object({name:z59.string().min(1).max(120),cron:z59.string().min(1).max(120),command:z59.string().min(1).max(500),secretKeys:z59.array(ProjectSecretKeySchema).default([]),enabled:z59.boolean().optional()}),UpdateProjectScheduleRequestSchema=z59.object({name:z59.string().min(1).max(120).optional(),cron:z59.string().min(1).max(120).optional(),command:z59.string().min(1).max(500).optional(),secretKeys:z59.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z59.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z59.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z59.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z59.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z59.object({maxRuns:z59.number().int().positive(),retentionDays:z59.number().int().positive().nullable(),outputRetentionDays:z59.number().int().positive(),maxOutputBytes:z59.number().int().positive()}),SchedulePolicyStateSchema=z59.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z59.object({code:z59.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z59.enum(["cached_subscription","free_fallback"]),activeSchedules:z59.object({used:z59.number().int().nonnegative(),limit:z59.number().int().nonnegative()}),minCadenceMinutes:z59.number().int().positive(),maxRunMs:z59.number().int().positive(),concurrency:z59.object({used:z59.number().int().nonnegative(),limit:z59.number().int().positive()}),compute:z59.object({settledMs:z59.number().int().nonnegative(),activeMs:z59.number().int().nonnegative(),reservedMs:z59.number().int().nonnegative().optional(),includedMs:z59.number().int().nonnegative(),remainingMs:z59.number().int().nonnegative(),resetsAt:z59.coerce.date()}),upgrade:z59.object({code:z59.literal("Pro"),activeSchedulesLimit:z59.number().int().positive(),minCadenceMinutes:z59.number().int().positive(),maxRunMs:z59.number().int().positive(),maxConcurrentRuns:z59.number().int().positive(),computeIncludedMs:z59.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z59.array(z59.string())}),ProjectScheduleUsageSchema=z59.object({runCount:z59.number().int().nonnegative(),runsWithOutput:z59.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z59.object({id:z59.uuid(),scheduleId:z59.uuid(),projectId:z59.uuid(),env:z59.string().min(1),scheduleName:z59.string().min(1),command:z59.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z59.object({id:z59.string().min(1),name:z59.string().min(1)}).nullable(),queuedAt:z59.coerce.date(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),exitCode:z59.number().int().nullable(),errorCode:z59.string().nullable(),error:z59.string().nullable(),outputBytes:z59.number().int().nonnegative(),outputTruncated:z59.boolean(),outputExpiresAt:z59.coerce.date().nullable(),metadataExpiresAt:z59.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z59.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z59.coerce.date().nullable(),items:z59.array(z59.object({key:z59.string().min(1),updatedAt:z59.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z59.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z59.object({trigger:z59.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z59.object({limit:z59.coerce.number().int().min(1).max(100).default(25),cursor:z59.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z59.object({items:z59.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z59.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z59.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z59.object({items:z59.array(ProjectScheduleRunDTOSchema),nextCursor:z59.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z60}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z60.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z60.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z60.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z60.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z60.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z60.discriminatedUnion("kind",[z60.object({kind:z60.literal("user"),userId:z60.string().min(1)}).strict(),z60.object({kind:z60.literal("agent"),agentKey:z60.string().min(1).max(120),agentId:z60.uuid().optional()}).strict(),z60.object({kind:z60.literal("system")}).strict()]),NotificationSummarySchema=z60.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z60.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z60.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z60.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z60.object({sessionId:z60.uuid(),branch:z60.string().min(1),targetBranch:z60.string().min(1),revision:z60.string().min(1),fingerprint:z60.string().min(1)}),NotificationPayloadSchema=z60.discriminatedUnion("topic",[z60.object({topic:z60.literal("database_quota_exceeded"),incidentId:z60.uuid(),observedAt:z60.iso.datetime()}).strict(),z60.object({topic:z60.literal("agent_run_outcome"),threadId:z60.uuid(),invocationId:z60.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("agent_retained_review"),threadId:z60.uuid().optional(),invocationId:z60.uuid().optional(),proposalId:z60.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("agent_conflict"),mergeId:z60.uuid(),threadId:z60.uuid().optional(),invocationId:z60.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("publication_failed"),publicationId:z60.uuid(),sourceBranch:z60.string().trim().min(1).max(120),failureCode:z60.string().trim().min(1).max(64),failedAt:z60.iso.datetime(),firstPublication:z60.boolean()}).strict()]),NotificationEnvelopeSchema=z60.object({id:z60.uuid(),projectId:z60.uuid(),sourceKey:z60.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z60.literal(1),payload:NotificationPayloadSchema,createdAt:z60.coerce.date()}),NotificationDeliveryStateSchema=z60.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z60.object({id:z60.uuid(),notificationRecipientId:z60.uuid(),projectId:z60.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z60.number().int().nonnegative(),nextAttemptAt:z60.coerce.date().nullable(),lastAttemptAt:z60.coerce.date().nullable(),sentAt:z60.coerce.date().nullable(),failureCode:z60.string().max(80).nullable(),createdAt:z60.coerce.date(),updatedAt:z60.coerce.date()}),NotificationPreferenceSchema=z60.object({topic:WorkNotificationTopicSchema,channel:z60.literal("email"),enabled:z60.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z60.enum(["default","explicit"])})}});import{z as z61}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","publishing","schedule","marketing"],NotificationPreferenceGroupSchema=z61.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","schedule.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z61.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z61.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z61.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z61.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z61.object({enabled:z61.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z61.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z61.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z61.discriminatedUnion("kind",[z61.object({kind:z61.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z61.enum(["work_review","publishing","schedule"]),enabled:z61.boolean(),source:PreferenceSourceSchema}).strict(),z61.object({kind:z61.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z61.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z61.object({kind:z61.literal("provider_subscription"),id:z61.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z61.literal("marketing"),name:z61.string(),description:z61.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z61.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z61.object({email:EmailNotificationPreferenceSchema,entries:z61.array(NotificationPreferenceEntrySchema),unavailableGroups:z61.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z61.object({enabled:z61.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z61.discriminatedUnion("kind",[z61.object({kind:z61.literal("toggle"),enabled:z61.boolean()}).strict(),z61.object({kind:z61.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z61.object({kind:z61.literal("provider_subscription"),enabled:z61.boolean()}).strict()])}});import{z as z62}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=z62.object({surface:SurfaceNameSchema,key:z62.string(),label:z62.string()}),InlineSchema=z62.object({text:z62.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z62.discriminatedUnion("type",[z62.object({type:z62.literal("paragraph"),content:z62.array(InlineSchema).max(24)}),z62.object({type:z62.literal("preview"),ref:DiffRefSchema,caption:z62.string().optional()}),z62.object({type:z62.literal("code"),code:z62.string(),lang:z62.string().optional(),caption:z62.string().optional()}),z62.object({type:z62.literal("risk"),level:z62.enum(["warning","error"]),content:z62.array(InlineSchema).max(24)}),z62.object({type:z62.literal("list"),items:z62.array(z62.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z62.object({headline:z62.string(),blocks:z62.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z62.object({summary:EnvDiffSummarySchema,fingerprint:z62.string(),generatedAt:z62.coerce.date(),cached:z62.boolean().optional(),credits:z62.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z63}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z63.object({date:z63.string(),visitors:z63.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z63.object({key:z63.string(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z63.object({path:z63.string(),pageName:z63.string().nullable().optional(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z63.object({preset:z63.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z63.string(),requestedTo:z63.string(),effectiveFrom:z63.string(),effectiveTo:z63.string(),isRetentionLimited:z63.boolean(),groupBy:z63.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z63.object({date:z63.string(),content:z63.string(),updatedAt:z63.string(),updatedByUserId:z63.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z63.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z63.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative(),botPageviews:z63.number().int().nonnegative(),botVisitors:z63.number().int().nonnegative(),bounceRate:z63.number().min(0).max(100),viewsPerVisit:z63.number().nonnegative(),averageVisitDurationSeconds:z63.number().nonnegative(),visitorsSeries:z63.array(ProjectDailyVisitorsDTOSchema),topPages:z63.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z63.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z63.object({state:z63.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z63.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z64}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=z64.object({id:z64.string(),email:z64.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z64.coerce.date(),createdAt:z64.coerce.date(),inviterUserId:z64.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z64.object({id:z64.string(),token:z64.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z64.object({success:z64.boolean(),projectId:z64.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z65}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=z65.object({id:z65.string(),name:z65.string(),image:z65.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z65.object({count:z65.int(),canRefer:z65.boolean(),eligibleAt:z65.iso.datetime().nullable()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z65.object({counts:z65.object({signed_up:z65.int(),activated:z65.int()}),credits:z65.object({total:z65.int(),earned:z65.int()}),canRefer:z65.boolean(),eligibleAt:z65.iso.datetime().nullable()}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z65.email(),emailVerified:z65.boolean(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z66}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=z66.object({id:z66.string(),principalType:ProjectPrincipalTypeSchema,principalId:z66.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z66.coerce.date(),expiresAt:z66.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z66.boolean().default(!1)}),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","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","locale:add","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","branch:create","environment:create","integration:manage","integration:run","sync:code","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z66.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z66.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z66.record(z66.string(),z66.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z66.object({access:z66.array(ProjectAccessItemDTOSchema),invites:z66.array(ProjectInviteDTOSchema),organization:z66.object({name:z66.string().nullable(),logo:z66.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z66.object({success:z66.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z66.object({success:z66.boolean(),projectId:z66.uuid()}))}});import{z as z67}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=z67.object({publicationStatus:PublicationStatusSchema,appUrl:z67.string().nullable(),lastPublishedAt:z67.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z68}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z68.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z68.object({branch:BranchSchema,revision:z68.string().min(1).max(64).nullable(),generation:z68.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z68.url().nullable()})}});import{z as z69}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewStartFailureSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewUpgradeRequiredSchema=z69.object({code:z69.literal("PREVIEW_UPGRADE_REQUIRED"),message:z69.string(),currentVersion:z69.number().int().positive(),targetVersion:z69.literal(4)}),PreviewBridgePackageSchema=z69.object({name:z69.string().min(1),version:z69.string().min(1)}),PreviewBridgeCapabilitySchema=z69.object({integrated:z69.boolean(),packages:z69.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z69.object({url:z69.url(),expiresAt:z69.iso.datetime().nullable(),source:z69.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z69.object({name:z69.string().min(1),locator:z69.string().min(1).optional(),source:z69.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z69.object({kind:z69.literal("dependency_build_scripts_blocked"),packageManager:z69.enum(["pnpm","yarn","bun"]),packages:z69.array(z69.string()),targets:z69.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z69.string(),approvalKey:z69.string(),command:z69.string().optional(),approval:z69.object({id:z69.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z69.object({code:z69.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z69.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z69.object({code:z69.literal("PREVIEW_START_FAILED"),message:z69.string(),logTail:z69.array(z69.string()).optional(),logTailTruncated:z69.boolean().optional()}),SandboxPullPhaseSchema=z69.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z69.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z69.object({message:z69.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z69.number().int().optional().catch(void 0),logTail:z69.array(z69.string()).optional().catch(void 0),logTailTruncated:z69.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z69.object({approvalId:z69.uuid()}),PreviewInstallPolicyApprovalEventSchema=z69.discriminatedUnion("type",[z69.object({type:z69.literal("progress"),step:z69.enum(["approval","install","restart","readiness"]),message:z69.string()}),z69.object({type:z69.literal("approved")}),z69.object({type:z69.literal("complete")}),z69.object({type:z69.literal("error"),code:z69.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z69.string()})])}});import{z as z70}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,OrganizationProjectCapacityDTOSchema,OrganizationProjectCapacityDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z70.string(),slug:z70.string().nullable(),logo:z70.string().nullable(),metadata:z70.record(z70.string(),z70.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z70.object({id:z70.string(),name:z70.string(),email:z70.email(),image:z70.string().nullable()}),OrganizationMemberDTOSchema=z70.object({id:z70.string(),userId:z70.string(),organizationId:z70.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z70.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z70.object({canCreateProject:z70.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z71}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z71.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z71.object({reason:CancellationReasonCodeSchema,details:z71.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z71.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z71.object({offerVersion:z71.string().trim().min(1),unusedPremiumCreditAmount:z71.number().int().nonnegative(),amountDueNow:z71.number().int().nonnegative(),renewsOn:z71.string()}),PlanMigrationPreviewDTOSchema=z71.object({currency:z71.string().trim().min(1),unusedPremiumCreditAmount:z71.number().int().nonnegative(),amountDueNow:z71.number().int().nonnegative(),startsAt:z71.string(),renewsAt:z71.string(),nextRenewalAmount:z71.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z71.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z71.object({id:z71.string(),organizationId:z71.string(),legacySubscriptionId:z71.string(),offeredPlanCode:z71.string(),offeredPlanName:z71.string(),offeredPriceAmount:z71.number(),offeredCurrency:z71.string(),offerVersion:z71.string(),state:PlanMigrationStateSchema,checkoutToken:z71.string().nullable(),deadlineAt:z71.string(),transitions:z71.array(z71.object({event:z71.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z71.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z71.object({included:z71.number().optional(),unitPrice:z71.number().optional(),dailyCap:z71.number().nullable().optional()}),EntitlementsDTOSchema=z71.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z71.object({retentionDays:z71.number().int().positive(),canUseExtendedDateRanges:z71.boolean()}).optional(),history:z71.object({retentionDays:z71.number().int().positive()}).optional(),members:z71.object({canInvite:z71.boolean(),maxMembers:z71.number().int().positive().nullable()}).optional(),projects:z71.object({maxProjects:z71.number().int().positive().nullable()}).optional(),domains:z71.object({canUseCustomDomains:z71.boolean(),maxDomains:z71.number().int().nonnegative().nullable()}).optional(),media_storage:z71.object({limitBytes:z71.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z71.object({usedBytes:z71.number().int().nonnegative().nullable(),limitBytes:z71.number().int().nonnegative().nullable(),state:z71.enum(["ready","unavailable"]),measuredAt:z71.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z71.object({toPlanCode:TemplateCodeSchema,effectiveAt:z71.string(),scheduledAt:z71.string().nullable()}),AutomaticSpendStopDTOSchema=z71.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z71.string(),spendStopped:z71.boolean(),settlementEndsAt:z71.string()}),HostingOverageStatusDTOSchema=z71.object({state:z71.enum(["ready","unavailable"]),planCode:z71.string(),overageAvailable:z71.boolean(),overageEnabled:z71.boolean(),monthlyCapUsd:z71.number().int().positive().nullable(),periodStart:z71.iso.datetime().nullable(),periodEnd:z71.iso.datetime().nullable(),usedBytes:z71.number().nonnegative().nullable(),includedBytes:z71.number().nonnegative().nullable(),overageBytes:z71.number().nonnegative(),currentOverageAmountMicros:z71.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z71.number().nonnegative().nullable(),currency:z71.string().nullable(),status:z71.enum(["ok","near_limit","paused"]),databaseCompute:z71.object({includedHoursPerSite:z71.number().nonnegative().nullable(),overageHours:z71.number().nonnegative(),fundedHours:z71.number().nonnegative(),sitesOverAllowance:z71.number().int().nonnegative(),rateMicrosPerHour:z71.number().nonnegative().nullable(),amountMicros:z71.number().nonnegative().nullable(),budgetSpent:z71.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z71.object({enabled:z71.boolean(),monthlyCapUsd:z71.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z71.object({id:z71.string(),external_id:z71.string(),customerId:z71.string(),planId:z71.string(),planCode:z71.union([TemplateCodeSchema,z71.literal("Unknown")]),currentPeriod:z71.object({start:z71.string(),end:z71.string().nullable()}),cancelAt:z71.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z71.string(),nextPaymentAt:z71.string().nullable(),baseAmount:z71.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z71.object({totalCap:z71.number(),dailyCap:z71.number(),usedTotal:z71.number()}),CreditBalanceDTOSchema=z71.object({total:z71.number(),base:z71.number(),dailyBase:z71.number(),purchases:z71.number(),awards:z71.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z71.object({total:z71.number(),nearLimit:z71.boolean(),canChat:z71.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z71.object({dailyFreeAvailable:z71.number(),monthlyAvailable:z71.number(),purchasedAvailable:z71.number(),awardedAvailable:z71.number()}),ProjectDailyCreditAllowanceDTOSchema=z71.object({periodCap:z71.number(),dailyGrant:z71.number(),usedThisPeriod:z71.number(),remainingThisPeriod:z71.number()}),ProjectCreditBalanceDTOSchema=z71.object({projectId:z71.uuid(),organizationId:z71.string(),balance:z71.object({totalAvailable:z71.number(),nearLimit:z71.boolean(),canUseAi:z71.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z71.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z71.discriminatedUnion("enabled",[z71.object({enabled:z71.literal(!0),thresholdUsd:z71.number().nonnegative(),refillAmountUsd:z71.number().nonnegative()}),z71.object({enabled:z71.literal(!1),thresholdUsd:z71.number().nonnegative().nullable(),refillAmountUsd:z71.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z71.discriminatedUnion("enabled",[z71.object({enabled:z71.literal(!0),thresholdUsd:z71.number().min(.01).multipleOf(.01),refillAmountUsd:z71.number().min(.01).multipleOf(.01),expectedRateToken:z71.string().trim().min(1).max(40)}).strict(),z71.object({enabled:z71.literal(!1),thresholdUsd:z71.number().min(.01).multipleOf(.01),expectedRateToken:z71.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z71.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z71.object({planCode:z71.union([TemplateCodeSchema,z71.literal("Unknown")]).nullable(),canPurchase:z71.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z71.number().int().positive(),minAmountUsd:z71.number().positive(),maxAmountUsd:z71.number().positive(),rateToken:z71.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z71.object({amountUsd:z71.number(),idempotencyKey:z71.string().trim().min(8).max(120),expectedRateToken:z71.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z71.object({invoiceId:z71.string(),newBalance:z71.int(),creditCount:z71.int(),amountUsd:z71.number(),creditsPerDollar:z71.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z71.object({url:z71.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z71.object({id:z71.string(),number:z71.string().nullable(),status:z71.string(),amountDue:z71.int(),currency:z71.string(),issuedAt:z71.string().nullable(),hostedInvoiceUrl:z71.string().nullable()}),PaymentRecoveryDTOSchema=z71.discriminatedUnion("status",[z71.object({status:z71.literal("eligible"),checkedAt:z71.string()}),z71.object({status:z71.literal("recovery_required"),checkedAt:z71.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z71.int().min(1)}),z71.object({status:z71.literal("unavailable"),checkedAt:z71.string(),reason:z71.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),CreditPurchasePricingResponseSchema=createResponseSchema(CreditPurchasePricingDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema),PaymentRecoveryResponseSchema=createResponseSchema(PaymentRecoveryDTOSchema)}});import{z as z72}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=z72.object({brand:z72.string(),last4:z72.string(),exp:z72.string(),isDefault:z72.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z73}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=z73.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z73.object({type:z73.literal("renameField"),contentType:z73.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z73.object({enabled:z73.boolean()}).strict(),ContentFieldGroupSchema=z73.object({id:z73.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z73.string().min(1).max(255),default:z73.boolean().optional()}).strict(),ContentTypeDTOSchema=z73.object({id:z73.string(),name:z73.string(),label:z73.string(),isSingleton:z73.boolean(),i18n:ContentTypeI18nSchema,description:z73.string().nullable().default(null),groups:z73.array(ContentFieldGroupSchema).default([]),fields:z73.record(z73.string(),FieldDefinitionSchema),createdAt:z73.string(),updatedAt:z73.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z73.object({contentTypes:z73.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z73.object({id:z73.string(),entryId:z73.string(),documentId:z73.string(),slug:z73.string(),locale:z73.string().optional(),createdAt:z73.string(),updatedAt:z73.string(),__fimo:z73.object({contentType:z73.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z73.object({data:z73.array(EntryDTOSchema),meta:z73.object({limit:z73.number(),offset:z73.number(),total:z73.number(),hasMore:z73.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z73.object({contentType:z73.string(),count:z73.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z73.object({counts:z73.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z73.object({count:z73.number().int().nonnegative(),sourceLocale:z73.string(),targetLocale:z73.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z73.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z73.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z73.union([z73.string(),z73.number(),z73.boolean(),z73.null()]),entryWhereOperatorSchema=z73.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z73.array(entryWhereScalarSchema).optional(),$nin:z73.array(entryWhereScalarSchema).optional(),$contains:z73.string().optional(),$startsWith:z73.string().optional(),$null:z73.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z73.record(z73.string(),z73.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z73.record(z73.string(),z73.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z73.object({data:z73.record(z73.string(),z73.unknown()),locale:z73.string().min(1).optional(),documentId:z73.uuid().optional()}),entryIdsSchema=z73.array(z73.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z73.object({sql:z73.string().min(1)}),BulkCreateEntriesRequestSchema=z73.object({entries:z73.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z73.union([z73.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z73.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z73.object({updates:z73.array(z73.object({id:z73.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z73.union([z73.object({ids:entryIdsSchema,locale:z73.string().min(1).optional()}),z73.object({where:EntryWhereSchema,locale:z73.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z73.object({data:z73.array(z73.record(z73.string(),z73.unknown())),meta:z73.object({rowCount:z73.number().int().nonnegative(),truncated:z73.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z73.object({data:z73.array(EntryDTOSchema),meta:z73.object({created:z73.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z73.object({data:z73.array(EntryDTOSchema),meta:z73.object({updated:z73.number().int().nonnegative(),missing:z73.array(z73.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z73.object({data:z73.array(EntryDTOSchema),meta:z73.object({deleted:z73.number().int().nonnegative(),missing:z73.array(z73.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z74}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z74.object({index:z74.number().int().nonnegative(),contentType:z74.string(),field:z74.string(),value:z74.string(),against:z74.enum(["stored","batch"]),ownerDocumentId:z74.uuid().optional(),ownerIndex:z74.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z74.object({code:z74.literal("unique_conflict"),message:z74.string(),conflicts:z74.array(UniqueConflictSchema),truncated:z74.boolean().optional()})}});import{z as z75}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=z75.object({kind:z75.literal("unique_conflict"),contentType:z75.string(),field:z75.string(),value:z75.string(),documentCount:z75.number().int().positive(),documentIds:z75.array(z75.uuid()),documentIdsTruncated:z75.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z75.object({code:z75.literal("schema_transition_rejected"),message:z75.string(),issues:z75.array(SchemaTransitionIssueSchema),truncated:z75.boolean().optional()})}});import{z as z76}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=z76.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z76.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z76.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z76.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z76.object({field:CmsFieldNameSchema,direction:z76.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z76.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z76.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z76.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z76.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z76.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z77}from"zod";var ContentOverviewPageSchema,ContentOverviewViewSchema,ContentOverviewViewsDTOSchema,UpdateContentOverviewViewRequestSchema,ContentOverviewViewsResponseSchema,init_content_overview_view_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content-overview-view.dto.js"(){"use strict";init_response();ContentOverviewPageSchema=z77.enum(["collections","singles","forms"]),ContentOverviewViewSchema=z77.enum(["cards","list"]),ContentOverviewViewsDTOSchema=z77.object({collections:ContentOverviewViewSchema,singles:ContentOverviewViewSchema,forms:ContentOverviewViewSchema}),UpdateContentOverviewViewRequestSchema=z77.object({view:ContentOverviewViewSchema}),ContentOverviewViewsResponseSchema=createResponseSchema(ContentOverviewViewsDTOSchema)}});import{z as z78}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z78.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z79}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z79.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z79.object({event:ClientTrackedEventSchema,properties:z79.record(z79.string(),z79.unknown()).default({})})}});import{z as z80}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z80.object({id:z80.string(),name:z80.string()}),AssetDTOSchema=z80.object({id:z80.string(),name:z80.string(),type:AssetTypeSchema,originalFileName:z80.string().nullable(),parentId:z80.string().nullable(),mimeType:z80.string().nullable(),fileSize:z80.number().nullable(),url:z80.string().nullable(),storageKey:z80.string().nullable(),createdAt:z80.string(),updatedAt:z80.string(),altText:z80.string().nullable().optional(),caption:z80.string().nullable().optional(),aiCaption:z80.string().nullable().optional(),aiAltText:z80.string().nullable().optional(),aiTags:z80.array(z80.string()).nullable().optional(),aiPrimaryColor:z80.string().nullable().optional(),aiProcessingStatus:z80.string().nullable().optional(),width:z80.number().nullable().optional(),height:z80.number().nullable().optional(),path:z80.array(AssetPathItemSchema).optional(),hasChildren:z80.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z80.lazy(()=>z80.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z80.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z80.object({error:z80.string(),code:z80.literal("media_storage_limit_exceeded"),usedBytes:z80.number().int().nonnegative(),limitBytes:z80.number().int().positive(),incomingBytes:z80.number().int().nonnegative()}),AssetReferenceScopeSchema=z80.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z80.object({assetIds:z80.array(z80.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z80.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z80.object({totalFiles:z80.number().int().nonnegative(),checkedFiles:z80.number().int().nonnegative(),limit:z80.number().int().positive()}),AssetReferenceFindingDTOSchema=z80.object({assetId:z80.uuid(),entryId:z80.string(),documentId:z80.string(),contentType:z80.string(),locale:z80.string().nullable(),slug:z80.string(),fieldPath:z80.string()}),AssetReferenceScopeResultDTOSchema=z80.object({scope:AssetReferenceScopeSchema,label:z80.string(),state:z80.enum(["available","not-published","failed"]),coverage:z80.enum(["complete","partial","failed"]),referenceCount:z80.number().int().nonnegative().optional(),codeReferenceCount:z80.number().int().nonnegative().optional(),referencedAssetIds:z80.array(z80.uuid()).optional(),references:z80.array(AssetReferenceFindingDTOSchema),reason:z80.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z80.discriminatedUnion("type",[z80.object({type:z80.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z80.object({type:z80.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z80.object({type:z80.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z80.object({replacementAssetId:z80.uuid()}),AssetReferenceReplacementResultSchema=z80.object({referencesReplaced:z80.number().int().nonnegative(),entriesChanged:z80.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z80.object({referencesReplaced:z80.number().int().nonnegative(),filesChanged:z80.number().int().nonnegative(),commitSha:z80.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z80.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z80.object({error:z80.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z80.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z80.object({intent:AssetRemovalIntentSchema,assetIds:z80.array(z80.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z80.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z80.object({id:z80.uuid(),intent:AssetRemovalIntentSchema,assetIds:z80.array(z80.uuid()),replacementAssetId:z80.uuid().nullable(),expiresAt:z80.iso.datetime(),undoable:z80.boolean(),requestedByMe:z80.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z80.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z80.object({error:z80.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z81}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z81.object({key:z81.string(),value:z81.string().optional(),defaultValue:z81.string(),locale:z81.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z82}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=z82.object({id:z82.string(),name:z82.string(),type:z82.enum(["file","folder"]),path:z82.string(),children:z82.lazy(()=>z82.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z82.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z82.object({path:z82.string(),exists:z82.boolean(),type:z82.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z83}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z83.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z83.object({minLength:z83.number().optional(),maxLength:z83.number().optional(),min:z83.number().optional(),max:z83.number().optional(),pattern:z83.string().optional(),maxFileSize:z83.number().optional(),accept:z83.array(z83.string()).optional()}),FormFieldSchema=z83.object({type:FormFieldTypeSchema,label:z83.string(),placeholder:z83.string().optional(),required:z83.boolean().optional(),defaultValue:z83.string().optional(),options:z83.array(z83.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z83.record(z83.string(),FormFieldSchema),FormContentSchema=z83.object({name:z83.string().min(1).max(255),label:z83.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema=FormContentSchema.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z84}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z84.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z84.object({id:z84.string().uuid(),label:z84.string(),status:ChatTaskStatusSchema,startedAt:z84.string(),endedAt:z84.string().nullable(),result:z84.string().nullable()}),ChatTaskListDTOSchema=z84.object({tasks:z84.array(ChatTaskDTOSchema)})}});import{z as z85}from"zod";var AgentPatchSchema,AgentToolInputSchema,AgentToolRoutineSchema,AgentToolErrorCodeSchema,AgentToolResultSchema,AgentInstructionAuthorSchema,AgentInstructionRevisionDTOSchema,AgentInstructionRevisionListDTOSchema,AgentInstructionRevisionListResponseSchema,AgentInstructionRestoreSchema,init_chat_agent_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-agent.dto.js"(){"use strict";init_response();init_chat_routine_dto();init_chat_dto();AgentPatchSchema=z85.object({name:z85.string().trim().min(1).max(120).optional(),description:z85.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z85.string().min(1)).optional(),live:z85.literal(!0).optional()}),AgentToolInputSchema=AgentPatchSchema.extend({create:z85.literal(!0).optional()}),AgentToolRoutineSchema=z85.object({id:z85.string(),name:z85.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z85.string().nullable()}),AgentToolErrorCodeSchema=z85.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z85.discriminatedUnion("ok",[z85.object({ok:z85.literal(!0),agent:z85.object({id:z85.string(),name:z85.string(),live:z85.boolean(),routines:z85.array(AgentToolRoutineSchema)}),revisionId:z85.string().optional()}),z85.object({ok:z85.literal(!1),error:z85.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z85.object({kind:z85.enum(["person","agent"]),id:z85.string().nullable(),name:z85.string().nullable()}),AgentInstructionRevisionDTOSchema=z85.object({id:z85.string().uuid(),previous:z85.string().nullable(),instructions:z85.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z85.string()}),AgentInstructionRevisionListDTOSchema=z85.object({revisions:z85.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z85.object({revisionId:z85.string().uuid()})}});import{z as z86}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=z86.object({url:z86.string().url(),key:z86.string(),size:z86.number(),contentType:z86.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z87}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=z87.object({canAccess:z87.boolean(),permissions:z87.record(z87.string(),z87.boolean()),role:z87.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z88}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:z88.string().trim().default(""),sort:z88.enum(["recent","name","relevance"]).default("recent"),category:z88.string().optional()})}});import{z as z89}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=z89.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z89.enum(["fimo","external"]),PaymentStatusSchema=z89.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z89.object({id:z89.string().uuid(),domain:z89.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z89.boolean(),price:z89.number().int().nullable(),renewalPrice:z89.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z89.string().nullable(),failureReason:z89.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z89.object({domain:z89.string(),available:z89.boolean(),premium:z89.boolean(),price:z89.number().nullable(),renewalPrice:z89.number().nullable(),purchaseType:z89.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z89.object({domain:z89.string(),price:z89.number().nullable(),renewalPrice:z89.number().nullable(),premium:z89.boolean(),allowedYears:z89.array(z89.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z89.object({firstName:z89.string().max(100),lastName:z89.string().max(100),companyName:z89.string().max(100).optional(),address1:z89.string().max(255),address2:z89.string().max(255).optional(),city:z89.string().max(100),state:z89.string().max(100),zip:z89.string().max(20),country:z89.string().max(2),phone:z89.string().max(30),email:z89.union([z89.string().email().max(255),z89.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z89.object({firstName:z89.string().min(1).max(100),lastName:z89.string().min(1).max(100),companyName:z89.string().max(100).optional(),address1:z89.string().min(1).max(255),address2:z89.string().max(255).optional(),city:z89.string().min(1).max(100),state:z89.string().min(1).max(100),zip:z89.string().min(1).max(20),country:z89.string().min(1).max(2),phone:z89.string().min(1).max(30),email:z89.string().email().max(255)}),SearchDomainsRequestSchema=z89.object({keyword:z89.string().min(1).max(100),tldFilter:z89.array(z89.string()).optional()}),CheckAvailabilityRequestSchema=z89.object({domains:z89.array(z89.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=z89.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z89.object({domain:DomainNameSchema,years:z89.number().int().min(1).max(10).optional().default(3),autoRenew:z89.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z89.object({autoRenew:z89.boolean().optional()}),RenewDomainRequestSchema=z89.object({years:z89.number().int().min(1).max(10).optional().default(1),autoRenew:z89.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z89.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z89.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z89.object({verified:z89.boolean(),email:z89.string().nullable(),verifyBy:z89.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z90}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectStatusSchema,DomainRedirectSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,DEFAULT_REDIRECT_STATUS,SetProjectDomainRedirectRequestSchema,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=z90.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=z90.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=z90.object({txtName:z90.string().nullable().optional(),txtValue:z90.string().nullable().optional(),httpUrl:z90.string().nullable().optional(),httpBody:z90.string().nullable().optional(),cname:z90.string().nullable().optional(),cnameTarget:z90.string().nullable().optional()}),SSLValidationErrorSchema=z90.object({message:z90.string()}),OwnershipVerificationSchema=z90.object({type:z90.string(),name:z90.string(),value:z90.string()}),ProjectDomainSSLDTOSchema=z90.object({status:z90.string(),method:z90.string().nullable(),type:z90.string().nullable(),validationRecords:z90.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z90.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z90.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z90.enum(["subdomain","apex"]),RedirectStatusSchema=z90.union([z90.literal(301),z90.literal(302),z90.literal(307),z90.literal(308)]),DomainRedirectSchema=z90.object({targetDomainId:z90.string(),targetHostname:z90.string(),status:RedirectStatusSchema}).nullable(),ProjectDomainDTOSchema=z90.object({id:z90.string(),hostname:z90.string(),status:z90.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z90.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z90.string(),scdCnameTarget:z90.string().optional(),apexTargets:z90.array(z90.string()),dnsAutoConfigured:z90.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirect:DomainRedirectSchema,migrationStatus:z90.string().nullable().optional(),primary:z90.boolean()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z90.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z90.object({hostname:z90.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:z90.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z90.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z90.object({available:z90.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z90.object({success:z90.boolean(),hostname:z90.string(),removed:z90.array(z90.object({id:z90.string(),hostname:z90.string()}))})),DEFAULT_REDIRECT_STATUS=307,SetProjectDomainRedirectRequestSchema=z90.object({targetDomainId:z90.uuid().toLowerCase(),status:RedirectStatusSchema.default(DEFAULT_REDIRECT_STATUS)})}});import{z as z91}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=z91.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z91.object({available:z91.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z91.object({slug:z91.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z91.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z91.object({subdomain:z91.string(),subdomainUpdatedAt:z91.coerce.date()})),SubdomainSuggestionsQuerySchema=z91.object({base:z91.string().max(100).optional(),max:z91.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z91.object({suggestions:z91.array(z91.string())}))}});import{z as z92}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","project_code_sync_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z92.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z92.object({code:ProjectTransferBlockerCodeSchema,message:z92.string(),count:z92.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z92.object({targetOrganizationId:z92.string().min(1)}),ProjectTransferResultDTO=createDTO(z92.object({projectId:z92.string(),sourceOrganizationId:z92.string(),targetOrganizationId:z92.string(),movedThreads:z92.number().int().nonnegative(),revokedInvites:z92.number().int().nonnegative(),revokedGrants:z92.number().int().nonnegative(),preservedGrants:z92.number().int().nonnegative(),warnings:z92.array(z92.string())}))}});import{z as z93}from"zod";var PROJECT_TOKEN_PREFIX,MB2,UNCLAIMED_PLAN,UnclaimedLockedFeatureSchema,UNCLAIMED_CLAIM_STATES,UnclaimedClaimStateSchema,UNCLAIMED_PROJECT_ERROR_CODES,UnclaimedProjectErrorCodeSchema,ProvisionUnclaimedProjectRequestSchema,UnclaimedProjectLimitsSchema,UnclaimedProjectClaimSchema,ProvisionUnclaimedProjectResponseDTO,UnclaimedClaimStatusDTO,UnclaimedClaimSecretSchema,UnclaimedClaimStatusRequestSchema,UnclaimedClaimStatesRequestSchema,UnclaimedClaimStatesResponseDTO,ClaimUnclaimedProjectRequestSchema,ClaimUnclaimedProjectResultDTO,ProjectTokenSelfDTO,init_unclaimed_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unclaimed-project.dto.js"(){"use strict";init_create_dto();init_project_dto();PROJECT_TOKEN_PREFIX="fimo_pt_",MB2=1e6,UNCLAIMED_PLAN={ttlHours:72,tokenTtlAfterClaimHours:24,media:{totalBytes:50*MB2,fileBytes:5*MB2,maxFiles:100,mimeTypes:["image/jpeg","image/png","image/webp","image/avif","image/gif"]},database:{storageBytes:100*MB2,computeSeconds:600*60,maxComputeUnits:.5},locked:{publish:"Publishing",subdomain:"A fimo.site address",custom_domains:"Custom domains",branches:"Extra Branches",environments:"Extra environments",asset_generation:"Generating images and videos",integrations:"Connecting integrations",invites:"Inviting people",schedules:"Schedules",agents:"Fimo agents",ai_credits:"AI features"}},UnclaimedLockedFeatureSchema=z93.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z93.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","unclaimed_deploy_limit","claim_not_claimable","claim_project_limit_reached","claim_target_organization_not_found","claim_target_organization_forbidden","claim_target_subscription_inactive","claim_blocked","project_token_required","unclaimed_media_limit"],UnclaimedProjectErrorCodeSchema=z93.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z93.object({displayName:z93.string().trim().min(1).max(80),machineId:z93.string().trim().min(1).max(128).optional(),cliVersion:z93.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z93.object({ttlHours:z93.number().int().positive(),lockedFeatures:z93.array(UnclaimedLockedFeatureSchema),media:z93.object({totalBytes:z93.number().int().nonnegative(),fileBytes:z93.number().int().positive(),maxFiles:z93.number().int().nonnegative(),mimeTypes:z93.array(z93.string())}),database:z93.object({storageBytes:z93.number().int().positive(),computeSeconds:z93.number().int().positive(),maxComputeUnits:z93.number().positive()})}),UnclaimedProjectClaimSchema=z93.object({url:z93.string().url(),expiresAt:z93.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z93.object({project:ProjectDTOSchema,token:z93.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z93.object({state:UnclaimedClaimStateSchema,displayName:z93.string().nullable(),expiresAt:z93.coerce.date().nullable(),projectId:z93.string().nullable()})),UnclaimedClaimSecretSchema=z93.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z93.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z93.object({secrets:z93.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z93.object({claims:z93.array(z93.object({state:UnclaimedClaimStateSchema,expiresAt:z93.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z93.object({secret:UnclaimedClaimSecretSchema,organizationId:z93.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z93.object({projectId:z93.string(),organizationId:z93.string()})),ProjectTokenSelfDTO=createDTO(z93.object({kind:z93.literal("project_token"),projectId:z93.string(),projectName:z93.string(),displayName:z93.string().nullable(),organizationId:z93.string().nullable(),organizationName:z93.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z93.coerce.date().nullable(),tokenExpiresAt:z93.coerce.date().nullable()}))}});import{z as z94}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=z94.object({translated:z94.number().int().nonnegative(),total:z94.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z94.object({locale:z94.string(),isDefault:z94.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z94.object({defaultLocale:z94.string(),locales:z94.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z94.object({locale:z94.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z94.object({locale:z94.string().min(1).max(40)}),ProjectLocaleMutationSchema=z94.object({locale:z94.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z94.object({locale:z94.string(),entriesDeleted:z94.number().int().nonnegative(),labelsDeleted:z94.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z95}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=z95.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z95.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=z95.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z95.number(),credits:z95.number().optional(),billingMode:z95.enum(["fimo-credits","provider-account"]).optional(),confidence:z95.enum(["exact","estimated","metered"]),basis:z95.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z96}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=z96.object({options:z96.record(z96.string(),z96.unknown()),name:z96.string().optional(),parentId:z96.string().nullable().optional(),altText:z96.string().optional(),caption:z96.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z96.string().min(1).optional(),model:z96.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=z96.object({jobId:z96.string(),status:z96.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z96.string().nullable().optional(),credits:z96.number().optional(),costUsd:z96.number().optional(),billingMode:z96.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z96.object({error:z96.string(),code:z96.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:z96.array(GenerationTaskIdSchema).optional(),availableModels:z96.array(z96.string()).optional(),issues:z96.array(z96.unknown()).optional()})}});import{z as z97}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=z97.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z97.object({name:z97.string(),key:z97.string(),description:z97.string(),type:FlagTypeSchema,required:z97.boolean(),defaultValue:z97.unknown().optional(),enumValues:z97.array(z97.string()).optional(),isArray:z97.boolean()}),AssetModelPriceSchema=z97.object({unitPrice:z97.number(),unit:z97.string(),confidence:z97.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z97.object({id:z97.string(),shortName:z97.string(),provider:z97.string(),source:z97.string(),modality:z97.enum(["image","video","audio"]),tags:z97.array(z97.string()),displayName:z97.string(),description:z97.string(),flags:z97.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z97.object({model:z97.string(),costUsd:z97.number(),credits:z97.number(),billingMode:z97.enum(["fimo-credits","provider-account"]),confidence:z97.enum(["exact","estimated","metered"]),basis:z97.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z98}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=z98.object({tourId:z98.string(),version:z98.string(),status:z98.string(),completedAt:z98.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z98.array(UserTourDTOSchema))}});import{z as z99}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=z99.object({backendProfile:OpsBackendProfileSchema,provider:z99.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z99.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z99.object({backendProfile:OpsBackendProfileSchema,provider:z99.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z99.literal(!1),reason:z99.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z100}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=z100.object({packageManager:z100.string().trim().min(1).max(200).nullable(),trackedLockfiles:z100.array(z100.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z100.string().trim().min(1)}),OpsProjectPackageManagerSchema=z100.object({target:z100.object({backendProfile:OpsBackendProfileSchema,projectId:z100.uuid(),projectEnv:z100.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z101}from"zod";function uniqueRoutineNames(spec){let names=(spec.routines??[]).map(routine=>routine.name);return new Set(names).size===names.length}var OpsAgentChatRoutineSpecSchema,OpsAgentChatAgentSpecSchema,OpsAgentChatSpecObjectSchema,UNIQUE_ROUTINE_NAMES,OpsAgentChatSpecSchema,OpsAgentChatCreateInputSchema,OpsAgentChatOutcomeSchema,OpsAgentChatRoutineResultSchema,OpsAgentChatCreateResultSchema,init_ops_agent_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-chat.dto.js"(){"use strict";init_ops();init_chat_routine_dto();OpsAgentChatRoutineSpecSchema=ChatRoutineCreateSchema.extend({schedule:ChatRoutineScheduleSchema.nullable(),paused:z101.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z101.union([z101.object({name:z101.string().trim().min(1).max(120),description:z101.string().trim().min(1).max(2e3)}).strict(),z101.object({template:z101.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z101.object({agent:OpsAgentChatAgentSpecSchema,routines:z101.array(OpsAgentChatRoutineSpecSchema).max(50).optional()}).strict();__name(uniqueRoutineNames,"uniqueRoutineNames");UNIQUE_ROUTINE_NAMES={path:["routines"],message:"Routine names must be unique within one agent"},OpsAgentChatSpecSchema=OpsAgentChatSpecObjectSchema.refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatCreateInputSchema=OpsAgentChatSpecObjectSchema.extend({reason:z101.string().trim().min(1).max(1e3),dryRun:z101.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z101.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z101.object({id:z101.string().uuid().nullable(),name:z101.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z101.string().nullable(),paused:z101.boolean(),outcome:z101.enum(["created","would_create"]),source:z101.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z101.object({target:z101.object({backendProfile:OpsBackendProfileSchema,projectId:z101.string().uuid()}),dryRun:z101.boolean(),applied:z101.boolean(),createdBy:z101.object({userId:z101.string()}),agent:z101.object({id:z101.string().uuid().nullable(),title:z101.string(),template:z101.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z101.array(OpsAgentChatRoutineResultSchema),skipped:z101.array(z101.object({name:z101.string(),reason:z101.literal("routine_exists")})),refused:z101.array(z101.object({name:z101.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z102}from"zod";var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z102.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z102.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z102.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z102.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z102.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z102.object({reason:WebhookEntryChangeReasonSchema,operationId:z102.string().optional(),batch:z102.object({index:z102.number().int().positive(),total:z102.number().int().positive()}).optional(),changes:z102.array(z102.object({action:WebhookEntryChangeActionSchema,contentType:z102.string(),id:z102.string(),documentId:z102.string(),locale:z102.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z102.object({form:z102.object({id:z102.string(),label:z102.string()}),submission:z102.object({id:z102.string(),data:z102.record(z102.string(),z102.unknown()),submittedAt:z102.string()})}),PublishStartedWebhookEventDataSchema=z102.object({publication:z102.object({status:z102.literal("publishing"),startedAt:z102.string()})}),PublishSucceededWebhookEventDataSchema=z102.object({publication:z102.object({status:z102.literal("published"),url:z102.string(),publishedAt:z102.string(),firstPublish:z102.boolean()})}),PublishFailedWebhookEventDataSchema=z102.object({publication:z102.object({status:z102.literal("failed"),reason:z102.string()})}),PublishUnpublishedWebhookEventDataSchema=z102.object({publication:z102.object({previousUrl:z102.string(),unpublishedAt:z102.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z102.object({report:z102.object({weekStart:z102.string(),weekEnd:z102.string(),pageviews:z102.number(),visitors:z102.number(),previousPageviews:z102.number(),previousVisitors:z102.number()})}),MediaAssetWebhookEventDataSchema=z102.object({id:z102.string().nullable(),name:z102.string().nullable(),type:z102.string(),mimeType:z102.string().nullable(),fileSize:z102.number().nullable()}),MediaUploadedWebhookEventDataSchema=z102.object({asset:MediaAssetWebhookEventDataSchema,operation:z102.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z102.object({asset:MediaAssetWebhookEventDataSchema,operation:z102.literal("updated")}),MediaDeletedWebhookEventDataSchema=z102.object({asset:MediaAssetWebhookEventDataSchema,operation:z102.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z102.object({domain:z102.object({id:z102.string(),hostname:z102.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z102.object({domain:z102.object({id:z102.string(),hostname:z102.string()})}),LabelChangedWebhookEventDataSchema=z102.object({changes:z102.array(z102.object({action:z102.enum(["created","updated","deleted"]),key:z102.string(),locale:z102.string(),value:z102.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z102.object({locale:z102.object({code:z102.string(),isDefault:z102.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z102.object({locale:z102.object({code:z102.string(),previousCode:z102.string()})}),LocaleDeletedWebhookEventDataSchema=z102.object({locale:z102.object({code:z102.string(),entriesDeleted:z102.number().int().nonnegative(),labelsDeleted:z102.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z102.object({environment:z102.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z102.object({environment:z102.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z102.object({merge:z102.object({id:z102.string(),from:BranchSchema,to:BranchSchema,applied:z102.array(z102.object({surface:SurfaceNameSchema,count:z102.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z102.object({branch:z102.object({name:BranchSchema}),version:z102.object({versionId:z102.uuid(),name:z102.string()})}),WebhookEventFamilySchema=z102.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z102.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z102.discriminatedUnion("source",[z102.object({source:z102.literal("literal"),value:z102.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z102.object({source:z102.literal("secret"),key:z102.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z102.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z102.object({name:z102.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z102.object({name:z102.string(),source:z102.enum(["literal","secret"]),secretKey:z102.string().nullable(),secretPrefix:z102.string().nullable(),configured:z102.literal(!0)}),WebhookFilterSchema=z102.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z102.string().min(1).max(255).optional(),mediaType:z102.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z102.string().min(1).max(255).optional(),locale:z102.string().min(1).max(120).optional()}),JsonValueSchema=z102.lazy(()=>z102.union([z102.string(),z102.number(),z102.boolean(),z102.null(),z102.array(JsonValueSchema),z102.record(z102.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z102.object({name:z102.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z102.url(),enabled:z102.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z102.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z102.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z102.object({name:z102.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z102.url().optional(),enabled:z102.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z102.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z102.boolean().optional()}),TestProjectWebhookRequestSchema=z102.object({eventType:WebhookEventTypeSchema.optional(),data:z102.record(z102.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z102.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z102.uuid(),name:z102.string(),eventType:WebhookEventTypeSchema,enabled:z102.boolean(),destination:z102.object({host:z102.string(),maskedUrl:z102.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z102.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z102.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z102.coerce.date().nullable(),deliveryStats24h:z102.object({succeeded:z102.number().int().nonnegative(),failed:z102.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z102.uuid(),projectId:z102.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z102.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z102.number().int().positive(),test:z102.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z102.number().int().nonnegative(),responseStatus:z102.number().int().nullable(),lastErrorCode:z102.string().nullable(),lastErrorMessage:z102.string().nullable(),payloadAvailable:z102.boolean(),destination:z102.object({host:z102.string(),maskedUrl:z102.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z102.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z102.string().nullable(),qstashMessageId:z102.string().nullable(),deliveredAt:z102.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z102.object({items:z102.array(WebhookDeliveryDTOSchema),pagination:z102.object({page:z102.number().int().positive(),limit:z102.number().int().positive(),total:z102.number().int().nonnegative(),totalPages:z102.number().int().positive(),hasMore:z102.boolean()}),stats:z102.object({total:z102.number().int().nonnegative(),succeeded:z102.number().int().nonnegative(),failed:z102.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z102.object({id:z102.uuid(),deliveryId:z102.uuid(),attempt:z102.number().int().positive(),status:z102.enum(["delivering","succeeded","failed"]),responseStatus:z102.number().int().nullable(),durationMs:z102.number().int().nonnegative(),responseExcerpt:z102.string().nullable(),errorCode:z102.string().nullable(),errorMessage:z102.string().nullable(),createdAt:z102.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z102.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z102.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z103}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=z103.object({key:z103.literal("fimo-2"),enabled:z103.boolean(),dismissed:z103.boolean().default(!1),interacted:z103.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z104}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteRecommendationsSchema,SiteMarketSchema,SitePageViewSchema,SiteSectionStatusSchema,SiteComparisonSchema,SiteReportSchema,SiteTypeSchema,SiteTermsCategorySchema,SiteUnderstandingSchema,SiteSuggestionSchema,SiteInterviewSuggestionsSchema,SiteInterviewAnswerSchema,SiteInterviewSchema,AnswerSiteInterviewRequestSchema,SiteFixesReportSchema,SiteOnboardingResultSchema,StartSiteOnboardingRequestSchema,StartSiteOnboardingResponseSchema,SiteOnboardingRefusedResponseSchema,platforms,frameworks,SiteTechnologySchema,SiteSourceTechnologySchema,SiteOnboardingStateSchema,SiteOnboardingStateDTO,SiteOnboardingStateResponseSchema,RetrySiteOnboardingRequestSchema,SiteOnboardingOutcomeSchema,AdminSiteOnboardingsQuerySchema,AdminSiteOnboardingDTOSchema,AdminSiteOnboardingDTO,AdminSiteOnboardingsResponseSchema,AdminSiteOnboardingStatsSchema,AdminSiteOnboardingStatsResponseSchema,AdminSiteOnboardingDetailSchema,AdminSiteOnboardingDetailDTO,AdminSiteOnboardingDetailResponseSchema,init_site_onboarding_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/site-onboarding.dto.js"(){"use strict";init_create_dto();init_response();SiteOnboardingStageSchema=z104.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z104.enum(["running","done","failed"]),SiteCloneStatusSchema=z104.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z104.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z104.object({code:SiteRefusalCodeSchema,suggestedUrl:z104.string().nullable()}),SiteCheckGroupSchema=z104.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z104.enum(["seo","geo"]),SITE_CHECKS=[{id:"robots_txt",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap_lastmod",group:"discovery",scores:["seo","geo"],weight:1},{id:"broken_links",group:"discovery",scores:["seo"],weight:2},{id:"internal_nofollow",group:"discovery",scores:["seo"],weight:1},{id:"blocked_from_crawling",group:"discovery",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"status_4xx",group:"indexing",scores:["seo","geo"],weight:2,cap:{seo:10,geo:10}},{id:"status_5xx",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:10,geo:10}},{id:"https_to_http",group:"indexing",scores:["seo"],weight:1,cap:{seo:50}},{id:"canonical",group:"indexing",scores:["seo"],weight:1},{id:"noindex",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"hreflang",group:"indexing",scores:["seo"],weight:1},{id:"missing_page",group:"indexing",scores:["seo","geo"],weight:1,cap:{seo:80,geo:80}},{id:"ai_bots_robots",group:"ai_crawlers",scores:["geo"],weight:3,cap:{geo:30}},{id:"ai_bot_access",group:"ai_crawlers",scores:["geo"],weight:2,cap:{geo:40}},{id:"llms_txt",group:"ai_crawlers",scores:["geo"],weight:1},{id:"server_rendering",group:"rendering",scores:["geo"],weight:3},{id:"semantic_html",group:"rendering",scores:["seo","geo"],weight:2},{id:"markdown_pages",group:"rendering",scores:["geo"],weight:1},{id:"markdown_alternate",group:"rendering",scores:["geo"],weight:.5},{id:"markdown_index",group:"rendering",scores:["geo"],weight:.5},{id:"meta_title",group:"metadata",scores:["seo"],weight:2},{id:"meta_description",group:"metadata",scores:["seo"],weight:2},{id:"structured_data",group:"metadata",scores:["seo","geo"],weight:2},{id:"organization_schema",group:"metadata",scores:["geo"],weight:2},{id:"entity_links",group:"metadata",scores:["geo"],weight:1},{id:"metadata_completeness",group:"metadata",scores:["seo","geo"],weight:2},{id:"trust_pages",group:"metadata",scores:["geo"],weight:2},{id:"word_count",group:"content",scores:["seo","geo"],weight:2},{id:"text_ratio",group:"content",scores:["seo"],weight:1},{id:"h1",group:"content",scores:["seo"],weight:2},{id:"image_alt",group:"content",scores:["seo","geo"],weight:1},{id:"broken_images",group:"content",scores:["seo"],weight:1},{id:"empty_link_text",group:"content",scores:["seo","geo"],weight:1},{id:"page_load",group:"speed",scores:["seo"],weight:3},{id:"unminified_assets",group:"speed",scores:["seo"],weight:1}],SiteCheckIdSchema=z104.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z104.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z104.record(z104.string(),z104.union([z104.string(),z104.number(),z104.boolean(),z104.array(z104.string())])),SiteCheckResultSchema=z104.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z104.object({id:SiteCheckGroupSchema,score:z104.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z104.object({answers:z104.number().int().min(0),domains:z104.record(z104.string(),z104.number().int().min(0))}),SiteMarketSchema=z104.object({domain:z104.string(),competitors:z104.array(z104.string()),rankings:z104.array(z104.object({domain:z104.string(),averagePosition:z104.number().min(1).nullable()})),keywords:z104.array(z104.object({keyword:z104.string(),positions:z104.record(z104.string(),z104.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z104.record(z104.string(),z104.string()).optional(),countryCode:z104.string().optional(),languageCode:z104.string().optional(),fetchedAt:z104.coerce.date()}),SitePageViewSchema=z104.object({url:z104.string(),title:z104.string().nullable(),description:z104.string().nullable(),h1:z104.string().nullable(),structuredData:z104.array(z104.string()),wordCount:z104.number().int().min(0),capturedAt:z104.coerce.date()}),SiteSectionStatusSchema=z104.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z104.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z104.coerce.date().optional(),afterQueuedAt:z104.coerce.date().optional()}),SiteReportSchema=z104.object({siteUrl:z104.string(),scannedAt:z104.coerce.date(),seoScore:z104.number().int().min(0).max(100).nullable(),geoScore:z104.number().int().min(0).max(100).nullable(),groups:z104.array(SiteReportGroupSchema),checks:z104.array(SiteCheckResultSchema),blockers:z104.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z104.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z104.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z104.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z104.object({name:z104.string(),summary:z104.string(),audience:z104.string(),positioning:z104.string(),homepage:z104.string()}),SiteSuggestionSchema=z104.object({label:z104.string(),url:z104.string().nullable()}),SiteInterviewSuggestionsSchema=z104.record(z104.string(),z104.record(z104.string(),z104.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z104.record(z104.string().max(50),z104.union([z104.string().trim().max(2e3),z104.array(z104.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z104.object({status:z104.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z104.record(z104.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z104.object({questionId:z104.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z104.object({fixes:z104.array(z104.object({checkId:SiteCheckIdSchema,status:z104.enum(["fixed","not_fixed","not_applicable"]),note:z104.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z104.object({fixes:SiteFixesReportSchema.nullable(),summary:z104.string().nullable()}),StartSiteOnboardingRequestSchema=z104.object({organizationId:z104.string().min(1),url:z104.string().trim().min(1).max(2048),locale:z104.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z104.object({projectId:z104.string()})),SiteOnboardingRefusedResponseSchema=z104.object({error:z104.literal("site_refused"),refusal:SiteRefusalSchema}),platforms=["wordpress","webflow","framer","wix","shopify","squarespace","ghost","drupal","joomla","lovable","bolt","replit","base44","site123","manus","unknown"],frameworks=["nextjs","nuxt","astro","gatsby","angular","react","vue","svelte","unknown"],SiteTechnologySchema=z104.object({detectionVersion:z104.union([z104.literal(1),z104.literal(2)]),sourcePlatforms:z104.array(z104.enum(platforms)).min(1).max(platforms.length),frontendFrameworks:z104.array(z104.enum(frameworks)).min(1).max(frameworks.length)}),SiteSourceTechnologySchema=SiteTechnologySchema.extend({detectedAt:z104.string().datetime({offset:!0})}),SiteOnboardingStateSchema=z104.object({projectId:z104.string(),sourceTechnology:SiteSourceTechnologySchema.nullable().optional(),siteUrl:z104.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z104.boolean(),budgetExhausted:z104.boolean(),sponsored:z104.boolean(),outOfCredits:z104.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z104.string().nullable(),welcomeThreadId:z104.string().nullable(),competitors:z104.array(z104.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z104.coerce.date(),openedAt:z104.coerce.date().nullable(),bannerDismissed:z104.boolean(),migrateDialogSeen:z104.boolean(),completed:z104.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z104.object({task:z104.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z104.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z104.object({search:z104.string().trim().max(200).optional(),organizationId:z104.string().trim().min(1).max(200).optional(),startDate:z104.coerce.date().optional(),endDate:z104.coerce.date().optional(),outcomes:z104.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z104.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z104.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z104.array(SiteTypeSchema).optional()),page:z104.coerce.number().int().min(1).default(1),pageSize:z104.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z104.object({projectId:z104.string(),projectName:z104.string(),organizationId:z104.string(),organizationName:z104.string().nullable(),ownerEmail:z104.string().nullable(),ownerName:z104.string().nullable(),siteUrl:z104.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z104.boolean(),cloneRetries:z104.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z104.number(),interviewQuestions:z104.number().nullable(),seoScore:z104.number().nullable(),geoScore:z104.number().nullable(),spentUsd:z104.number(),budgetCapUsd:z104.number(),capReached:z104.boolean(),cloneSeconds:z104.number().nullable(),createdAt:z104.coerce.date(),openedAt:z104.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z104.object({onboardings:z104.array(AdminSiteOnboardingDTOSchema),page:z104.number(),limit:z104.number(),total:z104.number(),totalPages:z104.number()})),AdminSiteOnboardingStatsSchema=z104.object({total:z104.number(),outcomes:z104.record(SiteOnboardingOutcomeSchema,z104.number()),funnel:z104.object({started:z104.number(),finished:z104.number(),opened:z104.number()}),bySiteType:z104.array(z104.object({siteType:SiteTypeSchema,total:z104.number(),finished:z104.number(),opened:z104.number()})),granularity:z104.enum(["hour","day"]),series:z104.array(z104.object({at:z104.coerce.date(),outcomes:z104.record(SiteOnboardingOutcomeSchema,z104.number())})),spentUsd:z104.object({total:z104.number(),average:z104.number().nullable()}),sponsored:z104.number(),paidByOrganization:z104.object({usd:z104.number(),credits:z104.number()}),capReached:z104.number(),cloneSeconds:z104.object({median:z104.number().nullable(),average:z104.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z104.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z104.string(),cloneThreadId:z104.string().nullable(),paidByOrganizationUsd:z104.number()}),interview:SiteInterviewSchema.extend({invocationIds:z104.array(z104.string())}).nullable(),knowledgeWritten:z104.string().nullable(),knowledgeNow:z104.object({content:z104.string(),updatedAt:z104.coerce.date().nullable(),updatedBy:z104.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z105}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=z105.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z105.object({total:z105.number(),base:z105.number(),purchases:z105.number(),awards:z105.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z105.object({id:z105.string(),name:z105.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z105.object({type:z105.string(),brand:z105.string().nullable(),last4:z105.string().nullable(),expirationDate:z105.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z105.object({currency:z105.string(),nextPaymentAmount:z105.number().nullable(),nextPaymentAt:z105.string().nullable(),billingInterval:z105.string().nullable(),totalAmount:z105.number().nullable(),discountAmount:z105.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z105.object({id:z105.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z105.string().nullable(),currentPeriodEndsAt:z105.string().nullable(),renewsAt:z105.string().nullable(),cancelAt:z105.string().nullable(),renewAutomatically:z105.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z105.object({type:z105.enum(["low_balance","critical_balance","approaching_limit"]),message:z105.string(),estimatedPromptsRemaining:z105.number().nullable(),avgCostPerPrompt:z105.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z105.object({monthlyCredits:z105.number().nullable(),usedThisPeriod:z105.number(),remainingThisPeriod:z105.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z105.object({organizationId:z105.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z105.string().nullable(),tenureDays:z105.number().int().nonnegative(),capturedAt:z105.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z105.object({hasSubscription:z105.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z105.number().nullable(),alerts:z105.array(CreditAlertDTOSchema),portalUrl:z105.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z105.object({creditCount:z105.number().int().positive(),expiresAt:z105.string().datetime().nullable().optional(),message:z105.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z105.literal("free"),amountCents:z105.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z105.literal("purchase"),amountCents:z105.number().int().positive()}),CreditTopupRequestDTOSchema=z105.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z105.object({success:z105.boolean(),transactionId:z105.string().nullable(),newBalance:z105.number(),creditCount:z105.number(),type:z105.enum(["free","purchase"]),invoiceId:z105.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z106}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=z106.object({totalCredits:z106.number(),totalCostUsd:z106.number(),totalMessages:z106.number(),avgCostPerMessage:z106.number(),periodStart:z106.string().nullable(),periodEnd:z106.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z106.object({projectId:z106.string(),projectName:z106.string(),projectDisplayName:z106.string().nullable(),credits:z106.number(),costUsd:z106.number(),messages:z106.number(),percentage:z106.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z106.object({userId:z106.string(),userName:z106.string().nullable(),userEmail:z106.string().email().nullable(),credits:z106.number(),costUsd:z106.number(),messages:z106.number(),percentage:z106.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z106.object({date:z106.string(),credits:z106.number(),costUsd:z106.number(),messages:z106.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z106.object({userId:z106.string(),userName:z106.string().nullable(),userEmail:z106.string().email().nullable(),credits:z106.number(),costUsd:z106.number(),messages:z106.number(),percentage:z106.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z106.object({projectId:z106.string(),projectName:z106.string(),projectDisplayName:z106.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z106.array(UsageByUserForProjectDTOSchema),timeline:z106.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z106.object({summary:UsageSummaryDTOSchema,byProject:z106.array(UsageByProjectDTOSchema),byUser:z106.array(UsageByUserDTOSchema),timeline:z106.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z107}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=z107.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z107.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z107.object({startDate:z107.string().optional(),endDate:z107.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z107.coerce.number().int().positive().default(1),limit:z107.coerce.number().int().positive().max(100).default(20),sortBy:z107.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z107.string().optional(),activeOnly:z107.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z107.object({totalCredits:z107.number(),totalCostUsd:z107.number(),totalMessages:z107.number(),automatedMessages:z107.number(),avgCostPerMessage:z107.number(),avgCreditsPerMessage:z107.number(),periodStart:z107.string(),periodEnd:z107.string(),creditsChange:z107.number().nullable(),costChange:z107.number().nullable(),messagesChange:z107.number().nullable(),unattributedCredits:z107.number(),unattributedCostUsd:z107.number(),unattributedMessages:z107.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z107.object({date:z107.string(),credits:z107.number(),costUsd:z107.number(),messages:z107.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z107.object({organizationId:z107.string(),organizationName:z107.string(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number(),userCount:z107.number(),projectCount:z107.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z107.object({userId:z107.string(),userName:z107.string().nullable(),userEmail:z107.string().nullable(),userImage:z107.string().nullable(),organizationId:z107.string().nullable(),organizationName:z107.string().nullable(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number(),projectCount:z107.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z107.object({projectId:z107.string(),projectName:z107.string(),projectDisplayName:z107.string().nullable(),organizationId:z107.string(),organizationName:z107.string(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number(),userCount:z107.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z107.object({id:z107.string(),name:z107.string(),value:z107.number(),percentage:z107.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z107.object({day:z107.number(),hour:z107.number(),value:z107.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z107.object({summary:UsageOverviewSummaryDTOSchema,timeline:z107.array(UsageTimelinePointDTOSchema),topOrganizations:z107.array(OrganizationUsageRowDTOSchema),topUsers:z107.array(UserUsageRowDTOSchema),topProjects:z107.array(ProjectUsageRowDTOSchema),creditDistribution:z107.array(UsageDistributionItemDTOSchema),userDistribution:z107.array(UsageDistributionItemDTOSchema),heatmap:z107.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z107.object({page:z107.number(),limit:z107.number(),totalItems:z107.number(),totalPages:z107.number(),hasMore:z107.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z107.object({organizations:z107.array(OrganizationUsageRowDTOSchema),top:z107.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z107.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z107.object({users:z107.array(ExtendedUserUsageRowDTOSchema),top:z107.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z107.string(),ownerName:z107.string().nullable(),ownerEmail:z107.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z107.object({projects:z107.array(ExtendedProjectUsageRowDTOSchema),top:z107.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z107.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z107.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z107.object({credits:z107.number(),costUsd:z107.number(),messages:z107.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z107.object({id:z107.string(),name:z107.string(),createdAt:z107.string(),memberCount:z107.number(),projectCount:z107.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z107.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z107.object({id:z107.string(),name:z107.string().nullable(),email:z107.string(),image:z107.string().nullable(),createdAt:z107.string(),organizationCount:z107.number(),projectCount:z107.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z107.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z107.object({id:z107.string(),name:z107.string(),displayName:z107.string().nullable(),createdAt:z107.string(),organizationId:z107.string(),organizationName:z107.string(),ownerId:z107.string(),ownerName:z107.string().nullable(),ownerEmail:z107.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z107.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z108}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=z108.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z108.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z108.object({command:z108.string().min(1).max(1e4),cwd:z108.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z108.record(z108.string(),z108.string()).optional(),name:z108.string().optional(),waitForCompletion:z108.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z108.object({identifier:z108.string(),status:SandboxProcessStatusSchema,command:z108.string().optional(),startedAt:z108.string().optional(),exitCode:z108.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z108.object({processes:z108.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z108.object({processId:z108.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z108.object({success:z108.boolean(),message:z108.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z109}from"zod";var ADMIN_UNCLAIMED_STATES,AdminUnclaimedStateSchema,AdminUnclaimedProjectsQuerySchema,AdminUnclaimedProjectDTOSchema,AdminUnclaimedProjectDTO,AdminUnclaimedProjectsResponseSchema,ClaimOutcomesSchema,AdminUnclaimedProjectStatsSchema,AdminUnclaimedProjectStatsResponseSchema,init_unclaimed_projects_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/unclaimed-projects.dto.js"(){"use strict";init_create_dto();init_response();ADMIN_UNCLAIMED_STATES=["waiting","claiming","claimed","overdue","archived"],AdminUnclaimedStateSchema=z109.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z109.object({search:z109.string().trim().max(200).optional(),startDate:z109.coerce.date().optional(),endDate:z109.coerce.date().optional(),states:z109.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z109.array(AdminUnclaimedStateSchema).optional()),cliVersions:z109.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z109.array(z109.string().max(64)).optional()),page:z109.coerce.number().int().min(1).default(1),pageSize:z109.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z109.object({projectId:z109.string(),displayName:z109.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z109.string().nullable(),createdAt:z109.coerce.date(),expiresAt:z109.coerce.date(),claimedAt:z109.coerce.date().nullable(),claimedOrganizationId:z109.string().nullable(),claimedOrganizationName:z109.string().nullable(),claimedByEmail:z109.string().nullable(),projectExists:z109.boolean(),previewUrl:z109.string().nullable(),hostingCostUsd:z109.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z109.object({projects:z109.array(AdminUnclaimedProjectDTOSchema),page:z109.number(),limit:z109.number(),total:z109.number(),totalPages:z109.number()})),ClaimOutcomesSchema=z109.object({total:z109.number(),claimed:z109.number(),archived:z109.number(),claimRate:z109.number().nullable(),medianTimeToClaimSeconds:z109.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z109.record(AdminUnclaimedStateSchema,z109.number()),averageTimeToClaimSeconds:z109.number().nullable(),byCliVersion:z109.array(ClaimOutcomesSchema.extend({cliVersion:z109.string().nullable()})),granularity:z109.enum(["hour","day"]),series:z109.array(z109.object({at:z109.coerce.date(),states:z109.record(AdminUnclaimedStateSchema,z109.number()),alive:z109.number(),hostingCostUsd:z109.number()})),hostingCostUsd:z109.number(),costPerProjectUsd:z109.number().nullable(),leftovers:z109.object({overdue:z109.number(),claiming:z109.number(),archivedNotDeleted:z109.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z110}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z110.enum(["internal","user-visible"]),SessionSetRetentionSchema=z110.object({additionalDays:z110.number().int().min(1).max(30)}).strict()}});import{z as z111}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z111.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z111.object({content:ProjectKnowledgeContentSchema,updatedAt:z111.string().nullable(),updatedBy:z111.string().nullable()}),ProjectKnowledgeUpdateSchema=z111.object({content:ProjectKnowledgeContentSchema,expectedUpdatedAt:z111.iso.datetime().nullable().optional()}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z111.object({id:z111.uuid(),status:z111.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z111.string().nullable(),reason:z111.enum(["insufficient_credits"]).nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z111.object({idempotencyKey:z111.uuid()})}});import{z as z112}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_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_args();init_commands();init_references2();init_types();init_chat_block();init_chat_place();init_chat_reply();init_chat_tabs();init_chat_block_state();init_admin_chat_block();init_admin_assistant();init_chat_portrait();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_session_dto();init_agent_proposal_dto();init_draft_change_dto();init_agent_question_dto();init_agent_question_follow_up_dto();init_integration_catalog_dto();init_integration_dto();init_code_sync_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_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_content_overview_view_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_chat_routine_dto();init_chat_task_dto();init_chat_agent_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_unclaimed_project_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_agent_proposals_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_chat_dto();init_webhook_dto();init_preview_feature_dto();init_site_onboarding_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto();init_unclaimed_projects_dto();init_work_sessions();init_project_knowledge_dto();init_organization_features_dto();init_admin_monitoring_dto();init_platform();init_sandbox();init_monitor();init_agent()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor3=0;do result+=string.substring(cursor3,index)+replace,cursor3=index+close.length,index=string.indexOf(close,cursor3);while(~index);return result+string.substring(cursor3)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types2=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout:stdout2,stderr}=opts,pendingWarnings=[];function emit(stream,envelope){let warnings=[...pendingWarnings,...envelope.warnings??[]].filter((warning,index,all)=>all.indexOf(warning)===index);pendingWarnings=[],stream.write(`${JSON.stringify(warnings.length>0?{...envelope,warnings}:envelope)}
6
+ `)}function reportSectionContentLength(blocks){return blocks.reduce((total,block2)=>total+(block2.title?.length??0)+derivedBlockBody(block2).length+(block2.fallback?.length??0),0)}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}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,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,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=z45.enum(REPORT_TONES),blockCommon={title:z45.string().trim().min(1).max(120).optional(),fallback:z45.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z45.object({type:z45.literal("text"),...blockCommon,text:z45.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=z45.object({type:z45.literal("metric"),...blockCommon,items:z45.array(z45.object({value:z45.string().trim().min(1).max(24),unit:z45.string().trim().min(1).max(12).optional(),label:z45.string().trim().min(1).max(160),note:z45.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z45.array(z45.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z45.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z45.object({type:z45.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z45.string().trim().min(1).max(12).optional(),points:z45.array(z45.object({label:z45.string().trim().min(1).max(24),value:z45.number().finite(),highlight:z45.boolean().optional()}).strict()).min(2).max(24),caption:z45.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((block2,ctx)=>{block2.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block2.kind==="composition"&&block2.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z45.object({type:z45.literal("list"),...blockCommon,items:z45.array(z45.object({tone:ReportToneSchema.optional(),label:z45.string().trim().min(1).max(24).optional(),heading:z45.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z45.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z45.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z45.object({type:z45.literal("table"),...blockCommon,columns:z45.array(z45.object({label:z45.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z45.array(z45.object({cells:z45.array(z45.object({text:z45.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block2,ctx)=>{block2.rows.forEach((row2,index)=>{row2.cells.length!==block2.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block2.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z45.object({type:z45.literal("media"),...blockCommon,assetId:z45.uuid(),alt:z45.string().trim().min(1).max(300),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z45.object({type:z45.literal("links"),...blockCommon,items:z45.array(z45.object({label:z45.string().trim().min(1).max(120),url:z45.url({protocol:/^https$/}).max(2e3),description:z45.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z45.object({type:z45.literal("code"),...blockCommon,language:z45.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z45.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z45.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z45.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z45.object({title:z45.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z45.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z45.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=z45.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z45.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z45.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z46}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=z46.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z46.object({dev:z46.string().trim().min(1).optional(),build:z46.string().trim().min(1).optional(),install:z46.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z46.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z46.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z46.object({type:z46.enum(["header","cookie","query","host"]),key:z46.string().min(1).optional(),value:z46.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:z46.array(FimoHostingConditionSchema).min(1).optional(),missing:z46.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z46.object({source:z46.string().min(1),destination:z46.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z46.object({source:z46.string().min(1),destination:z46.string().min(1),permanent:z46.boolean().optional(),statusCode:z46.union([z46.literal(301),z46.literal(302),z46.literal(307),z46.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z46.object({source:z46.string().min(1),headers:z46.array(z46.object({key:z46.string().min(1),value:z46.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z46.object({rewrites:z46.array(FimoHostingRewriteSchema).optional(),redirects:z46.array(FimoHostingRedirectSchema).optional(),headers:z46.array(FimoHostingHeaderSchema).optional(),cleanUrls:z46.boolean().optional(),trailingSlash:z46.boolean().optional()}).strict(),FimoAppConfigSchema=z46.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 isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52,params){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param)&&params?.[param]?.type!=="external")}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";__name(isEntryParamBinding,"isEntryParamBinding");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")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z47}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,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();ProjectBranchStatusSchema=z47.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z47.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z47.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z47.string().nullable(),deletedAt:z47.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z47.object({id:z47.union([z47.literal(PREVIEW_ENVIRONMENT_KEY),z47.uuid()]),name:z47.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z47.object({sessionId:z47.uuid(),name:z47.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z47.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z47.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z47.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z47.object({surface:z47.enum(["code","schemas","content","translations","assets","forms"]),status:z47.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z47.number().int().nonnegative(),conflictCount:z47.number().int().nonnegative()}),BranchDiffResultSchema=z47.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z47.coerce.date(),surfaces:z47.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z48}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=z48.object({projectId:z48.uuid(),name:z48.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z48.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z48.literal("production"),sourceBranch:BranchSchema,isPublished:z48.boolean(),url:z48.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z48.literal(PREVIEW_ENVIRONMENT_KEY),kind:z48.literal("preview"),matchedBranchCount:z48.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z48.literal("custom"),matchedBranchCount:z48.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z48.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z48.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z48.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z48.object({deletedId:z48.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z49}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectVariableBaseSchema,ProjectVariableDTOSchema,ProjectVariableDTO,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=z49.object({kind:z49.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z49.object({kind:z49.enum(["variable","secret"]),value:z49.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z49.string().min(1).max(255),exposure:z49.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z49.object({kind:z49.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),key:z49.string(),kind:z49.literal("secret"),exposure:z49.literal("private"),environment:EnvironmentKeySchema,maskedValue:z49.string().optional(),createdAt:z49.date().transform(value=>value.toISOString()),updatedAt:z49.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),key:z49.string(),kind:z49.literal("variable"),environment:EnvironmentKeySchema,managed:z49.boolean(),createdAt:z49.date().transform(value=>value.toISOString()),updatedAt:z49.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z49.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z49.literal("public"),value:z49.string()}),ProjectVariableBaseSchema.extend({exposure:z49.literal("private"),maskedValue:z49.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z49.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z50}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=z50.object({success:z50.literal(!0),downloadUrl:z50.string(),expiresAt:z50.string(),fileSize:z50.number(),duration:z50.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z50.object({success:z50.literal(!0),projectId:z50.string(),projectName:z50.string(),displayName:z50.string(),projectUrl:z50.string(),duration:z50.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z50.object({contentTypes:z50.number(),entries:z50.number(),assets:z50.number(),translations:z50.number(),forms:z50.number(),codeFiles:z50.number(),assetFiles:z50.number()}),ImportPreviewSurfaceDTOSchema=z50.object({name:z50.string(),included:z50.boolean(),count:z50.number().optional(),note:z50.string().optional()}),ImportPreviewDTOSchema=z50.object({projectName:z50.string(),displayName:z50.string().nullable(),category:z50.string().nullable(),exportedAt:z50.string(),version:z50.string(),envScope:z50.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z50.array(ImportPreviewSurfaceDTOSchema),fileSize:z50.number(),fileName:z50.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z50.object({success:z50.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z51}from"zod";var AgentSessionStatusSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,SessionErrorCodeSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentSessionStatusSchema=z51.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z51.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z51.object({capturedAt:z51.coerce.date(),fingerprint:z51.string().min(1).max(256),counts:z51.object({code:z51.number().int().nonnegative(),content:z51.number().int().nonnegative(),schemas:z51.number().int().nonnegative(),labels:z51.number().int().nonnegative(),assets:z51.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z51.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z51.object({diff:DiffReportSchema,code:z51.array(CodeFileDiffSchema.extend({raw:z51.string().max(24576)})).max(200),schemas:z51.array(SchemaTypeDiffSchema).max(200),content:z51.array(z51.object({key:z51.string().min(1).max(512),collection:z51.string().min(1).max(256),slug:z51.string().max(512).optional(),verb:z51.enum(["added","modified","deleted"]),fields:z51.array(z51.object({name:z51.string().min(1).max(256),before:z51.unknown().optional(),after:z51.unknown().optional()})).max(20)})).max(200),labels:z51.array(z51.object({key:z51.string().min(1).max(512),locale:z51.string().min(1).max(64).optional(),before:z51.unknown().nullable(),after:z51.unknown().nullable()})).max(200),assets:z51.array(z51.object({key:z51.string().min(1).max(512),name:z51.string().min(1).max(512),verb:z51.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z51.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z52}from"zod";var AskDraftChangeRequestSchema,RewriteDraftWordsRequestSchema,DraftChangeStateQuerySchema,DraftChangeStateSchema,ApproveProposalRequestSchema,ProposalApprovalStateQuerySchema,init_draft_change_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/draft-change.dto.js"(){"use strict";AskDraftChangeRequestSchema=z52.object({projectId:z52.uuid(),reviewId:z52.uuid(),entryId:z52.string().min(1).max(120),contentTypeName:z52.string().min(1).max(120),field:z52.string().min(1).max(120),quote:z52.string().min(1).max(2e4).optional(),locale:z52.string().min(1).max(35).optional(),message:z52.string().trim().min(1).max(4e3),providerMessageId:z52.string().min(1).max(200)}),RewriteDraftWordsRequestSchema=AskDraftChangeRequestSchema.extend({format:z52.enum(["rich","plain"]),words:z52.string().min(1).max(4e4),surroundingText:z52.string().max(2e4).optional()}),DraftChangeStateQuerySchema=z52.object({projectId:z52.uuid(),reviewId:z52.uuid()}),DraftChangeStateSchema=z52.object({busy:z52.boolean(),reply:z52.string().nullable()}),ApproveProposalRequestSchema=z52.object({projectId:z52.uuid(),proposalId:z52.uuid(),providerMessageId:z52.string().min(1).max(200),message:z52.string().trim().min(1).max(200),threadId:z52.uuid().optional()}),ProposalApprovalStateQuerySchema=z52.object({projectId:z52.uuid(),proposalId:z52.uuid(),threadId:z52.uuid().optional()})}});import{z as z53}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=z53.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z53.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=z53.object({description:z53.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z53.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z53.array(z53.uuid()).optional()}),AgentQuestionSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),threadId:z53.uuid(),invocationId:z53.uuid(),agentKey:z53.string().min(1).max(120),anchorEnv:z53.string().min(1).max(64),retainedEnv:z53.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z53.string().min(1).nullable(),continuationInvocationId:z53.uuid().nullable(),askedAt:z53.coerce.date(),expiresAt:z53.coerce.date(),closedAt:z53.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z53.object({questionId:z53.uuid(),invocationId:z53.uuid(),askedAt:z53.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z53.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z53.object({question:AgentQuestionSchema,continuationInvocationId:z53.uuid(),deduped:z53.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z54}from"zod";var AgentQuestionFollowUpRequestSchema,AgentQuestionFollowUpSchema,AgentQuestionFollowUpDTO,init_agent_question_follow_up_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question-follow-up.dto.js"(){"use strict";init_create_dto();AgentQuestionFollowUpRequestSchema=z54.object({projectId:z54.uuid(),agentId:z54.uuid(),recipientEmail:z54.email().max(320)}).strict(),AgentQuestionFollowUpSchema=z54.object({projectId:z54.uuid(),agentId:z54.uuid(),eligible:z54.boolean(),reason:z54.enum(["ready","no_pending_questions","incomplete_coverage","unavailable"]),agentPendingQuestions:z54.number().int().nonnegative().nullable(),projectPendingQuestions:z54.number().int().nonnegative().nullable(),agentLegacyPendingForms:z54.number().int().nonnegative().nullable(),projectLegacyPendingForms:z54.number().int().nonnegative().nullable(),agentPendingCoverage:z54.enum(["complete","partial","unknown"]),projectPendingCoverage:z54.enum(["complete","partial","unknown"]),snapshotAt:z54.iso.datetime().nullable()}),AgentQuestionFollowUpDTO=createDTO(AgentQuestionFollowUpSchema)}});import{z as z55}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,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=z55.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z55.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z55.enum(["secret_text"]),IntegrationCredentialUsageSchema=z55.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z55.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z55.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z55.object({mode:IntegrationAuthModeSchema,label:z55.string().min(1),description:z55.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z55.object({id:z55.string().min(1),label:z55.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z55.boolean()}),IntegrationToolDefinitionDTOSchema=z55.object({key:z55.string().min(1),name:z55.string().min(1),description:z55.string().min(1),effect:IntegrationToolEffectSchema,input:z55.record(z55.string(),z55.unknown()).optional()}),IntegrationRecipeDTOSchema=z55.object({title:z55.string().min(1),description:z55.string().min(1),command:z55.string().min(1).optional()}),IntegrationInfoDTOSchema=z55.object({key:z55.string().min(1),name:z55.string().min(1),summary:z55.string().min(1),type:z55.enum(["native","mcp"]).optional(),url:z55.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z55.array(IntegrationAuthModeDTOSchema),credentials:z55.array(IntegrationCredentialDefinitionDTOSchema),tools:z55.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z55.enum(["available","unavailable"]).optional(),connectionCapabilities:z55.object({customIdentityCreation:z55.boolean()}).optional(),recipes:z55.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z55.object({projectId:z55.uuid(),integrationKey:z55.string().min(1),name:z55.string().min(1),summary:z55.string().min(1),installed:z55.boolean(),enabled:z55.boolean(),setupState:z55.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z55.string().nullable(),connectionId:z55.uuid().nullable().optional(),connectionAlias:z55.string().min(1).nullable().optional(),connectionStatus:z55.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z55.array(z55.string()),installedAt:z55.coerce.date().nullable(),updatedAt:z55.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z55.object({id:z55.uuid(),projectId:z55.uuid(),integrationKey:z55.string().min(1),enabled:z55.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z55.string(),connectionId:z55.uuid().nullable().optional(),connectionAlias:z55.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z55.array(z55.string()),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z55.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z55.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z55.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z55.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z55.object({id:z55.uuid(),organizationId:z55.string().min(1),integrationKey:z55.string().min(1),registrationId:z55.uuid().nullable(),alias:z55.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z55.string().min(1),externalAccountName:z55.string().nullable(),externalBotUserId:z55.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z55.array(z55.string()),connectedAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z55.boolean(),isDefault:z55.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z55.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z55.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z55.record(McpHeaderNameSchema,z55.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z55.object({alias:z55.string().min(1).max(120).optional(),token:z55.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z55.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=z55.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z55.object({displayName:z55.string().trim().min(1).max(35),backgroundColor:z55.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z55.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z55.discriminatedUnion("mode",[z55.object({mode:z55.literal("personal"),alias:z55.string().min(1).max(120),token:z55.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z55.boolean().optional()}),z55.object({mode:z55.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z55.boolean().optional(),registrationId:z55.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),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=z55.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z55.union([z55.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z55.object({type:z55.literal("mcp"),name:z55.string().trim().min(1).max(120),url:z55.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z55.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z55.string().min(1).optional(),integrationId:z55.string().min(2).max(80).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=z55.object({integrationKey:z55.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z55.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z55.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z55.literal("oauth"),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()})]),ReusableMcpServerAuthKindSchema=z55.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z55.object({id:z55.uuid(),name:z55.string().min(1),host:z55.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z55.string().min(1),availability:z55.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z55.object({query:z55.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z55.object({serverId:z55.uuid()}),LinearOAuthApplicationDistributionSchema=z55.enum(["private","public"]),OrganizationLinearAppDTOSchema=z55.object({id:z55.uuid(),displayName:z55.string().min(1),description:z55.string().nullable(),iconUrl:z55.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z55.enum(["active","revoked","disconnected"]),connectionIds:z55.array(z55.uuid()),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z55.object({appName:z55.string().trim().min(2).max(80),description:z55.string().trim().max(1e3).optional(),iconUrl:z55.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z55.object({projectId:z55.uuid(),registrationId:z55.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z55.object({integrationKey:z55.string().min(1),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z55.discriminatedUnion("mode",[z55.object({mode:z55.literal("personal"),integrationKey:z55.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z55.object({mode:z55.literal("oauth"),integrationKey:z55.string().min(1),connectUrl:z55.string().url(),expiresAt:z55.coerce.date()})]),BindProjectChannelRequestSchema=z55.object({ref:z55.string().min(1),connectionAlias:z55.string().min(1).optional(),agentName:z55.string().min(1).max(160).nullable().optional(),force:z55.boolean().optional()}),ListProjectChannelsQuerySchema=z55.object({integrationKey:z55.string().min(1)}),SearchProjectChannelsQuerySchema=z55.object({integrationKey:z55.string().min(1),connectionAlias:z55.string().min(1),query:z55.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z55.object({id:z55.uuid(),projectId:z55.uuid(),integrationKey:z55.string().min(1),connectionId:z55.uuid(),externalWorkspaceId:z55.string().min(1),externalChannelId:z55.string().min(1),externalChannelName:z55.string().nullable(),agentName:z55.string().nullable(),enabled:z55.boolean(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z55.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z55.object({id:z55.string().min(1),name:z55.string().min(1),visibility:z55.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z55.string().min(1).nullable(),canMove:z55.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z55.object({markdown:z55.boolean().optional(),summary:z55.boolean().optional(),links:z55.boolean().optional(),branding:z55.boolean().optional(),images:z55.boolean().optional(),html:z55.union([z55.literal("cleaned"),z55.literal("raw"),z55.boolean()]).optional(),json:z55.union([z55.boolean(),z55.object({prompt:z55.string().min(1).max(1e4),schema:z55.record(z55.string(),z55.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z55.object({url:z55.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional(),waitForMs:z55.number().int().min(0).max(3e4).optional(),maxAgeMs:z55.number().int().min(0).optional(),minAgeMs:z55.number().int().min(0).optional(),storeInCache:z55.boolean().optional(),proxy:z55.enum(["basic","enhanced","auto"]).optional(),mobile:z55.boolean().optional(),location:z55.object({country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z55.array(z55.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z55.object({query:z55.string().min(1),maxResults:z55.number().int().positive().max(20).optional(),sources:z55.array(z55.enum(["web","news","images"])).min(1).max(3).optional(),categories:z55.array(z55.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z55.enum(["hour","day","week","month","year"]).optional(),location:z55.string().min(1).max(160).optional(),country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z55.object({query:z55.string().min(1).max(500),maxResults:z55.number().int().min(1).max(100).optional(),types:z55.array(z55.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z55.array(z55.string().min(1).max(512)).min(1).max(20).optional(),sources:z55.array(z55.string().min(1).max(512)).min(1).max(20).optional(),passages:z55.number().int().min(1).max(5).optional(),skills:z55.literal("only").optional(),language:z55.string().min(1).optional(),topic:z55.string().min(1).optional(),license:z55.string().min(1).optional(),minStars:z55.number().int().min(0).optional(),maxStars:z55.number().int().min(0).optional(),archived:z55.boolean().optional(),fork:z55.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z55.object({query:z55.string().min(1).max(500),maxResults:z55.number().int().min(1).max(500).optional(),authors:z55.array(z55.string().min(1)).min(1).optional(),categories:z55.array(z55.string().min(1)).min(1).optional(),from:z55.iso.date().optional(),to:z55.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z55.object({paperId:z55.string().min(1).max(512),query:z55.string().min(1).max(500).optional(),maxPassages:z55.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z55.object({paperId:z55.string().min(1).max(512),intent:z55.string().min(1).max(500),mode:z55.enum(["similar","citers","references"]).optional(),maxResults:z55.number().int().min(1).max(500).optional(),rerank:z55.boolean().optional(),anchors:z55.array(z55.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z55.object({url:z55.string().url(),search:z55.string().min(1).optional(),limit:z55.number().int().positive().max(200).optional(),includeSubdomains:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z55.object({url:z55.string().url(),limit:z55.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z55.object({text:z55.string().min(1).max(200).optional(),cron:z55.string().min(1).max(120).optional(),timezone:z55.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z55.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z55.boolean().optional(),timeoutMs:z55.number().int().positive().max(12e4).optional(),waitForMs:z55.number().int().min(0).max(3e4).optional(),maxAgeMs:z55.number().int().min(0).optional(),minAgeMs:z55.number().int().min(0).optional(),storeInCache:z55.boolean().optional(),proxy:z55.enum(["basic","enhanced","auto"]).optional(),mobile:z55.boolean().optional(),location:z55.object({country:z55.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z55.array(z55.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z55.union([z55.object({type:z55.enum(["scrape","crawl"]).default("scrape"),urls:z55.array(z55.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z55.object({type:z55.literal("search"),queries:z55.array(z55.string().min(1).max(256)).min(1).max(12),searchWindow:z55.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z55.number().int().min(1).max(50).optional(),includeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z55.array(z55.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z55.object({name:z55.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z55.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z55.string().min(1).max(2e3).optional(),judgeEnabled:z55.boolean().optional(),retentionDays:z55.number().int().min(1).max(365).optional(),notification:z55.object({email:z55.object({enabled:z55.boolean().default(!0),recipients:z55.array(z55.string().email()).min(1).max(20),includeDiffs:z55.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=z55.object({monitorId:z55.string().uuid(),name:z55.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z55.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z55.string().min(1).max(2e3).optional(),judgeEnabled:z55.boolean().optional(),retentionDays:z55.number().int().min(1).max(365).optional(),status:z55.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z55.object({monitorId:z55.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z55.string().uuid()}),RunProjectIntegrationToolRequestSchema=z55.object({tool:z55.string().min(1),input:z55.record(z55.string(),z55.unknown()),connectionAlias:z55.string().min(1).optional(),approval:z55.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z55.object({provider:z55.string().min(1),providerCredits:z55.number().nonnegative().optional(),providerCostUsd:z55.number().nonnegative().optional(),requests:z55.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z55.object({credits:z55.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),title:z55.string().optional(),statusCode:z55.number().optional(),markdown:z55.string().optional(),summary:z55.string().optional(),links:z55.array(z55.string()).optional(),images:z55.array(z55.string()).optional(),html:z55.string().optional(),json:z55.unknown().optional(),branding:z55.record(z55.string(),z55.unknown()).optional(),warning:z55.string().optional()}),FirecrawlSearchToolOutputSchema=z55.object({query:z55.string(),provider:z55.literal("firecrawl"),warning:z55.string().optional(),results:z55.array(z55.object({title:z55.string(),url:z55.string(),snippet:z55.string().optional(),content:z55.string().optional(),score:z55.number().optional(),publishedAt:z55.string().optional()}))}),FirecrawlResearchPaperSchema=z55.object({paperId:z55.string(),primaryId:z55.string().optional(),ids:z55.record(z55.string(),z55.array(z55.string())).optional(),title:z55.string().optional(),abstract:z55.string().optional(),score:z55.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z55.object({text:z55.string(),score:z55.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(z55.object({id:z55.string(),type:z55.string().min(1).optional(),url:z55.string(),title:z55.string().optional(),passages:z55.array(z55.object({text:z55.string()}).passthrough())}).passthrough()),coverage:z55.record(z55.string(),z55.string()).optional(),reranked:z55.boolean().optional(),repos:z55.array(z55.record(z55.string(),z55.unknown())).optional(),sources:z55.array(z55.record(z55.string(),z55.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),paper:z55.record(z55.string(),z55.unknown()),paperId:z55.string().optional(),query:z55.string().optional(),passages:z55.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),results:z55.array(FirecrawlResearchPaperSchema),poolSize:z55.number().int().nonnegative(),truncated:z55.boolean(),note:z55.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),count:z55.number(),links:z55.array(z55.object({url:z55.string(),title:z55.string().optional(),description:z55.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z55.object({url:z55.string(),provider:z55.literal("firecrawl"),total:z55.number(),pages:z55.array(z55.object({url:z55.string(),title:z55.string().optional(),statusCode:z55.number().optional(),markdown:z55.string().optional(),summary:z55.string().optional(),links:z55.array(z55.string()).optional(),images:z55.array(z55.string()).optional(),html:z55.string().optional(),warning:z55.string().optional()})),warning:z55.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z55.object({cron:z55.string().optional(),text:z55.string().optional(),timezone:z55.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z55.object({id:z55.string().optional(),type:z55.enum(["scrape","crawl","search"]).optional(),urls:z55.array(z55.string()).optional(),queries:z55.array(z55.string()).optional(),searchWindow:z55.string().optional(),maxResults:z55.number().optional(),includeDomains:z55.array(z55.string()).optional(),excludeDomains:z55.array(z55.string()).optional(),scrapeOptions:z55.record(z55.string(),z55.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z55.object({id:z55.string(),name:z55.string(),status:z55.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z55.string().nullable().optional(),lastRunAt:z55.string().nullable().optional(),currentCheckId:z55.string().nullable().optional(),targets:z55.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z55.string().nullable().optional(),judgeEnabled:z55.boolean().optional(),estimatedCreditsPerMonth:z55.number().optional(),createdAt:z55.string().optional(),updatedAt:z55.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z55.object({id:z55.string(),monitorId:z55.string(),scheduledFor:z55.string().nullable().optional(),startedAt:z55.string().nullable().optional(),finishedAt:z55.string().nullable().optional(),estimatedCredits:z55.number().nullable().optional(),reservedCredits:z55.number().nullable().optional(),actualCredits:z55.number().nullable().optional(),billingStatus:z55.string().nullable().optional(),summary:z55.object({totalPages:z55.number().optional(),same:z55.number().optional(),changed:z55.number().optional(),new:z55.number().optional(),removed:z55.number().optional(),error:z55.number().optional()}).passthrough().optional(),error:z55.string().nullable().optional(),createdAt:z55.string().optional(),updatedAt:z55.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitors:z55.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),deleted:z55.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),checks:z55.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z55.object({provider:z55.literal("firecrawl"),monitorId:z55.string(),check:FirecrawlMonitorCheckOutputSchema,next:z55.string().optional()}),FirecrawlToolKeySchema=z55.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=z55.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z55.object({projectId:z55.uuid(),integrationKey:z55.string().min(1),tool:z55.string().min(1),connectionAlias:z55.string().min(1).nullable().optional(),output:z55.record(z55.string(),z55.unknown()),executedAt:z55.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z55.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z55.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z55.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z55.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z55.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z55.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z55.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z55.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z55.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z55.array(ProjectChannelCandidateDTOSchema))}});import{z as z56}from"zod";var IntegrationIdSchema,IntegrationScopeSchema,IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema,IntegrationAuthSchema,IntegrationRecipeSchema,IntegrationSettingSchema,IntegrationToolsSchema,IntegrationSkillSchema,IntegrationManifestSchema,IntegrationPermissionDTOSchema,IntegrationSettingDefinitionDTOSchema,IntegrationKindSchema,IntegrationSummaryDTOSchema,IntegrationAccountDTOSchema,IntegrationSiteDTOSchema,OrganizationIntegrationDTOSchema,ProjectIntegrationDTOSchema,IntegrationReturnPathSchema,StartIntegrationInstallRequestSchema,StartIntegrationInstallDTOSchema,AddOrganizationMcpServerDTOSchema,ConnectIntegrationKeyRequestSchema,ReplaceIntegrationServerCredentialsRequestSchema,UpdateIntegrationSiteRequestSchema,UpdateIntegrationSitesRequestSchema,UpdateProjectIntegrationSettingsRequestSchema,IntegrationSettingOptionDTOSchema,IntegrationToolMatchDTOSchema,ProjectIntegrationGuideDTOSchema,APPROVAL_TOKEN_MAX,REQUEST_TOKEN_MAX,RunIntegrationToolRequestSchema,IntegrationApprovalCallShape,IntegrationToolRunResultDTOSchema,IntegrationApprovalPreviewRequestSchema,IntegrationApprovalPreviewDTOSchema,RoutineIntegrationApprovalSchema,IntegrationApprovalDecisionSchema,DecideIntegrationApprovalRequestSchema,IntegrationApprovalDecisionDTOSchema,IntegrationAgentAccessDTOSchema,init_integration_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration-catalog.dto.js"(){"use strict";init_integration_dto();IntegrationIdSchema=z56.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z56.strictObject({scope:z56.string().min(1),reason:z56.string().min(1).max(200)}),IntegrationOAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("oauth"),actor:z56.literal("user").default("user"),authorizationUrl:z56.url(),tokenUrl:z56.url(),revocationUrl:z56.url().optional(),userInfoUrl:z56.url().optional(),client:z56.strictObject({idEnv:z56.string().min(1),secretEnv:z56.string().min(1)}),authorizeParams:z56.record(z56.string(),z56.string()).default({}),scopes:z56.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("apiKey"),keyLabel:z56.string().min(1).max(80),placeholder:z56.string().min(1).max(40).optional(),helpUrl:z56.url()}),IntegrationProviderAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("provider")}),IntegrationMcpAuthSchema=z56.strictObject({id:z56.string().min(1).max(40),label:z56.string().min(1).max(80),kind:z56.literal("mcp"),methods:z56.array(McpIntegrationSetupAuthSchema).min(1),scopes:z56.array(z56.string().min(1)).min(1).optional(),header:z56.object({name:z56.string().min(1).max(80),valuePrefix:z56.string().max(80)}).optional()}),IntegrationAuthSchema=z56.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z56.strictObject({title:z56.string().min(1).max(80),description:z56.string().min(1).max(300),command:z56.string().min(1).optional()}),IntegrationSettingSchema=z56.strictObject({type:z56.enum(["string","choice"]),label:z56.string().min(1).max(80),description:z56.string().min(1).max(300).optional(),required:z56.boolean().default(!1),optionsFrom:z56.strictObject({tool:z56.string().min(1)}).optional()}),IntegrationToolsSchema=z56.discriminatedUnion("source",[z56.strictObject({source:z56.literal("hosted")}),z56.strictObject({source:z56.literal("mcp"),url:z56.url()})]),IntegrationSkillSchema=z56.strictObject({name:z56.string().min(1).max(64),description:z56.string().min(1).max(300),content:z56.string().min(1)}),IntegrationManifestSchema=z56.strictObject({apiVersion:z56.literal(1),id:IntegrationIdSchema,version:z56.string().regex(/^\d+\.\d+\.\d+$/),listing:z56.strictObject({name:z56.string().min(1).max(60),description:z56.string().min(1).max(200),details:z56.string().min(1).max(1e3),icon:z56.string().min(1),category:z56.enum(["seo","ai-visibility","analytics","communication"]),publisher:z56.string().min(1).max(60),agentReads:z56.strictObject({label:z56.string().min(1).max(80),description:z56.string().min(1).max(200)}).optional()}),auth:z56.array(IntegrationAuthSchema).min(1),identity:z56.strictObject({label:z56.string().min(1)}).optional(),settings:z56.record(z56.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z56.array(IntegrationSkillSchema).default([]),recipes:z56.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z56.object({scope:z56.string(),reason:z56.string()}),IntegrationSettingDefinitionDTOSchema=z56.object({key:z56.string(),type:z56.enum(["string","choice"]),label:z56.string(),description:z56.string().nullable(),required:z56.boolean(),hasOptions:z56.boolean()}),IntegrationKindSchema=z56.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z56.object({id:z56.string(),kind:IntegrationKindSchema,integrationKey:z56.string(),host:z56.string().nullable(),apiKey:z56.object({label:z56.string(),placeholder:z56.string().nullable(),helpUrl:z56.string(),primary:z56.boolean()}).nullable(),mcp:z56.object({url:z56.string(),methods:z56.array(McpIntegrationSetupAuthSchema),header:z56.object({name:z56.string(),valuePrefix:z56.string()}).nullable()}).nullable(),name:z56.string(),description:z56.string(),details:z56.string(),icon:z56.string(),category:z56.string(),publisher:z56.string(),signInLabel:z56.string(),permissions:z56.array(IntegrationPermissionDTOSchema),readOnly:z56.boolean(),settings:z56.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z56.object({connectionId:z56.uuid(),alias:z56.string(),accountName:z56.string().nullable(),status:z56.enum(["active","revoked"]),authKind:z56.enum(["oauth","api_key"]),connectedAt:z56.coerce.date()}),IntegrationSiteDTOSchema=z56.object({projectId:z56.uuid(),projectName:z56.string(),enabled:z56.boolean(),granted:z56.boolean(),connectionId:z56.uuid().nullable(),settings:z56.record(z56.string(),z56.string()),missingSettings:z56.array(z56.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z56.boolean(),accounts:z56.array(IntegrationAccountDTOSchema),siteAccess:z56.enum(["all","selected"]),sites:z56.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z56.boolean(),enabled:z56.boolean(),granted:z56.boolean(),accountName:z56.string().nullable(),settingsValues:z56.record(z56.string(),z56.string()),missingSettings:z56.array(z56.string()),tools:z56.array(z56.object({key:z56.string(),name:z56.string(),description:z56.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z56.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z56.object({projectId:z56.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z56.object({connectUrl:z56.url().nullable(),expiresAt:z56.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z56.string()}),ConnectIntegrationKeyRequestSchema=z56.object({key:z56.string().trim().min(1).max(500),projectId:z56.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z56.object({token:z56.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z56.object({enabled:z56.boolean(),connectionId:z56.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z56.object({access:z56.enum(["all","selected"]).optional(),projectIds:z56.array(z56.uuid()).max(1e3),connectionId:z56.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z56.object({settings:z56.record(z56.string(),z56.string().max(500))}),IntegrationSettingOptionDTOSchema=z56.object({value:z56.string(),label:z56.string(),suggested:z56.boolean()}),IntegrationToolMatchDTOSchema=z56.object({integrationId:z56.string(),integrationName:z56.string(),key:z56.string(),name:z56.string(),description:z56.string(),effect:IntegrationToolEffectSchema,input:z56.record(z56.string(),z56.unknown())}),ProjectIntegrationGuideDTOSchema=z56.object({integrationId:z56.string(),name:z56.string(),description:z56.string(),content:z56.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z56.object({tool:z56.string().min(1).max(120),input:z56.record(z56.string(),z56.unknown()).default({}),approval:z56.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z56.boolean().optional()}),IntegrationApprovalCallShape={integration:z56.object({id:z56.string(),name:z56.string()}),tool:z56.object({key:z56.string(),name:z56.string(),effect:IntegrationToolEffectSchema}),input:z56.record(z56.string(),z56.unknown()),reason:z56.string(),canAlwaysAllow:z56.boolean()},IntegrationToolRunResultDTOSchema=z56.discriminatedUnion("status",[z56.object({status:z56.literal("ok"),output:z56.record(z56.string(),z56.unknown())}),z56.object({status:z56.literal("approval_required"),request:z56.string(),approveUrl:z56.string(),...IntegrationApprovalCallShape}),z56.object({status:z56.literal("blocked"),reason:z56.string()})]),IntegrationApprovalPreviewRequestSchema=z56.object({request:z56.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z56.object({...IntegrationApprovalCallShape,allowOnce:z56.boolean(),expiresAt:z56.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z56.string()}),IntegrationApprovalDecisionSchema=z56.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z56.object({request:z56.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z56.object({decision:IntegrationApprovalDecisionSchema,approval:z56.string().optional(),resumed:z56.boolean().optional()}),IntegrationAgentAccessDTOSchema=z56.object({reads:z56.object({label:z56.string(),description:z56.string()}).nullable(),tools:z56.array(z56.object({tool:z56.string(),label:z56.string(),description:z56.string(),allowed:z56.boolean()}))})}});import{z as z57}from"zod";var CodeSyncProviderSchema,CodeSyncAvailabilityDTOSchema,CodeSyncAvailabilityDTO,CodeSyncStatusSchema,CodeSyncErrorCodeSchema,CodeSyncAccountSchema,CodeSyncRepositorySchema,CodeSyncBranchStatusSchema,CodeSyncBranchDTOSchema,CodeSyncConnectionDTOSchema,CodeSyncConnectionDTO,CodeSyncDTOSchema,CodeSyncDTO,CreateCodeSyncConnectionRequestSchema,CreateCodeSyncRepositoryRequestSchema,ActivateCodeSyncConnectionRequestSchema,AuthorizeCodeSyncResponseSchema,CodeSyncJobSchema,init_code_sync_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/code-sync.dto.js"(){"use strict";init_create_dto();CodeSyncProviderSchema=z57.enum(["github"]),CodeSyncAvailabilityDTOSchema=z57.object({enabled:z57.boolean()}),CodeSyncAvailabilityDTO=createDTO(CodeSyncAvailabilityDTOSchema),CodeSyncStatusSchema=z57.enum(["connecting","choose_repository","creating","creation_unknown","access_required","checking_branches","waiting_for_code","partial","syncing","up_to_date","error","stopping"]),CodeSyncErrorCodeSchema=z57.enum(["access_required","conflict","rejected","unavailable","unsupported","limit","creation_unknown","creation_failed","authorization_expired","project_changed","configuration","source_missing","source_changed"]),CodeSyncAccountSchema=z57.object({installationId:z57.number().int().positive(),login:z57.string(),type:z57.enum(["User","Organization"])}),CodeSyncRepositorySchema=z57.object({id:z57.number().int().positive(),name:z57.string(),fullName:z57.string(),url:z57.string().url(),visibility:z57.enum(["private","public"])}),CodeSyncBranchStatusSchema=z57.enum(["pending","syncing","up_to_date","waiting_for_code","conflict","error","retired"]),CodeSyncBranchDTOSchema=z57.object({id:z57.string().uuid(),branchName:z57.string(),status:CodeSyncBranchStatusSchema,errorCode:CodeSyncErrorCodeSchema.nullable(),expectedHead:z57.string().nullable(),pendingTarget:z57.string().nullable(),lastSyncedAt:z57.string().datetime().nullable(),nextAttemptAt:z57.string().datetime()}),CodeSyncConnectionDTOSchema=z57.object({id:z57.string().uuid(),provider:CodeSyncProviderSchema,status:CodeSyncStatusSchema,repository:CodeSyncRepositorySchema.nullable(),accountLogin:z57.string().nullable(),accounts:z57.array(CodeSyncAccountSchema),installUrl:z57.string().url().nullable(),installationSettingsUrl:z57.string().url().nullable(),nextAttemptAt:z57.string().datetime(),errorCode:CodeSyncErrorCodeSchema.nullable(),branches:z57.array(CodeSyncBranchDTOSchema),counts:z57.object({total:z57.number().int().nonnegative(),upToDate:z57.number().int().nonnegative(),conflicts:z57.number().int().nonnegative(),pending:z57.number().int().nonnegative(),errors:z57.number().int().nonnegative(),waiting:z57.number().int().nonnegative()})}),CodeSyncConnectionDTO=createDTO(CodeSyncConnectionDTOSchema),CodeSyncDTOSchema=z57.object({providers:z57.array(z57.object({id:CodeSyncProviderSchema,available:z57.boolean()})),connections:z57.array(CodeSyncConnectionDTOSchema)}),CodeSyncDTO=createDTO(CodeSyncDTOSchema),CreateCodeSyncConnectionRequestSchema=z57.object({provider:CodeSyncProviderSchema}).strict(),CreateCodeSyncRepositoryRequestSchema=z57.object({installationId:z57.number().int().positive(),repositoryName:z57.string().trim().min(1).max(100).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(name=>name!=="."&&name!==".."&&!name.endsWith(".git")),visibility:z57.enum(["private","public"]).default("private")}).strict(),ActivateCodeSyncConnectionRequestSchema=z57.object({installationId:z57.number().int().positive(),repositoryId:z57.number().int().positive()}).strict(),AuthorizeCodeSyncResponseSchema=z57.object({url:z57.string().url()}),CodeSyncJobSchema=z57.object({version:z57.literal(2),connectionId:z57.string().uuid(),connectionGeneration:z57.string().uuid(),siteGeneration:z57.string().uuid()}).strict()}});import{z as z58}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,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=z58.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z58.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z58.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z58.object({userId:z58.string().min(1),name:z58.string(),email:z58.string().min(1),subscribed:z58.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z58.object({maxSubscribers:z58.number().int().positive(),subscriberCount:z58.number().int().nonnegative(),effectiveRecipientCount:z58.number().int().nonnegative(),currentUserSubscribed:z58.boolean(),candidates:z58.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z58.object({userIds:z58.array(z58.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z58.object({topic:UserManagedNotificationTopicSchema,enabled:z58.boolean(),source:z58.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z58.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z58.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z58.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z58.string().nullable(),maskedEmail:z58.string().min(1),applied:z58.boolean(),expiresAt:z58.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z58.object({scheduleId:z58.string().min(1),scheduleName:z58.string(),projectId:z58.string().min(1),projectName:z58.string(),env:z58.string().min(1)}),FollowedSchedulesSchema=z58.object({schedules:z58.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z59}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=z59.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=z59.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z59.uuid(),env:z59.string().min(1),name:z59.string().min(1),cron:z59.string().min(1),command:z59.string().min(1),secretKeys:z59.array(z59.string().min(1)),enabled:z59.boolean(),lastRunAt:z59.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z59.string().nullable(),suspendedAt:z59.coerce.date().nullable().optional(),suspensionReason:z59.string().nullable().optional(),overPolicyReasons:z59.array(z59.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z59.object({name:z59.string().min(1).max(120),cron:z59.string().min(1).max(120),command:z59.string().min(1).max(500),secretKeys:z59.array(ProjectSecretKeySchema).default([]),enabled:z59.boolean().optional()}),UpdateProjectScheduleRequestSchema=z59.object({name:z59.string().min(1).max(120).optional(),cron:z59.string().min(1).max(120).optional(),command:z59.string().min(1).max(500).optional(),secretKeys:z59.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z59.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z59.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z59.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z59.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z59.object({maxRuns:z59.number().int().positive(),retentionDays:z59.number().int().positive().nullable(),outputRetentionDays:z59.number().int().positive(),maxOutputBytes:z59.number().int().positive()}),SchedulePolicyStateSchema=z59.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z59.object({code:z59.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z59.enum(["cached_subscription","free_fallback"]),activeSchedules:z59.object({used:z59.number().int().nonnegative(),limit:z59.number().int().nonnegative()}),minCadenceMinutes:z59.number().int().positive(),maxRunMs:z59.number().int().positive(),concurrency:z59.object({used:z59.number().int().nonnegative(),limit:z59.number().int().positive()}),compute:z59.object({settledMs:z59.number().int().nonnegative(),activeMs:z59.number().int().nonnegative(),reservedMs:z59.number().int().nonnegative().optional(),includedMs:z59.number().int().nonnegative(),remainingMs:z59.number().int().nonnegative(),resetsAt:z59.coerce.date()}),upgrade:z59.object({code:z59.literal("Pro"),activeSchedulesLimit:z59.number().int().positive(),minCadenceMinutes:z59.number().int().positive(),maxRunMs:z59.number().int().positive(),maxConcurrentRuns:z59.number().int().positive(),computeIncludedMs:z59.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z59.array(z59.string())}),ProjectScheduleUsageSchema=z59.object({runCount:z59.number().int().nonnegative(),runsWithOutput:z59.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z59.object({id:z59.uuid(),scheduleId:z59.uuid(),projectId:z59.uuid(),env:z59.string().min(1),scheduleName:z59.string().min(1),command:z59.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z59.object({id:z59.string().min(1),name:z59.string().min(1)}).nullable(),queuedAt:z59.coerce.date(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),exitCode:z59.number().int().nullable(),errorCode:z59.string().nullable(),error:z59.string().nullable(),outputBytes:z59.number().int().nonnegative(),outputTruncated:z59.boolean(),outputExpiresAt:z59.coerce.date().nullable(),metadataExpiresAt:z59.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z59.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z59.coerce.date().nullable(),items:z59.array(z59.object({key:z59.string().min(1),updatedAt:z59.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z59.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z59.object({trigger:z59.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z59.object({limit:z59.coerce.number().int().min(1).max(100).default(25),cursor:z59.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z59.object({items:z59.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z59.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z59.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z59.object({items:z59.array(ProjectScheduleRunDTOSchema),nextCursor:z59.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z60}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z60.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z60.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z60.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z60.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z60.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z60.discriminatedUnion("kind",[z60.object({kind:z60.literal("user"),userId:z60.string().min(1)}).strict(),z60.object({kind:z60.literal("agent"),agentKey:z60.string().min(1).max(120),agentId:z60.uuid().optional()}).strict(),z60.object({kind:z60.literal("system")}).strict()]),NotificationSummarySchema=z60.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z60.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z60.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z60.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z60.object({sessionId:z60.uuid(),branch:z60.string().min(1),targetBranch:z60.string().min(1),revision:z60.string().min(1),fingerprint:z60.string().min(1)}),NotificationPayloadSchema=z60.discriminatedUnion("topic",[z60.object({topic:z60.literal("database_quota_exceeded"),incidentId:z60.uuid(),observedAt:z60.iso.datetime()}).strict(),z60.object({topic:z60.literal("agent_run_outcome"),threadId:z60.uuid(),invocationId:z60.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("agent_retained_review"),threadId:z60.uuid().optional(),invocationId:z60.uuid().optional(),proposalId:z60.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("agent_conflict"),mergeId:z60.uuid(),threadId:z60.uuid().optional(),invocationId:z60.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z60.object({topic:z60.literal("publication_failed"),publicationId:z60.uuid(),sourceBranch:z60.string().trim().min(1).max(120),failureCode:z60.string().trim().min(1).max(64),failedAt:z60.iso.datetime(),firstPublication:z60.boolean()}).strict()]),NotificationEnvelopeSchema=z60.object({id:z60.uuid(),projectId:z60.uuid(),sourceKey:z60.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z60.literal(1),payload:NotificationPayloadSchema,createdAt:z60.coerce.date()}),NotificationDeliveryStateSchema=z60.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z60.object({id:z60.uuid(),notificationRecipientId:z60.uuid(),projectId:z60.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z60.number().int().nonnegative(),nextAttemptAt:z60.coerce.date().nullable(),lastAttemptAt:z60.coerce.date().nullable(),sentAt:z60.coerce.date().nullable(),failureCode:z60.string().max(80).nullable(),createdAt:z60.coerce.date(),updatedAt:z60.coerce.date()}),NotificationPreferenceSchema=z60.object({topic:WorkNotificationTopicSchema,channel:z60.literal("email"),enabled:z60.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z60.enum(["default","explicit"])})}});import{z as z61}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","publishing","schedule","marketing"],NotificationPreferenceGroupSchema=z61.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","schedule.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z61.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z61.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z61.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z61.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z61.object({enabled:z61.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z61.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z61.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z61.discriminatedUnion("kind",[z61.object({kind:z61.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z61.enum(["work_review","publishing","schedule"]),enabled:z61.boolean(),source:PreferenceSourceSchema}).strict(),z61.object({kind:z61.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z61.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z61.object({kind:z61.literal("provider_subscription"),id:z61.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z61.literal("marketing"),name:z61.string(),description:z61.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z61.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z61.object({email:EmailNotificationPreferenceSchema,entries:z61.array(NotificationPreferenceEntrySchema),unavailableGroups:z61.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z61.object({enabled:z61.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z61.discriminatedUnion("kind",[z61.object({kind:z61.literal("toggle"),enabled:z61.boolean()}).strict(),z61.object({kind:z61.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z61.object({kind:z61.literal("provider_subscription"),enabled:z61.boolean()}).strict()])}});import{z as z62}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=z62.object({surface:SurfaceNameSchema,key:z62.string(),label:z62.string()}),InlineSchema=z62.object({text:z62.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z62.discriminatedUnion("type",[z62.object({type:z62.literal("paragraph"),content:z62.array(InlineSchema).max(24)}),z62.object({type:z62.literal("preview"),ref:DiffRefSchema,caption:z62.string().optional()}),z62.object({type:z62.literal("code"),code:z62.string(),lang:z62.string().optional(),caption:z62.string().optional()}),z62.object({type:z62.literal("risk"),level:z62.enum(["warning","error"]),content:z62.array(InlineSchema).max(24)}),z62.object({type:z62.literal("list"),items:z62.array(z62.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z62.object({headline:z62.string(),blocks:z62.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z62.object({summary:EnvDiffSummarySchema,fingerprint:z62.string(),generatedAt:z62.coerce.date(),cached:z62.boolean().optional(),credits:z62.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z63}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z63.object({date:z63.string(),visitors:z63.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z63.object({key:z63.string(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z63.object({path:z63.string(),pageName:z63.string().nullable().optional(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z63.object({preset:z63.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z63.string(),requestedTo:z63.string(),effectiveFrom:z63.string(),effectiveTo:z63.string(),isRetentionLimited:z63.boolean(),groupBy:z63.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z63.object({date:z63.string(),content:z63.string(),updatedAt:z63.string(),updatedByUserId:z63.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z63.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z63.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z63.number().int().nonnegative(),pageviews:z63.number().int().nonnegative(),botPageviews:z63.number().int().nonnegative(),botVisitors:z63.number().int().nonnegative(),bounceRate:z63.number().min(0).max(100),viewsPerVisit:z63.number().nonnegative(),averageVisitDurationSeconds:z63.number().nonnegative(),visitorsSeries:z63.array(ProjectDailyVisitorsDTOSchema),topPages:z63.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z63.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z63.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z63.object({state:z63.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z63.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z64}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=z64.object({id:z64.string(),email:z64.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z64.coerce.date(),createdAt:z64.coerce.date(),inviterUserId:z64.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z64.object({id:z64.string(),token:z64.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z64.object({success:z64.boolean(),projectId:z64.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z65}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=z65.object({id:z65.string(),name:z65.string(),image:z65.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z65.object({count:z65.int(),canRefer:z65.boolean(),eligibleAt:z65.iso.datetime().nullable()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z65.object({counts:z65.object({signed_up:z65.int(),activated:z65.int()}),credits:z65.object({total:z65.int(),earned:z65.int()}),canRefer:z65.boolean(),eligibleAt:z65.iso.datetime().nullable()}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z65.email(),emailVerified:z65.boolean(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z66}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=z66.object({id:z66.string(),principalType:ProjectPrincipalTypeSchema,principalId:z66.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z66.coerce.date(),expiresAt:z66.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z66.boolean().default(!1)}),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","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","locale:add","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","branch:create","environment:create","integration:manage","integration:run","sync:code","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z66.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z66.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z66.record(z66.string(),z66.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z66.object({access:z66.array(ProjectAccessItemDTOSchema),invites:z66.array(ProjectInviteDTOSchema),organization:z66.object({name:z66.string().nullable(),logo:z66.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z66.object({success:z66.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z66.object({success:z66.boolean(),projectId:z66.uuid()}))}});import{z as z67}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=z67.object({publicationStatus:PublicationStatusSchema,appUrl:z67.string().nullable(),lastPublishedAt:z67.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z68}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z68.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z68.object({branch:BranchSchema,revision:z68.string().min(1).max(64).nullable(),generation:z68.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z68.url().nullable()})}});import{z as z69}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewStartFailureSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewUpgradeRequiredSchema=z69.object({code:z69.literal("PREVIEW_UPGRADE_REQUIRED"),message:z69.string(),currentVersion:z69.number().int().positive(),targetVersion:z69.literal(4)}),PreviewBridgePackageSchema=z69.object({name:z69.string().min(1),version:z69.string().min(1)}),PreviewBridgeCapabilitySchema=z69.object({integrated:z69.boolean(),packages:z69.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z69.object({url:z69.url(),expiresAt:z69.iso.datetime().nullable(),source:z69.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z69.object({name:z69.string().min(1),locator:z69.string().min(1).optional(),source:z69.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z69.object({kind:z69.literal("dependency_build_scripts_blocked"),packageManager:z69.enum(["pnpm","yarn","bun"]),packages:z69.array(z69.string()),targets:z69.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z69.string(),approvalKey:z69.string(),command:z69.string().optional(),approval:z69.object({id:z69.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z69.object({code:z69.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z69.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z69.object({code:z69.literal("PREVIEW_START_FAILED"),message:z69.string(),logTail:z69.array(z69.string()).optional(),logTailTruncated:z69.boolean().optional()}),SandboxPullPhaseSchema=z69.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z69.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z69.object({message:z69.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z69.number().int().optional().catch(void 0),logTail:z69.array(z69.string()).optional().catch(void 0),logTailTruncated:z69.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z69.object({approvalId:z69.uuid()}),PreviewInstallPolicyApprovalEventSchema=z69.discriminatedUnion("type",[z69.object({type:z69.literal("progress"),step:z69.enum(["approval","install","restart","readiness"]),message:z69.string()}),z69.object({type:z69.literal("approved")}),z69.object({type:z69.literal("complete")}),z69.object({type:z69.literal("error"),code:z69.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z69.string()})])}});import{z as z70}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,OrganizationProjectCapacityDTOSchema,OrganizationProjectCapacityDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z70.string(),slug:z70.string().nullable(),logo:z70.string().nullable(),metadata:z70.record(z70.string(),z70.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z70.object({id:z70.string(),name:z70.string(),email:z70.email(),image:z70.string().nullable()}),OrganizationMemberDTOSchema=z70.object({id:z70.string(),userId:z70.string(),organizationId:z70.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z70.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z70.object({canCreateProject:z70.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z71}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z71.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z71.object({reason:CancellationReasonCodeSchema,details:z71.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z71.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z71.object({offerVersion:z71.string().trim().min(1),unusedPremiumCreditAmount:z71.number().int().nonnegative(),amountDueNow:z71.number().int().nonnegative(),renewsOn:z71.string()}),PlanMigrationPreviewDTOSchema=z71.object({currency:z71.string().trim().min(1),unusedPremiumCreditAmount:z71.number().int().nonnegative(),amountDueNow:z71.number().int().nonnegative(),startsAt:z71.string(),renewsAt:z71.string(),nextRenewalAmount:z71.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z71.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z71.object({id:z71.string(),organizationId:z71.string(),legacySubscriptionId:z71.string(),offeredPlanCode:z71.string(),offeredPlanName:z71.string(),offeredPriceAmount:z71.number(),offeredCurrency:z71.string(),offerVersion:z71.string(),state:PlanMigrationStateSchema,checkoutToken:z71.string().nullable(),deadlineAt:z71.string(),transitions:z71.array(z71.object({event:z71.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z71.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z71.object({included:z71.number().optional(),unitPrice:z71.number().optional(),dailyCap:z71.number().nullable().optional()}),EntitlementsDTOSchema=z71.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z71.object({retentionDays:z71.number().int().positive(),canUseExtendedDateRanges:z71.boolean()}).optional(),history:z71.object({retentionDays:z71.number().int().positive()}).optional(),members:z71.object({canInvite:z71.boolean(),maxMembers:z71.number().int().positive().nullable()}).optional(),projects:z71.object({maxProjects:z71.number().int().positive().nullable()}).optional(),domains:z71.object({canUseCustomDomains:z71.boolean(),maxDomains:z71.number().int().nonnegative().nullable()}).optional(),media_storage:z71.object({limitBytes:z71.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z71.object({usedBytes:z71.number().int().nonnegative().nullable(),limitBytes:z71.number().int().nonnegative().nullable(),state:z71.enum(["ready","unavailable"]),measuredAt:z71.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z71.object({toPlanCode:TemplateCodeSchema,effectiveAt:z71.string(),scheduledAt:z71.string().nullable()}),AutomaticSpendStopDTOSchema=z71.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z71.string(),spendStopped:z71.boolean(),settlementEndsAt:z71.string()}),HostingOverageStatusDTOSchema=z71.object({state:z71.enum(["ready","unavailable"]),planCode:z71.string(),overageAvailable:z71.boolean(),overageEnabled:z71.boolean(),monthlyCapUsd:z71.number().int().positive().nullable(),periodStart:z71.iso.datetime().nullable(),periodEnd:z71.iso.datetime().nullable(),usedBytes:z71.number().nonnegative().nullable(),includedBytes:z71.number().nonnegative().nullable(),overageBytes:z71.number().nonnegative(),currentOverageAmountMicros:z71.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z71.number().nonnegative().nullable(),currency:z71.string().nullable(),status:z71.enum(["ok","near_limit","paused"]),databaseCompute:z71.object({includedHoursPerSite:z71.number().nonnegative().nullable(),overageHours:z71.number().nonnegative(),fundedHours:z71.number().nonnegative(),sitesOverAllowance:z71.number().int().nonnegative(),rateMicrosPerHour:z71.number().nonnegative().nullable(),amountMicros:z71.number().nonnegative().nullable(),budgetSpent:z71.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z71.object({enabled:z71.boolean(),monthlyCapUsd:z71.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z71.object({id:z71.string(),external_id:z71.string(),customerId:z71.string(),planId:z71.string(),planCode:z71.union([TemplateCodeSchema,z71.literal("Unknown")]),currentPeriod:z71.object({start:z71.string(),end:z71.string().nullable()}),cancelAt:z71.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z71.string(),nextPaymentAt:z71.string().nullable(),baseAmount:z71.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z71.object({totalCap:z71.number(),dailyCap:z71.number(),usedTotal:z71.number()}),CreditBalanceDTOSchema=z71.object({total:z71.number(),base:z71.number(),dailyBase:z71.number(),purchases:z71.number(),awards:z71.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z71.object({total:z71.number(),nearLimit:z71.boolean(),canChat:z71.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z71.object({dailyFreeAvailable:z71.number(),monthlyAvailable:z71.number(),purchasedAvailable:z71.number(),awardedAvailable:z71.number()}),ProjectDailyCreditAllowanceDTOSchema=z71.object({periodCap:z71.number(),dailyGrant:z71.number(),usedThisPeriod:z71.number(),remainingThisPeriod:z71.number()}),ProjectCreditBalanceDTOSchema=z71.object({projectId:z71.uuid(),organizationId:z71.string(),balance:z71.object({totalAvailable:z71.number(),nearLimit:z71.boolean(),canUseAi:z71.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z71.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z71.discriminatedUnion("enabled",[z71.object({enabled:z71.literal(!0),thresholdUsd:z71.number().nonnegative(),refillAmountUsd:z71.number().nonnegative()}),z71.object({enabled:z71.literal(!1),thresholdUsd:z71.number().nonnegative().nullable(),refillAmountUsd:z71.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z71.discriminatedUnion("enabled",[z71.object({enabled:z71.literal(!0),thresholdUsd:z71.number().min(.01).multipleOf(.01),refillAmountUsd:z71.number().min(.01).multipleOf(.01),expectedRateToken:z71.string().trim().min(1).max(40)}).strict(),z71.object({enabled:z71.literal(!1),thresholdUsd:z71.number().min(.01).multipleOf(.01),expectedRateToken:z71.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z71.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z71.object({planCode:z71.union([TemplateCodeSchema,z71.literal("Unknown")]).nullable(),canPurchase:z71.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z71.number().int().positive(),minAmountUsd:z71.number().positive(),maxAmountUsd:z71.number().positive(),rateToken:z71.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z71.object({amountUsd:z71.number(),idempotencyKey:z71.string().trim().min(8).max(120),expectedRateToken:z71.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z71.object({invoiceId:z71.string(),newBalance:z71.int(),creditCount:z71.int(),amountUsd:z71.number(),creditsPerDollar:z71.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z71.object({url:z71.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z71.object({id:z71.string(),number:z71.string().nullable(),status:z71.string(),amountDue:z71.int(),currency:z71.string(),issuedAt:z71.string().nullable(),hostedInvoiceUrl:z71.string().nullable()}),PaymentRecoveryDTOSchema=z71.discriminatedUnion("status",[z71.object({status:z71.literal("eligible"),checkedAt:z71.string()}),z71.object({status:z71.literal("recovery_required"),checkedAt:z71.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z71.int().min(1)}),z71.object({status:z71.literal("unavailable"),checkedAt:z71.string(),reason:z71.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),CreditPurchasePricingResponseSchema=createResponseSchema(CreditPurchasePricingDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema),PaymentRecoveryResponseSchema=createResponseSchema(PaymentRecoveryDTOSchema)}});import{z as z72}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=z72.object({brand:z72.string(),last4:z72.string(),exp:z72.string(),isDefault:z72.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z73}from"zod";var SignupMarketingConsentModeSchema,SignupMarketingConsentDTOSchema,SignupMarketingConsentResponseSchema,MarketingOptInRequestSchema,init_marketing_consent_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/marketing-consent.dto.js"(){"use strict";init_response();SignupMarketingConsentModeSchema=z73.enum(["checkbox","notice"]),SignupMarketingConsentDTOSchema=z73.object({mode:SignupMarketingConsentModeSchema}),SignupMarketingConsentResponseSchema=createResponseSchema(SignupMarketingConsentDTOSchema),MarketingOptInRequestSchema=z73.object({consent:SignupMarketingConsentModeSchema})}});import{z as z74}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=z74.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z74.object({type:z74.literal("renameField"),contentType:z74.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z74.object({enabled:z74.boolean()}).strict(),ContentFieldGroupSchema=z74.object({id:z74.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z74.string().min(1).max(255),default:z74.boolean().optional()}).strict(),ContentTypeDTOSchema=z74.object({id:z74.string(),name:z74.string(),label:z74.string(),isSingleton:z74.boolean(),i18n:ContentTypeI18nSchema,description:z74.string().nullable().default(null),groups:z74.array(ContentFieldGroupSchema).default([]),fields:z74.record(z74.string(),FieldDefinitionSchema),createdAt:z74.string(),updatedAt:z74.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z74.object({contentTypes:z74.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z74.object({id:z74.string(),entryId:z74.string(),documentId:z74.string(),slug:z74.string(),locale:z74.string().optional(),createdAt:z74.string(),updatedAt:z74.string(),__fimo:z74.object({contentType:z74.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z74.object({data:z74.array(EntryDTOSchema),meta:z74.object({limit:z74.number(),offset:z74.number(),total:z74.number(),hasMore:z74.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z74.object({contentType:z74.string(),count:z74.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z74.object({counts:z74.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z74.object({count:z74.number().int().nonnegative(),sourceLocale:z74.string(),targetLocale:z74.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z74.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z74.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z74.union([z74.string(),z74.number(),z74.boolean(),z74.null()]),entryWhereOperatorSchema=z74.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z74.array(entryWhereScalarSchema).optional(),$nin:z74.array(entryWhereScalarSchema).optional(),$contains:z74.string().optional(),$startsWith:z74.string().optional(),$null:z74.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z74.record(z74.string(),z74.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z74.record(z74.string(),z74.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z74.object({data:z74.record(z74.string(),z74.unknown()),locale:z74.string().min(1).optional(),documentId:z74.uuid().optional()}),entryIdsSchema=z74.array(z74.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z74.object({sql:z74.string().min(1)}),BulkCreateEntriesRequestSchema=z74.object({entries:z74.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z74.union([z74.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z74.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z74.object({updates:z74.array(z74.object({id:z74.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z74.union([z74.object({ids:entryIdsSchema,locale:z74.string().min(1).optional()}),z74.object({where:EntryWhereSchema,locale:z74.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z74.object({data:z74.array(z74.record(z74.string(),z74.unknown())),meta:z74.object({rowCount:z74.number().int().nonnegative(),truncated:z74.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z74.object({data:z74.array(EntryDTOSchema),meta:z74.object({created:z74.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z74.object({data:z74.array(EntryDTOSchema),meta:z74.object({updated:z74.number().int().nonnegative(),missing:z74.array(z74.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z74.object({data:z74.array(EntryDTOSchema),meta:z74.object({deleted:z74.number().int().nonnegative(),missing:z74.array(z74.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z75}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z75.object({index:z75.number().int().nonnegative(),contentType:z75.string(),field:z75.string(),value:z75.string(),against:z75.enum(["stored","batch"]),ownerDocumentId:z75.uuid().optional(),ownerIndex:z75.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z75.object({code:z75.literal("unique_conflict"),message:z75.string(),conflicts:z75.array(UniqueConflictSchema),truncated:z75.boolean().optional()})}});import{z as z76}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=z76.object({kind:z76.literal("unique_conflict"),contentType:z76.string(),field:z76.string(),value:z76.string(),documentCount:z76.number().int().positive(),documentIds:z76.array(z76.uuid()),documentIdsTruncated:z76.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z76.object({code:z76.literal("schema_transition_rejected"),message:z76.string(),issues:z76.array(SchemaTransitionIssueSchema),truncated:z76.boolean().optional()})}});import{z as z77}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=z77.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z77.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z77.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z77.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z77.object({field:CmsFieldNameSchema,direction:z77.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z77.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z77.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z77.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z77.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z77.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z78}from"zod";var ContentOverviewPageSchema,ContentOverviewViewSchema,ContentOverviewViewsDTOSchema,UpdateContentOverviewViewRequestSchema,ContentOverviewViewsResponseSchema,init_content_overview_view_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content-overview-view.dto.js"(){"use strict";init_response();ContentOverviewPageSchema=z78.enum(["collections","singles","forms"]),ContentOverviewViewSchema=z78.enum(["cards","list"]),ContentOverviewViewsDTOSchema=z78.object({collections:ContentOverviewViewSchema,singles:ContentOverviewViewSchema,forms:ContentOverviewViewSchema}),UpdateContentOverviewViewRequestSchema=z78.object({view:ContentOverviewViewSchema}),ContentOverviewViewsResponseSchema=createResponseSchema(ContentOverviewViewsDTOSchema)}});import{z as z79}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z79.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z80}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z80.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z80.object({event:ClientTrackedEventSchema,properties:z80.record(z80.string(),z80.unknown()).default({})})}});import{z as z81}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z81.object({id:z81.string(),name:z81.string()}),AssetDTOSchema=z81.object({id:z81.string(),name:z81.string(),type:AssetTypeSchema,originalFileName:z81.string().nullable(),parentId:z81.string().nullable(),mimeType:z81.string().nullable(),fileSize:z81.number().nullable(),url:z81.string().nullable(),storageKey:z81.string().nullable(),createdAt:z81.string(),updatedAt:z81.string(),altText:z81.string().nullable().optional(),caption:z81.string().nullable().optional(),aiCaption:z81.string().nullable().optional(),aiAltText:z81.string().nullable().optional(),aiTags:z81.array(z81.string()).nullable().optional(),aiPrimaryColor:z81.string().nullable().optional(),aiProcessingStatus:z81.string().nullable().optional(),width:z81.number().nullable().optional(),height:z81.number().nullable().optional(),path:z81.array(AssetPathItemSchema).optional(),hasChildren:z81.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z81.lazy(()=>z81.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z81.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z81.object({error:z81.string(),code:z81.literal("media_storage_limit_exceeded"),usedBytes:z81.number().int().nonnegative(),limitBytes:z81.number().int().positive(),incomingBytes:z81.number().int().nonnegative()}),AssetReferenceScopeSchema=z81.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z81.object({assetIds:z81.array(z81.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z81.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z81.object({totalFiles:z81.number().int().nonnegative(),checkedFiles:z81.number().int().nonnegative(),limit:z81.number().int().positive()}),AssetReferenceFindingDTOSchema=z81.object({assetId:z81.uuid(),entryId:z81.string(),documentId:z81.string(),contentType:z81.string(),locale:z81.string().nullable(),slug:z81.string(),fieldPath:z81.string()}),AssetReferenceScopeResultDTOSchema=z81.object({scope:AssetReferenceScopeSchema,label:z81.string(),state:z81.enum(["available","not-published","failed"]),coverage:z81.enum(["complete","partial","failed"]),referenceCount:z81.number().int().nonnegative().optional(),codeReferenceCount:z81.number().int().nonnegative().optional(),referencedAssetIds:z81.array(z81.uuid()).optional(),references:z81.array(AssetReferenceFindingDTOSchema),reason:z81.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z81.discriminatedUnion("type",[z81.object({type:z81.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z81.object({type:z81.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z81.object({type:z81.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z81.object({replacementAssetId:z81.uuid()}),AssetReferenceReplacementResultSchema=z81.object({referencesReplaced:z81.number().int().nonnegative(),entriesChanged:z81.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z81.object({referencesReplaced:z81.number().int().nonnegative(),filesChanged:z81.number().int().nonnegative(),commitSha:z81.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z81.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z81.object({error:z81.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z81.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z81.object({intent:AssetRemovalIntentSchema,assetIds:z81.array(z81.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z81.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z81.object({id:z81.uuid(),intent:AssetRemovalIntentSchema,assetIds:z81.array(z81.uuid()),replacementAssetId:z81.uuid().nullable(),expiresAt:z81.iso.datetime(),undoable:z81.boolean(),requestedByMe:z81.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z81.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z81.object({error:z81.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z82}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z82.object({key:z82.string(),value:z82.string().optional(),defaultValue:z82.string(),locale:z82.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z83}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=z83.object({id:z83.string(),name:z83.string(),type:z83.enum(["file","folder"]),path:z83.string(),children:z83.lazy(()=>z83.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z83.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z83.object({path:z83.string(),exists:z83.boolean(),type:z83.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z84}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z84.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z84.object({minLength:z84.number().optional(),maxLength:z84.number().optional(),min:z84.number().optional(),max:z84.number().optional(),pattern:z84.string().optional(),maxFileSize:z84.number().optional(),accept:z84.array(z84.string()).optional()}),FormFieldSchema=z84.object({type:FormFieldTypeSchema,label:z84.string(),placeholder:z84.string().optional(),required:z84.boolean().optional(),defaultValue:z84.string().optional(),options:z84.array(z84.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z84.record(z84.string(),FormFieldSchema),FormContentSchema=z84.object({name:z84.string().min(1).max(255),label:z84.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema=FormContentSchema.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z85}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z85.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z85.object({id:z85.string().uuid(),label:z85.string(),status:ChatTaskStatusSchema,startedAt:z85.string(),endedAt:z85.string().nullable(),result:z85.string().nullable()}),ChatTaskListDTOSchema=z85.object({tasks:z85.array(ChatTaskDTOSchema)})}});import{z as z86}from"zod";var AgentPatchSchema,AgentToolInputSchema,AgentToolRoutineSchema,AgentToolErrorCodeSchema,AgentToolResultSchema,AgentInstructionAuthorSchema,AgentInstructionRevisionDTOSchema,AgentInstructionRevisionListDTOSchema,AgentInstructionRevisionListResponseSchema,AgentInstructionRestoreSchema,init_chat_agent_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-agent.dto.js"(){"use strict";init_response();init_chat_routine_dto();init_chat_dto();AgentPatchSchema=z86.object({name:z86.string().trim().min(1).max(120).optional(),description:z86.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z86.string().min(1)).optional(),live:z86.literal(!0).optional()}),AgentToolInputSchema=AgentPatchSchema.extend({create:z86.literal(!0).optional()}),AgentToolRoutineSchema=z86.object({id:z86.string(),name:z86.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z86.string().nullable()}),AgentToolErrorCodeSchema=z86.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z86.discriminatedUnion("ok",[z86.object({ok:z86.literal(!0),agent:z86.object({id:z86.string(),name:z86.string(),live:z86.boolean(),routines:z86.array(AgentToolRoutineSchema)}),revisionId:z86.string().optional()}),z86.object({ok:z86.literal(!1),error:z86.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z86.object({kind:z86.enum(["person","agent"]),id:z86.string().nullable(),name:z86.string().nullable()}),AgentInstructionRevisionDTOSchema=z86.object({id:z86.string().uuid(),previous:z86.string().nullable(),instructions:z86.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z86.string()}),AgentInstructionRevisionListDTOSchema=z86.object({revisions:z86.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z86.object({revisionId:z86.string().uuid()})}});import{z as z87}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=z87.object({url:z87.string().url(),key:z87.string(),size:z87.number(),contentType:z87.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z88}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=z88.object({canAccess:z88.boolean(),permissions:z88.record(z88.string(),z88.boolean()),role:z88.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z89}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:z89.string().trim().default(""),sort:z89.enum(["recent","name","relevance"]).default("recent"),category:z89.string().optional()})}});import{z as z90}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=z90.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z90.enum(["fimo","external"]),PaymentStatusSchema=z90.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z90.object({id:z90.string().uuid(),domain:z90.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z90.boolean(),price:z90.number().int().nullable(),renewalPrice:z90.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z90.string().nullable(),failureReason:z90.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z90.object({domain:z90.string(),available:z90.boolean(),premium:z90.boolean(),price:z90.number().nullable(),renewalPrice:z90.number().nullable(),purchaseType:z90.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z90.object({domain:z90.string(),price:z90.number().nullable(),renewalPrice:z90.number().nullable(),premium:z90.boolean(),allowedYears:z90.array(z90.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z90.object({firstName:z90.string().max(100),lastName:z90.string().max(100),companyName:z90.string().max(100).optional(),address1:z90.string().max(255),address2:z90.string().max(255).optional(),city:z90.string().max(100),state:z90.string().max(100),zip:z90.string().max(20),country:z90.string().max(2),phone:z90.string().max(30),email:z90.union([z90.string().email().max(255),z90.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z90.object({firstName:z90.string().min(1).max(100),lastName:z90.string().min(1).max(100),companyName:z90.string().max(100).optional(),address1:z90.string().min(1).max(255),address2:z90.string().max(255).optional(),city:z90.string().min(1).max(100),state:z90.string().min(1).max(100),zip:z90.string().min(1).max(20),country:z90.string().min(1).max(2),phone:z90.string().min(1).max(30),email:z90.string().email().max(255)}),SearchDomainsRequestSchema=z90.object({keyword:z90.string().min(1).max(100),tldFilter:z90.array(z90.string()).optional()}),CheckAvailabilityRequestSchema=z90.object({domains:z90.array(z90.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=z90.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z90.object({domain:DomainNameSchema,years:z90.number().int().min(1).max(10).optional().default(3),autoRenew:z90.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z90.object({autoRenew:z90.boolean().optional()}),RenewDomainRequestSchema=z90.object({years:z90.number().int().min(1).max(10).optional().default(1),autoRenew:z90.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z90.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z90.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z90.object({verified:z90.boolean(),email:z90.string().nullable(),verifyBy:z90.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z91}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectStatusSchema,DomainRedirectSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,DEFAULT_REDIRECT_STATUS,SetProjectDomainRedirectRequestSchema,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=z91.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=z91.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=z91.object({txtName:z91.string().nullable().optional(),txtValue:z91.string().nullable().optional(),httpUrl:z91.string().nullable().optional(),httpBody:z91.string().nullable().optional(),cname:z91.string().nullable().optional(),cnameTarget:z91.string().nullable().optional()}),SSLValidationErrorSchema=z91.object({message:z91.string()}),OwnershipVerificationSchema=z91.object({type:z91.string(),name:z91.string(),value:z91.string()}),ProjectDomainSSLDTOSchema=z91.object({status:z91.string(),method:z91.string().nullable(),type:z91.string().nullable(),validationRecords:z91.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z91.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z91.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z91.enum(["subdomain","apex"]),RedirectStatusSchema=z91.union([z91.literal(301),z91.literal(302),z91.literal(307),z91.literal(308)]),DomainRedirectSchema=z91.object({targetDomainId:z91.string(),targetHostname:z91.string(),status:RedirectStatusSchema}).nullable(),ProjectDomainDTOSchema=z91.object({id:z91.string(),hostname:z91.string(),status:z91.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z91.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z91.string(),scdCnameTarget:z91.string().optional(),apexTargets:z91.array(z91.string()),dnsAutoConfigured:z91.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirect:DomainRedirectSchema,migrationStatus:z91.string().nullable().optional(),primary:z91.boolean()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z91.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z91.object({hostname:z91.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:z91.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z91.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z91.object({available:z91.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z91.object({success:z91.boolean(),hostname:z91.string(),removed:z91.array(z91.object({id:z91.string(),hostname:z91.string()}))})),DEFAULT_REDIRECT_STATUS=307,SetProjectDomainRedirectRequestSchema=z91.object({targetDomainId:z91.uuid().toLowerCase(),status:RedirectStatusSchema.default(DEFAULT_REDIRECT_STATUS)})}});import{z as z92}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=z92.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z92.object({available:z92.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z92.object({slug:z92.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z92.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z92.object({subdomain:z92.string(),subdomainUpdatedAt:z92.coerce.date()})),SubdomainSuggestionsQuerySchema=z92.object({base:z92.string().max(100).optional(),max:z92.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z92.object({suggestions:z92.array(z92.string())}))}});import{z as z93}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","project_code_sync_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z93.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z93.object({code:ProjectTransferBlockerCodeSchema,message:z93.string(),count:z93.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z93.object({targetOrganizationId:z93.string().min(1)}),ProjectTransferResultDTO=createDTO(z93.object({projectId:z93.string(),sourceOrganizationId:z93.string(),targetOrganizationId:z93.string(),movedThreads:z93.number().int().nonnegative(),revokedInvites:z93.number().int().nonnegative(),revokedGrants:z93.number().int().nonnegative(),preservedGrants:z93.number().int().nonnegative(),warnings:z93.array(z93.string())}))}});import{z as z94}from"zod";var PROJECT_TOKEN_PREFIX,MB2,UNCLAIMED_PLAN,UnclaimedLockedFeatureSchema,UNCLAIMED_CLAIM_STATES,UnclaimedClaimStateSchema,UNCLAIMED_PROJECT_ERROR_CODES,UnclaimedProjectErrorCodeSchema,ProvisionUnclaimedProjectRequestSchema,UnclaimedProjectLimitsSchema,UnclaimedProjectClaimSchema,ProvisionUnclaimedProjectResponseDTO,UnclaimedClaimStatusDTO,UnclaimedClaimSecretSchema,UnclaimedClaimStatusRequestSchema,UnclaimedClaimStatesRequestSchema,UnclaimedClaimStatesResponseDTO,ClaimUnclaimedProjectRequestSchema,ClaimUnclaimedProjectResultDTO,ProjectTokenSelfDTO,init_unclaimed_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unclaimed-project.dto.js"(){"use strict";init_create_dto();init_project_dto();PROJECT_TOKEN_PREFIX="fimo_pt_",MB2=1e6,UNCLAIMED_PLAN={ttlHours:72,tokenTtlAfterClaimHours:24,media:{totalBytes:50*MB2,fileBytes:5*MB2,maxFiles:100,mimeTypes:["image/jpeg","image/png","image/webp","image/avif","image/gif"]},database:{storageBytes:100*MB2,computeSeconds:600*60,maxComputeUnits:.5},locked:{publish:"Publishing",subdomain:"A fimo.site address",custom_domains:"Custom domains",branches:"Extra Branches",environments:"Extra environments",asset_generation:"Generating images and videos",integrations:"Connecting integrations",invites:"Inviting people",schedules:"Schedules",agents:"Fimo agents",ai_credits:"AI features"}},UnclaimedLockedFeatureSchema=z94.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z94.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","unclaimed_deploy_limit","claim_not_claimable","claim_project_limit_reached","claim_target_organization_not_found","claim_target_organization_forbidden","claim_target_subscription_inactive","claim_blocked","project_token_required","unclaimed_media_limit"],UnclaimedProjectErrorCodeSchema=z94.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z94.object({displayName:z94.string().trim().min(1).max(80),machineId:z94.string().trim().min(1).max(128).optional(),cliVersion:z94.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z94.object({ttlHours:z94.number().int().positive(),lockedFeatures:z94.array(UnclaimedLockedFeatureSchema),media:z94.object({totalBytes:z94.number().int().nonnegative(),fileBytes:z94.number().int().positive(),maxFiles:z94.number().int().nonnegative(),mimeTypes:z94.array(z94.string())}),database:z94.object({storageBytes:z94.number().int().positive(),computeSeconds:z94.number().int().positive(),maxComputeUnits:z94.number().positive()})}),UnclaimedProjectClaimSchema=z94.object({url:z94.string().url(),expiresAt:z94.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z94.object({project:ProjectDTOSchema,token:z94.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z94.object({state:UnclaimedClaimStateSchema,displayName:z94.string().nullable(),expiresAt:z94.coerce.date().nullable(),projectId:z94.string().nullable()})),UnclaimedClaimSecretSchema=z94.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z94.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z94.object({secrets:z94.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z94.object({claims:z94.array(z94.object({state:UnclaimedClaimStateSchema,expiresAt:z94.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z94.object({secret:UnclaimedClaimSecretSchema,organizationId:z94.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z94.object({projectId:z94.string(),organizationId:z94.string()})),ProjectTokenSelfDTO=createDTO(z94.object({kind:z94.literal("project_token"),projectId:z94.string(),projectName:z94.string(),displayName:z94.string().nullable(),organizationId:z94.string().nullable(),organizationName:z94.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z94.coerce.date().nullable(),tokenExpiresAt:z94.coerce.date().nullable()}))}});import{z as z95}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=z95.object({translated:z95.number().int().nonnegative(),total:z95.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z95.object({locale:z95.string(),isDefault:z95.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z95.object({defaultLocale:z95.string(),locales:z95.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z95.object({locale:z95.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z95.object({locale:z95.string().min(1).max(40)}),ProjectLocaleMutationSchema=z95.object({locale:z95.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z95.object({locale:z95.string(),entriesDeleted:z95.number().int().nonnegative(),labelsDeleted:z95.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z96}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=z96.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z96.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=z96.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z96.number(),credits:z96.number().optional(),billingMode:z96.enum(["fimo-credits","provider-account"]).optional(),confidence:z96.enum(["exact","estimated","metered"]),basis:z96.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z97}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=z97.object({options:z97.record(z97.string(),z97.unknown()),name:z97.string().optional(),parentId:z97.string().nullable().optional(),altText:z97.string().optional(),caption:z97.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z97.string().min(1).optional(),model:z97.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=z97.object({jobId:z97.string(),status:z97.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z97.string().nullable().optional(),credits:z97.number().optional(),costUsd:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z97.object({error:z97.string(),code:z97.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:z97.array(GenerationTaskIdSchema).optional(),availableModels:z97.array(z97.string()).optional(),issues:z97.array(z97.unknown()).optional()})}});import{z as z98}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=z98.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z98.object({name:z98.string(),key:z98.string(),description:z98.string(),type:FlagTypeSchema,required:z98.boolean(),defaultValue:z98.unknown().optional(),enumValues:z98.array(z98.string()).optional(),isArray:z98.boolean()}),AssetModelPriceSchema=z98.object({unitPrice:z98.number(),unit:z98.string(),confidence:z98.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z98.object({id:z98.string(),shortName:z98.string(),provider:z98.string(),source:z98.string(),modality:z98.enum(["image","video","audio"]),tags:z98.array(z98.string()),displayName:z98.string(),description:z98.string(),flags:z98.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z98.object({model:z98.string(),costUsd:z98.number(),credits:z98.number(),billingMode:z98.enum(["fimo-credits","provider-account"]),confidence:z98.enum(["exact","estimated","metered"]),basis:z98.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z99}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=z99.object({tourId:z99.string(),version:z99.string(),status:z99.string(),completedAt:z99.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z99.array(UserTourDTOSchema))}});import{z as z100}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=z100.object({backendProfile:OpsBackendProfileSchema,provider:z100.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z100.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z100.object({backendProfile:OpsBackendProfileSchema,provider:z100.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z100.literal(!1),reason:z100.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z101}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=z101.object({packageManager:z101.string().trim().min(1).max(200).nullable(),trackedLockfiles:z101.array(z101.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z101.string().trim().min(1)}),OpsProjectPackageManagerSchema=z101.object({target:z101.object({backendProfile:OpsBackendProfileSchema,projectId:z101.uuid(),projectEnv:z101.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z102}from"zod";function uniqueRoutineNames(spec){let names=(spec.routines??[]).map(routine=>routine.name);return new Set(names).size===names.length}var OpsAgentChatRoutineSpecSchema,OpsAgentChatAgentSpecSchema,OpsAgentChatSpecObjectSchema,UNIQUE_ROUTINE_NAMES,OpsAgentChatSpecSchema,OpsAgentChatCreateInputSchema,OpsAgentChatOutcomeSchema,OpsAgentChatRoutineResultSchema,OpsAgentChatCreateResultSchema,init_ops_agent_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-chat.dto.js"(){"use strict";init_ops();init_chat_routine_dto();OpsAgentChatRoutineSpecSchema=ChatRoutineCreateSchema.extend({schedule:ChatRoutineScheduleSchema.nullable(),paused:z102.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z102.union([z102.object({name:z102.string().trim().min(1).max(120),description:z102.string().trim().min(1).max(2e3)}).strict(),z102.object({template:z102.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z102.object({agent:OpsAgentChatAgentSpecSchema,routines:z102.array(OpsAgentChatRoutineSpecSchema).max(50).optional()}).strict();__name(uniqueRoutineNames,"uniqueRoutineNames");UNIQUE_ROUTINE_NAMES={path:["routines"],message:"Routine names must be unique within one agent"},OpsAgentChatSpecSchema=OpsAgentChatSpecObjectSchema.refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatCreateInputSchema=OpsAgentChatSpecObjectSchema.extend({reason:z102.string().trim().min(1).max(1e3),dryRun:z102.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z102.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z102.object({id:z102.string().uuid().nullable(),name:z102.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z102.string().nullable(),paused:z102.boolean(),outcome:z102.enum(["created","would_create"]),source:z102.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z102.object({target:z102.object({backendProfile:OpsBackendProfileSchema,projectId:z102.string().uuid()}),dryRun:z102.boolean(),applied:z102.boolean(),createdBy:z102.object({userId:z102.string()}),agent:z102.object({id:z102.string().uuid().nullable(),title:z102.string(),template:z102.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z102.array(OpsAgentChatRoutineResultSchema),skipped:z102.array(z102.object({name:z102.string(),reason:z102.literal("routine_exists")})),refused:z102.array(z102.object({name:z102.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z103}from"zod";var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z103.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z103.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z103.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z103.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z103.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z103.object({reason:WebhookEntryChangeReasonSchema,operationId:z103.string().optional(),batch:z103.object({index:z103.number().int().positive(),total:z103.number().int().positive()}).optional(),changes:z103.array(z103.object({action:WebhookEntryChangeActionSchema,contentType:z103.string(),id:z103.string(),documentId:z103.string(),locale:z103.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z103.object({form:z103.object({id:z103.string(),label:z103.string()}),submission:z103.object({id:z103.string(),data:z103.record(z103.string(),z103.unknown()),submittedAt:z103.string()})}),PublishStartedWebhookEventDataSchema=z103.object({publication:z103.object({status:z103.literal("publishing"),startedAt:z103.string()})}),PublishSucceededWebhookEventDataSchema=z103.object({publication:z103.object({status:z103.literal("published"),url:z103.string(),publishedAt:z103.string(),firstPublish:z103.boolean()})}),PublishFailedWebhookEventDataSchema=z103.object({publication:z103.object({status:z103.literal("failed"),reason:z103.string()})}),PublishUnpublishedWebhookEventDataSchema=z103.object({publication:z103.object({previousUrl:z103.string(),unpublishedAt:z103.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z103.object({report:z103.object({weekStart:z103.string(),weekEnd:z103.string(),pageviews:z103.number(),visitors:z103.number(),previousPageviews:z103.number(),previousVisitors:z103.number()})}),MediaAssetWebhookEventDataSchema=z103.object({id:z103.string().nullable(),name:z103.string().nullable(),type:z103.string(),mimeType:z103.string().nullable(),fileSize:z103.number().nullable()}),MediaUploadedWebhookEventDataSchema=z103.object({asset:MediaAssetWebhookEventDataSchema,operation:z103.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z103.object({asset:MediaAssetWebhookEventDataSchema,operation:z103.literal("updated")}),MediaDeletedWebhookEventDataSchema=z103.object({asset:MediaAssetWebhookEventDataSchema,operation:z103.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z103.object({domain:z103.object({id:z103.string(),hostname:z103.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z103.object({domain:z103.object({id:z103.string(),hostname:z103.string()})}),LabelChangedWebhookEventDataSchema=z103.object({changes:z103.array(z103.object({action:z103.enum(["created","updated","deleted"]),key:z103.string(),locale:z103.string(),value:z103.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z103.object({locale:z103.object({code:z103.string(),isDefault:z103.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z103.object({locale:z103.object({code:z103.string(),previousCode:z103.string()})}),LocaleDeletedWebhookEventDataSchema=z103.object({locale:z103.object({code:z103.string(),entriesDeleted:z103.number().int().nonnegative(),labelsDeleted:z103.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z103.object({environment:z103.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z103.object({environment:z103.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z103.object({merge:z103.object({id:z103.string(),from:BranchSchema,to:BranchSchema,applied:z103.array(z103.object({surface:SurfaceNameSchema,count:z103.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z103.object({branch:z103.object({name:BranchSchema}),version:z103.object({versionId:z103.uuid(),name:z103.string()})}),WebhookEventFamilySchema=z103.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z103.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z103.discriminatedUnion("source",[z103.object({source:z103.literal("literal"),value:z103.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z103.object({source:z103.literal("secret"),key:z103.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z103.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z103.object({name:z103.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z103.object({name:z103.string(),source:z103.enum(["literal","secret"]),secretKey:z103.string().nullable(),secretPrefix:z103.string().nullable(),configured:z103.literal(!0)}),WebhookFilterSchema=z103.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z103.string().min(1).max(255).optional(),mediaType:z103.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z103.string().min(1).max(255).optional(),locale:z103.string().min(1).max(120).optional()}),JsonValueSchema=z103.lazy(()=>z103.union([z103.string(),z103.number(),z103.boolean(),z103.null(),z103.array(JsonValueSchema),z103.record(z103.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z103.object({name:z103.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z103.url(),enabled:z103.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z103.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z103.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z103.object({name:z103.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z103.url().optional(),enabled:z103.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z103.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z103.boolean().optional()}),TestProjectWebhookRequestSchema=z103.object({eventType:WebhookEventTypeSchema.optional(),data:z103.record(z103.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z103.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z103.uuid(),name:z103.string(),eventType:WebhookEventTypeSchema,enabled:z103.boolean(),destination:z103.object({host:z103.string(),maskedUrl:z103.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z103.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z103.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z103.coerce.date().nullable(),deliveryStats24h:z103.object({succeeded:z103.number().int().nonnegative(),failed:z103.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z103.uuid(),projectId:z103.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z103.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z103.number().int().positive(),test:z103.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z103.number().int().nonnegative(),responseStatus:z103.number().int().nullable(),lastErrorCode:z103.string().nullable(),lastErrorMessage:z103.string().nullable(),payloadAvailable:z103.boolean(),destination:z103.object({host:z103.string(),maskedUrl:z103.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z103.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z103.string().nullable(),qstashMessageId:z103.string().nullable(),deliveredAt:z103.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z103.object({items:z103.array(WebhookDeliveryDTOSchema),pagination:z103.object({page:z103.number().int().positive(),limit:z103.number().int().positive(),total:z103.number().int().nonnegative(),totalPages:z103.number().int().positive(),hasMore:z103.boolean()}),stats:z103.object({total:z103.number().int().nonnegative(),succeeded:z103.number().int().nonnegative(),failed:z103.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z103.object({id:z103.uuid(),deliveryId:z103.uuid(),attempt:z103.number().int().positive(),status:z103.enum(["delivering","succeeded","failed"]),responseStatus:z103.number().int().nullable(),durationMs:z103.number().int().nonnegative(),responseExcerpt:z103.string().nullable(),errorCode:z103.string().nullable(),errorMessage:z103.string().nullable(),createdAt:z103.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z103.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z103.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z104}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=z104.object({key:z104.literal("fimo-2"),enabled:z104.boolean(),dismissed:z104.boolean().default(!1),interacted:z104.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z105}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteRecommendationsSchema,SiteMarketSchema,SitePageViewSchema,SiteSectionStatusSchema,SiteComparisonSchema,SiteReportSchema,SiteTypeSchema,SiteTermsCategorySchema,SiteUnderstandingSchema,SiteSuggestionSchema,SiteInterviewSuggestionsSchema,SiteInterviewAnswerSchema,SiteInterviewSchema,AnswerSiteInterviewRequestSchema,SiteFixesReportSchema,SiteOnboardingResultSchema,StartSiteOnboardingRequestSchema,StartSiteOnboardingResponseSchema,SiteOnboardingRefusedResponseSchema,platforms,frameworks,SiteTechnologySchema,SiteSourceTechnologySchema,SiteOnboardingStateSchema,SiteOnboardingStateDTO,SiteOnboardingStateResponseSchema,RetrySiteOnboardingRequestSchema,SiteOnboardingOutcomeSchema,AdminSiteOnboardingsQuerySchema,AdminSiteOnboardingDTOSchema,AdminSiteOnboardingDTO,AdminSiteOnboardingsResponseSchema,AdminSiteOnboardingStatsSchema,AdminSiteOnboardingStatsResponseSchema,AdminSiteOnboardingDetailSchema,AdminSiteOnboardingDetailDTO,AdminSiteOnboardingDetailResponseSchema,init_site_onboarding_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/site-onboarding.dto.js"(){"use strict";init_create_dto();init_response();SiteOnboardingStageSchema=z105.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z105.enum(["running","done","failed"]),SiteCloneStatusSchema=z105.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z105.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z105.object({code:SiteRefusalCodeSchema,suggestedUrl:z105.string().nullable()}),SiteCheckGroupSchema=z105.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z105.enum(["seo","geo"]),SITE_CHECKS=[{id:"robots_txt",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap_lastmod",group:"discovery",scores:["seo","geo"],weight:1},{id:"broken_links",group:"discovery",scores:["seo"],weight:2},{id:"internal_nofollow",group:"discovery",scores:["seo"],weight:1},{id:"blocked_from_crawling",group:"discovery",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"status_4xx",group:"indexing",scores:["seo","geo"],weight:2,cap:{seo:10,geo:10}},{id:"status_5xx",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:10,geo:10}},{id:"https_to_http",group:"indexing",scores:["seo"],weight:1,cap:{seo:50}},{id:"canonical",group:"indexing",scores:["seo"],weight:1},{id:"noindex",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"hreflang",group:"indexing",scores:["seo"],weight:1},{id:"missing_page",group:"indexing",scores:["seo","geo"],weight:1,cap:{seo:80,geo:80}},{id:"ai_bots_robots",group:"ai_crawlers",scores:["geo"],weight:3,cap:{geo:30}},{id:"ai_bot_access",group:"ai_crawlers",scores:["geo"],weight:2,cap:{geo:40}},{id:"llms_txt",group:"ai_crawlers",scores:["geo"],weight:1},{id:"server_rendering",group:"rendering",scores:["geo"],weight:3},{id:"semantic_html",group:"rendering",scores:["seo","geo"],weight:2},{id:"markdown_pages",group:"rendering",scores:["geo"],weight:1},{id:"markdown_alternate",group:"rendering",scores:["geo"],weight:.5},{id:"markdown_index",group:"rendering",scores:["geo"],weight:.5},{id:"meta_title",group:"metadata",scores:["seo"],weight:2},{id:"meta_description",group:"metadata",scores:["seo"],weight:2},{id:"structured_data",group:"metadata",scores:["seo","geo"],weight:2},{id:"organization_schema",group:"metadata",scores:["geo"],weight:2},{id:"entity_links",group:"metadata",scores:["geo"],weight:1},{id:"metadata_completeness",group:"metadata",scores:["seo","geo"],weight:2},{id:"trust_pages",group:"metadata",scores:["geo"],weight:2},{id:"word_count",group:"content",scores:["seo","geo"],weight:2},{id:"text_ratio",group:"content",scores:["seo"],weight:1},{id:"h1",group:"content",scores:["seo"],weight:2},{id:"image_alt",group:"content",scores:["seo","geo"],weight:1},{id:"broken_images",group:"content",scores:["seo"],weight:1},{id:"empty_link_text",group:"content",scores:["seo","geo"],weight:1},{id:"page_load",group:"speed",scores:["seo"],weight:3},{id:"unminified_assets",group:"speed",scores:["seo"],weight:1}],SiteCheckIdSchema=z105.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z105.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z105.record(z105.string(),z105.union([z105.string(),z105.number(),z105.boolean(),z105.array(z105.string())])),SiteCheckResultSchema=z105.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z105.object({id:SiteCheckGroupSchema,score:z105.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z105.object({answers:z105.number().int().min(0),domains:z105.record(z105.string(),z105.number().int().min(0))}),SiteMarketSchema=z105.object({domain:z105.string(),competitors:z105.array(z105.string()),rankings:z105.array(z105.object({domain:z105.string(),averagePosition:z105.number().min(1).nullable()})),keywords:z105.array(z105.object({keyword:z105.string(),positions:z105.record(z105.string(),z105.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z105.record(z105.string(),z105.string()).optional(),countryCode:z105.string().optional(),languageCode:z105.string().optional(),fetchedAt:z105.coerce.date()}),SitePageViewSchema=z105.object({url:z105.string(),title:z105.string().nullable(),description:z105.string().nullable(),h1:z105.string().nullable(),structuredData:z105.array(z105.string()),wordCount:z105.number().int().min(0),capturedAt:z105.coerce.date()}),SiteSectionStatusSchema=z105.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z105.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z105.coerce.date().optional(),afterQueuedAt:z105.coerce.date().optional()}),SiteReportSchema=z105.object({siteUrl:z105.string(),scannedAt:z105.coerce.date(),seoScore:z105.number().int().min(0).max(100).nullable(),geoScore:z105.number().int().min(0).max(100).nullable(),groups:z105.array(SiteReportGroupSchema),checks:z105.array(SiteCheckResultSchema),blockers:z105.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z105.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z105.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z105.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z105.object({name:z105.string(),summary:z105.string(),audience:z105.string(),positioning:z105.string(),homepage:z105.string()}),SiteSuggestionSchema=z105.object({label:z105.string(),url:z105.string().nullable()}),SiteInterviewSuggestionsSchema=z105.record(z105.string(),z105.record(z105.string(),z105.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z105.record(z105.string().max(50),z105.union([z105.string().trim().max(2e3),z105.array(z105.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z105.object({status:z105.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z105.record(z105.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z105.object({questionId:z105.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z105.object({fixes:z105.array(z105.object({checkId:SiteCheckIdSchema,status:z105.enum(["fixed","not_fixed","not_applicable"]),note:z105.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z105.object({fixes:SiteFixesReportSchema.nullable(),summary:z105.string().nullable()}),StartSiteOnboardingRequestSchema=z105.object({organizationId:z105.string().min(1),url:z105.string().trim().min(1).max(2048),locale:z105.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z105.object({projectId:z105.string()})),SiteOnboardingRefusedResponseSchema=z105.object({error:z105.literal("site_refused"),refusal:SiteRefusalSchema}),platforms=["wordpress","webflow","framer","wix","shopify","squarespace","ghost","drupal","joomla","lovable","bolt","replit","base44","site123","manus","unknown"],frameworks=["nextjs","nuxt","astro","gatsby","angular","react","vue","svelte","unknown"],SiteTechnologySchema=z105.object({detectionVersion:z105.union([z105.literal(1),z105.literal(2)]),sourcePlatforms:z105.array(z105.enum(platforms)).min(1).max(platforms.length),frontendFrameworks:z105.array(z105.enum(frameworks)).min(1).max(frameworks.length)}),SiteSourceTechnologySchema=SiteTechnologySchema.extend({detectedAt:z105.string().datetime({offset:!0})}),SiteOnboardingStateSchema=z105.object({projectId:z105.string(),sourceTechnology:SiteSourceTechnologySchema.nullable().optional(),siteUrl:z105.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z105.boolean(),budgetExhausted:z105.boolean(),sponsored:z105.boolean(),outOfCredits:z105.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z105.string().nullable(),welcomeThreadId:z105.string().nullable(),competitors:z105.array(z105.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z105.coerce.date(),openedAt:z105.coerce.date().nullable(),bannerDismissed:z105.boolean(),migrateDialogSeen:z105.boolean(),completed:z105.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z105.object({task:z105.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z105.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z105.object({search:z105.string().trim().max(200).optional(),organizationId:z105.string().trim().min(1).max(200).optional(),startDate:z105.coerce.date().optional(),endDate:z105.coerce.date().optional(),outcomes:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(SiteTypeSchema).optional()),page:z105.coerce.number().int().min(1).default(1),pageSize:z105.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z105.object({projectId:z105.string(),projectName:z105.string(),organizationId:z105.string(),organizationName:z105.string().nullable(),ownerEmail:z105.string().nullable(),ownerName:z105.string().nullable(),siteUrl:z105.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z105.boolean(),cloneRetries:z105.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z105.number(),interviewQuestions:z105.number().nullable(),seoScore:z105.number().nullable(),geoScore:z105.number().nullable(),spentUsd:z105.number(),budgetCapUsd:z105.number(),capReached:z105.boolean(),cloneSeconds:z105.number().nullable(),createdAt:z105.coerce.date(),openedAt:z105.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z105.object({onboardings:z105.array(AdminSiteOnboardingDTOSchema),page:z105.number(),limit:z105.number(),total:z105.number(),totalPages:z105.number()})),AdminSiteOnboardingStatsSchema=z105.object({total:z105.number(),outcomes:z105.record(SiteOnboardingOutcomeSchema,z105.number()),funnel:z105.object({started:z105.number(),finished:z105.number(),opened:z105.number()}),bySiteType:z105.array(z105.object({siteType:SiteTypeSchema,total:z105.number(),finished:z105.number(),opened:z105.number()})),granularity:z105.enum(["hour","day"]),series:z105.array(z105.object({at:z105.coerce.date(),outcomes:z105.record(SiteOnboardingOutcomeSchema,z105.number())})),spentUsd:z105.object({total:z105.number(),average:z105.number().nullable()}),sponsored:z105.number(),paidByOrganization:z105.object({usd:z105.number(),credits:z105.number()}),capReached:z105.number(),cloneSeconds:z105.object({median:z105.number().nullable(),average:z105.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z105.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z105.string(),cloneThreadId:z105.string().nullable(),paidByOrganizationUsd:z105.number()}),interview:SiteInterviewSchema.extend({invocationIds:z105.array(z105.string())}).nullable(),knowledgeWritten:z105.string().nullable(),knowledgeNow:z105.object({content:z105.string(),updatedAt:z105.coerce.date().nullable(),updatedBy:z105.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z106}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=z106.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z106.object({total:z106.number(),base:z106.number(),purchases:z106.number(),awards:z106.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z106.object({id:z106.string(),name:z106.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z106.object({type:z106.string(),brand:z106.string().nullable(),last4:z106.string().nullable(),expirationDate:z106.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z106.object({currency:z106.string(),nextPaymentAmount:z106.number().nullable(),nextPaymentAt:z106.string().nullable(),billingInterval:z106.string().nullable(),totalAmount:z106.number().nullable(),discountAmount:z106.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z106.object({id:z106.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z106.string().nullable(),currentPeriodEndsAt:z106.string().nullable(),renewsAt:z106.string().nullable(),cancelAt:z106.string().nullable(),renewAutomatically:z106.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z106.object({type:z106.enum(["low_balance","critical_balance","approaching_limit"]),message:z106.string(),estimatedPromptsRemaining:z106.number().nullable(),avgCostPerPrompt:z106.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z106.object({monthlyCredits:z106.number().nullable(),usedThisPeriod:z106.number(),remainingThisPeriod:z106.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z106.object({organizationId:z106.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z106.string().nullable(),tenureDays:z106.number().int().nonnegative(),capturedAt:z106.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z106.object({hasSubscription:z106.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z106.number().nullable(),alerts:z106.array(CreditAlertDTOSchema),portalUrl:z106.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z106.object({creditCount:z106.number().int().positive(),expiresAt:z106.string().datetime().nullable().optional(),message:z106.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z106.literal("free"),amountCents:z106.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z106.literal("purchase"),amountCents:z106.number().int().positive()}),CreditTopupRequestDTOSchema=z106.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z106.object({success:z106.boolean(),transactionId:z106.string().nullable(),newBalance:z106.number(),creditCount:z106.number(),type:z106.enum(["free","purchase"]),invoiceId:z106.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z107}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=z107.object({totalCredits:z107.number(),totalCostUsd:z107.number(),totalMessages:z107.number(),avgCostPerMessage:z107.number(),periodStart:z107.string().nullable(),periodEnd:z107.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z107.object({projectId:z107.string(),projectName:z107.string(),projectDisplayName:z107.string().nullable(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z107.object({userId:z107.string(),userName:z107.string().nullable(),userEmail:z107.string().email().nullable(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z107.object({date:z107.string(),credits:z107.number(),costUsd:z107.number(),messages:z107.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z107.object({userId:z107.string(),userName:z107.string().nullable(),userEmail:z107.string().email().nullable(),credits:z107.number(),costUsd:z107.number(),messages:z107.number(),percentage:z107.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z107.object({projectId:z107.string(),projectName:z107.string(),projectDisplayName:z107.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z107.array(UsageByUserForProjectDTOSchema),timeline:z107.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z107.object({summary:UsageSummaryDTOSchema,byProject:z107.array(UsageByProjectDTOSchema),byUser:z107.array(UsageByUserDTOSchema),timeline:z107.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z108}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=z108.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z108.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z108.object({startDate:z108.string().optional(),endDate:z108.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z108.coerce.number().int().positive().default(1),limit:z108.coerce.number().int().positive().max(100).default(20),sortBy:z108.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z108.string().optional(),activeOnly:z108.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z108.object({totalCredits:z108.number(),totalCostUsd:z108.number(),totalMessages:z108.number(),automatedMessages:z108.number(),avgCostPerMessage:z108.number(),avgCreditsPerMessage:z108.number(),periodStart:z108.string(),periodEnd:z108.string(),creditsChange:z108.number().nullable(),costChange:z108.number().nullable(),messagesChange:z108.number().nullable(),unattributedCredits:z108.number(),unattributedCostUsd:z108.number(),unattributedMessages:z108.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z108.object({date:z108.string(),credits:z108.number(),costUsd:z108.number(),messages:z108.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z108.object({organizationId:z108.string(),organizationName:z108.string(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number(),userCount:z108.number(),projectCount:z108.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z108.object({userId:z108.string(),userName:z108.string().nullable(),userEmail:z108.string().nullable(),userImage:z108.string().nullable(),organizationId:z108.string().nullable(),organizationName:z108.string().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number(),projectCount:z108.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z108.object({projectId:z108.string(),projectName:z108.string(),projectDisplayName:z108.string().nullable(),organizationId:z108.string(),organizationName:z108.string(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number(),userCount:z108.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z108.object({id:z108.string(),name:z108.string(),value:z108.number(),percentage:z108.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z108.object({day:z108.number(),hour:z108.number(),value:z108.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z108.object({summary:UsageOverviewSummaryDTOSchema,timeline:z108.array(UsageTimelinePointDTOSchema),topOrganizations:z108.array(OrganizationUsageRowDTOSchema),topUsers:z108.array(UserUsageRowDTOSchema),topProjects:z108.array(ProjectUsageRowDTOSchema),creditDistribution:z108.array(UsageDistributionItemDTOSchema),userDistribution:z108.array(UsageDistributionItemDTOSchema),heatmap:z108.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z108.object({page:z108.number(),limit:z108.number(),totalItems:z108.number(),totalPages:z108.number(),hasMore:z108.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z108.object({organizations:z108.array(OrganizationUsageRowDTOSchema),top:z108.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z108.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z108.object({users:z108.array(ExtendedUserUsageRowDTOSchema),top:z108.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z108.string(),ownerName:z108.string().nullable(),ownerEmail:z108.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z108.object({projects:z108.array(ExtendedProjectUsageRowDTOSchema),top:z108.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z108.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z108.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z108.object({credits:z108.number(),costUsd:z108.number(),messages:z108.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z108.object({id:z108.string(),name:z108.string(),createdAt:z108.string(),memberCount:z108.number(),projectCount:z108.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z108.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z108.object({id:z108.string(),name:z108.string().nullable(),email:z108.string(),image:z108.string().nullable(),createdAt:z108.string(),organizationCount:z108.number(),projectCount:z108.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z108.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z108.object({id:z108.string(),name:z108.string(),displayName:z108.string().nullable(),createdAt:z108.string(),organizationId:z108.string(),organizationName:z108.string(),ownerId:z108.string(),ownerName:z108.string().nullable(),ownerEmail:z108.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z108.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z109}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=z109.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z109.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z109.object({command:z109.string().min(1).max(1e4),cwd:z109.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z109.record(z109.string(),z109.string()).optional(),name:z109.string().optional(),waitForCompletion:z109.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z109.object({identifier:z109.string(),status:SandboxProcessStatusSchema,command:z109.string().optional(),startedAt:z109.string().optional(),exitCode:z109.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z109.object({processes:z109.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z109.object({processId:z109.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z109.object({success:z109.boolean(),message:z109.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z110}from"zod";var ADMIN_UNCLAIMED_STATES,AdminUnclaimedStateSchema,AdminUnclaimedProjectsQuerySchema,AdminUnclaimedProjectDTOSchema,AdminUnclaimedProjectDTO,AdminUnclaimedProjectsResponseSchema,ClaimOutcomesSchema,AdminUnclaimedProjectStatsSchema,AdminUnclaimedProjectStatsResponseSchema,init_unclaimed_projects_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/unclaimed-projects.dto.js"(){"use strict";init_create_dto();init_response();ADMIN_UNCLAIMED_STATES=["waiting","claiming","claimed","overdue","archived"],AdminUnclaimedStateSchema=z110.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z110.object({search:z110.string().trim().max(200).optional(),startDate:z110.coerce.date().optional(),endDate:z110.coerce.date().optional(),states:z110.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z110.array(AdminUnclaimedStateSchema).optional()),cliVersions:z110.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z110.array(z110.string().max(64)).optional()),page:z110.coerce.number().int().min(1).default(1),pageSize:z110.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z110.object({projectId:z110.string(),displayName:z110.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z110.string().nullable(),createdAt:z110.coerce.date(),expiresAt:z110.coerce.date(),claimedAt:z110.coerce.date().nullable(),claimedOrganizationId:z110.string().nullable(),claimedOrganizationName:z110.string().nullable(),claimedByEmail:z110.string().nullable(),projectExists:z110.boolean(),previewUrl:z110.string().nullable(),hostingCostUsd:z110.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z110.object({projects:z110.array(AdminUnclaimedProjectDTOSchema),page:z110.number(),limit:z110.number(),total:z110.number(),totalPages:z110.number()})),ClaimOutcomesSchema=z110.object({total:z110.number(),claimed:z110.number(),archived:z110.number(),claimRate:z110.number().nullable(),medianTimeToClaimSeconds:z110.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z110.record(AdminUnclaimedStateSchema,z110.number()),averageTimeToClaimSeconds:z110.number().nullable(),byCliVersion:z110.array(ClaimOutcomesSchema.extend({cliVersion:z110.string().nullable()})),granularity:z110.enum(["hour","day"]),series:z110.array(z110.object({at:z110.coerce.date(),states:z110.record(AdminUnclaimedStateSchema,z110.number()),alive:z110.number(),hostingCostUsd:z110.number()})),hostingCostUsd:z110.number(),costPerProjectUsd:z110.number().nullable(),leftovers:z110.object({overdue:z110.number(),claiming:z110.number(),archivedNotDeleted:z110.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z111}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z111.enum(["internal","user-visible"]),SessionSetRetentionSchema=z111.object({additionalDays:z111.number().int().min(1).max(30)}).strict()}});import{z as z112}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z112.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z112.object({content:ProjectKnowledgeContentSchema,updatedAt:z112.string().nullable(),updatedBy:z112.string().nullable()}),ProjectKnowledgeUpdateSchema=z112.object({content:ProjectKnowledgeContentSchema,expectedUpdatedAt:z112.iso.datetime().nullable().optional()}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z112.object({id:z112.uuid(),status:z112.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z112.string().nullable(),reason:z112.enum(["insufficient_credits"]).nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z112.object({idempotencyKey:z112.uuid()})}});import{z as z113}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_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_args();init_commands();init_references2();init_types();init_chat_block();init_chat_place();init_chat_reply();init_chat_tabs();init_chat_block_state();init_admin_chat_block();init_admin_assistant();init_chat_portrait();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_session_dto();init_agent_proposal_dto();init_draft_change_dto();init_agent_question_dto();init_agent_question_follow_up_dto();init_integration_catalog_dto();init_integration_dto();init_code_sync_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_marketing_consent_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_content_overview_view_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_chat_routine_dto();init_chat_task_dto();init_chat_agent_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_unclaimed_project_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_agent_proposals_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_chat_dto();init_webhook_dto();init_preview_feature_dto();init_site_onboarding_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto();init_unclaimed_projects_dto();init_work_sessions();init_project_knowledge_dto();init_organization_features_dto();init_admin_monitoring_dto();init_platform();init_sandbox();init_monitor();init_agent()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor3=0;do result+=string.substring(cursor3,index)+replace,cursor3=index+close.length,index=string.indexOf(close,cursor3);while(~index);return result+string.substring(cursor3)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types2=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout:stdout2,stderr}=opts,pendingWarnings=[];function emit(stream,envelope){let warnings=[...pendingWarnings,...envelope.warnings??[]].filter((warning,index,all)=>all.indexOf(warning)===index);pendingWarnings=[],stream.write(`${JSON.stringify(warnings.length>0?{...envelope,warnings}:envelope)}
7
7
  `)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data={headline:event.headline};return event.details&&(data.details=event.details),base.data=data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}case"table":{let rows=event.rows.map(row2=>{let out={};for(let col of event.columns)out[col.key]=row2[col.key];return event.isActive?.(row2)===!0&&(out.__active=!0),out}),data={...event.jsonData,columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"kv":{let data={fields:event.fields};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout2,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.details?{details:event.details}:{},...event.hint?{hint:event.hint}:{}}})},warn(event){pendingWarnings.push(event.message)},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{...event.jsonData,message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout2,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout:stdout2,stderr}=opts;function write(stream,line){stream.write(`${line}
8
8
  `)}__name(write,"write");function renderMessage2(event){if(write(stdout2,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w of event.warnings)write(stdout2,` ${palette2.warn(symbols.warn)} ${w}`);maybeHint(event.hint)}__name(renderMessage2,"renderMessage");function renderAlignedFields(fields,indent){let keys=Object.keys(fields),longest=keys.reduce((m,k)=>Math.max(m,k.length),0);for(let k of keys){let value=fields[k];value!=null&&write(stdout2,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout2,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout2,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r2=>displayWidth(String(r2[c2.key]??""))))),header=columns.map((c2,i2)=>padToWidth(c2.label,widths[i2])).join(" ");write(stdout2,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i2)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i2]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout2,`${marker} ${cells.join(" ")}`)}maybeHint(event.hint)}__name(renderTable2,"renderTable");function paintCell(cell,role){switch(role){case"success":return palette2.success(cell);case"warn":return palette2.warn(cell);case"error":return palette2.error(cell);case"dim":return palette2.dim(cell);case"accent":return palette2.accent(cell)}}__name(paintCell,"paintCell");function renderKv(event){event.headline&&write(stdout2,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout2.write(event.script.endsWith(`
9
9
  `)?event.script:`${event.script}
@@ -46,7 +46,7 @@ Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Hel
46
46
  `).includes(LOCAL_CREDENTIALS_RULE))return;let separator=current===""||current.endsWith(`
47
47
  `)?"":`
48
48
  `;fs2.appendFileSync(ignorePath,`${separator}${LOCAL_CREDENTIALS_RULE}
49
- `)}function resolveAuth(cfg=loadConfig()){return explicitAuth(cfg)??projectTokenFileAuth(cfg)??sessionAuth(cfg)}function resolveAccountAuth(cfg=loadConfig()){return explicitAuth(cfg)??sessionAuth(cfg)}function explicitAuth(cfg){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();return bearer?bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer}:null}function projectTokenFileAuth(cfg){let tokenFile=findProjectToken(cfg);return tokenFile?{kind:"project",token:tokenFile.file.token,tokenFile}:null}function sessionAuth(cfg){let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,LOCAL_CREDENTIALS_RULE,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),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}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");LOCAL_CREDENTIALS_RULE="*.local.json";__name(ignoreLocalCredentials,"ignoreLocalCredentials");__name(resolveAuth,"resolveAuth");__name(resolveAccountAuth,"resolveAccountAuth");__name(explicitAuth,"explicitAuth");__name(projectTokenFileAuth,"projectTokenFileAuth");__name(sessionAuth,"sessionAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});import{z as z113}from"zod";function createResponseSchema2(dataSchema){return z113.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId2,suffix){return`/management/projects/${encodeURIComponent(projectId2)}${suffix}`}function managementBranchPath(projectId2,branch,suffix){return managementProjectPath(projectId2,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId2,branch,suffix){return`/tenant/${encodeURIComponent(projectId2)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&&params.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z113.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor3){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor3))throw new Error("Invalid pagination cursor.");let base64=cursor3.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z113.object({items:z113.array(itemSchema),nextCursor:z113.string().nullable(),total:z113.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId2,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId2,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z113.uuid(),sessionStatusSchema=z113.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z113.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z113.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z113.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z113.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z113.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z113.string().nullable().optional(),goal:z113.string().nullable().optional(),provenance:z113.object({source:z113.enum(["studio","slack","mcp"]),creator:z113.object({kind:z113.enum(["user","slack","agent","oauth","conversation"]),id:z113.string()}),conversationId:z113.string().nullable(),runId:z113.string().nullable()}).nullable().optional(),createdBy:z113.string().optional(),createdAt:z113.iso.datetime().optional(),savedRevision:z113.string().nullable().optional(),targetBranch:z113.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z113.string().min(1)}),workingBranch:z113.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z113.url().nullable(),lastActivityAt:z113.iso.datetime(),expiresAt:z113.iso.datetime().nullable(),retention:z113.enum(["temporary","durable"]).optional(),visibility:z113.enum(["internal","user-visible"]).optional(),onExpire:z113.enum(["discard","keep"]),nextOperations:z113.array(z113.string())}),paginationShape={limit:z113.number().int().min(1).max(100).optional(),cursor:z113.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z113.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z113.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor3=>cursor3==null||/^[1-9]\d*$/.test(cursor3)&&Number.isSafeInteger(Number(cursor3)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z113.object({data:z113.array(z113.unknown()),meta:z113.object({limit:z113.number().int().positive(),offset:z113.number().int().nonnegative(),total:z113.number().int().nonnegative(),hasMore:z113.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z114}from"zod";var agent,chats,routines,routineRun,routineRuns,routineRunLedger,projectChats,chatAuthor,liveTurn,chatMessages,chatSearch,isoTime,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z114.object({id:uuidSchema,kind:z114.string(),title:z114.string().nullable(),description:z114.string().nullable()}),chats=z114.object({chats:z114.array(agent)}),routines=z114.object({routines:z114.array(z114.object({id:uuidSchema,name:z114.string(),instructions:z114.string(),paused:z114.boolean(),triggers:z114.object({schedule:z114.object({cron:z114.string(),timezone:z114.string()}).nullable(),event:z114.object({text:z114.string()}).nullable()}),nextRunAt:z114.string().nullable(),lastRunAt:z114.string().nullable(),lastOutcome:z114.string().nullable(),outOfAgentHoursUntil:z114.string().nullable()}))}),routineRun=z114.object({startedAt:z114.string(),trigger:z114.enum(["schedule","hand","event"]),startedBy:z114.object({kind:z114.enum(["person","agent"]),name:z114.string().nullable()}).nullable(),status:z114.enum(["queued","running","finished","failed","cancelled"]),outcome:z114.string().nullable(),summary:z114.string().nullable(),durationMs:z114.number().nullable(),credits:z114.number().nullable()}),routineRuns=z114.object({runs:z114.array(routineRun)}),routineRunLedger=z114.object({runs:z114.array(routineRun.extend({messageId:uuidSchema}))}),projectChats=z114.object({chats:z114.array(agent.extend({createdAt:z114.string(),lastMessageAt:z114.string().nullable(),running:z114.boolean(),awaitingAnswer:z114.boolean()}))}),chatAuthor=z114.object({kind:z114.enum(["person","agent","routine","system"]),id:z114.string().nullable()}),liveTurn=z114.object({invocationId:z114.string(),step:z114.string(),startedAt:z114.string()}).nullable().default(null),chatMessages=z114.object({threadId:z114.string().nullable(),title:z114.string().nullable(),messages:z114.array(z114.object({id:uuidSchema,role:z114.enum(["user","assistant"]),parts:z114.array(z114.unknown()),metadata:z114.record(z114.string(),z114.unknown()).nullable(),createdAt:z114.string(),author:chatAuthor,invocationId:z114.string().nullable().optional(),invocationStatus:z114.string().nullable().optional(),invocationTerminalReason:z114.string().nullable().optional()})),nextCursor:z114.string().nullable(),liveTurn,queue:z114.array(z114.object({id:uuidSchema,author:chatAuthor,failed:z114.boolean(),queuedAt:z114.string()})).default([]),queuePaused:z114.boolean().default(!1),queueWaitUntil:z114.string().nullable().default(null)}),chatSearch=z114.object({hits:z114.array(z114.object({chatId:uuidSchema,chatTitle:z114.string().nullable(),messageId:uuidSchema,role:z114.string(),authorKind:chatAuthor.shape.kind,createdAt:z114.string(),snippet:z114.string()}))}),isoTime=z114.iso.datetime({offset:!0}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId:projectId2,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId:projectId2})}),"buildRequest")},"agents.routineRuns":{domain:"agents",summary:"Read a routine\u2019s newest runs: when each started, what started it and how it ended.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRuns,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")},"agents.chats":{domain:"agents",summary:"Read every chat of the project, agents and regular chats, newest activity first.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:projectChats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest")},"agents.messages":{domain:"agents",summary:"Read a page of a chat, newest first, with whether a turn runs and what waits in its queue.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,cursor:z114.string().min(1).optional(),limit:z114.number().int().min(1).max(200).optional()}).strict(),outputSchema:chatMessages,buildRequest:__name(({projectId:projectId2,branch,threadId,cursor:cursor3,limit})=>({method:"GET",context:{branch},path:addQuery("/chat/project/messages",{projectId:projectId2,threadId,cursor:cursor3,limit})}),"buildRequest")},"agents.search":{domain:"agents",summary:"Search the words of the project\u2019s chats, best match first, with the ids to read around each hit.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,query:z114.string().trim().min(1).max(500),chatId:uuidSchema.optional(),after:isoTime.optional(),before:isoTime.optional(),limit:z114.number().int().min(1).max(50).optional()}).strict(),outputSchema:chatSearch,buildRequest:__name(({projectId:projectId2,branch,...query})=>({method:"GET",context:{branch},path:addQuery("/chat/project/search",{projectId:projectId2,...query})}),"buildRequest")},"agents.createChat":{domain:"agents",summary:"Open a new regular chat; it is listed once its first message is sent.",accessScope:"agents",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,title:z114.string().trim().min(1).max(120).optional()}).strict(),outputSchema:z114.object({id:uuidSchema}),buildRequest:__name(({projectId:projectId2,branch,id,title})=>({method:"POST",context:{branch},path:"/chat/project/threads",body:{projectId:projectId2,id,kind:"chat",...title?{title}:{}}}),"buildRequest")},"agents.runRoutine":{domain:"agents",summary:"Start a routine now, with an optional message for its run.",accessScope:"agents",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema,message:z114.string().trim().min(1).max(2e4).optional()}).strict(),outputSchema:z114.object({kind:z114.enum(["published","queued","replay","streaming","busy","refused"]),messageId:uuidSchema.nullable()}),buildRequest:__name(({projectId:projectId2,branch,threadId,routineId,message})=>({method:"POST",context:{branch},path:`/chat/project/threads/${threadId}/routines/${routineId}/run`,body:{projectId:projectId2,...message?{message}:{}}}),"buildRequest")},"agents.routineRunLedger":{domain:"agents",summary:"Read a routine\u2019s newest runs with the message that started each and the credits it spent.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRunLedger,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")}}}});import{z as z115}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z115.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z115.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z115.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z115.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z115.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z115.union([z115.literal(7),z115.literal(30),z115.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z115.object({date:z115.string(),content:z115.string(),updatedAt:z115.string(),updatedByUserId:z115.string()}),analyticsBreakdownSchema=z115.object({key:z115.string(),visitors:z115.number().int().nonnegative(),pageviews:z115.number().int().nonnegative()}),analyticsPageBreakdownSchema=z115.object({path:z115.string(),pageName:z115.string().nullable().optional(),visitors:z115.number().int().nonnegative(),pageviews:z115.number().int().nonnegative()}),analyticsPageviewsSchema=z115.object({range:z115.object({preset:analyticsPresetSchema,requestedFrom:z115.string(),requestedTo:z115.string(),effectiveFrom:z115.string(),effectiveTo:z115.string(),isRetentionLimited:z115.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z115.number().int().nonnegative(),pageviews:z115.number().int().nonnegative(),botPageviews:z115.number().int().nonnegative().default(0),botVisitors:z115.number().int().nonnegative().default(0),bounceRate:z115.number().min(0).max(100),viewsPerVisit:z115.number().nonnegative(),averageVisitDurationSeconds:z115.number().nonnegative(),visitorsSeries:z115.array(z115.object({date:z115.string(),visitors:z115.number().int().nonnegative()})),topPages:z115.array(analyticsPageBreakdownSchema),topBrowsers:z115.array(analyticsBreakdownSchema),topDevices:z115.array(analyticsBreakdownSchema),topBots:z115.array(analyticsBreakdownSchema).default([]),topAiAssistants:z115.array(analyticsBreakdownSchema).default([]),topCountries:z115.array(analyticsBreakdownSchema),topSources:z115.array(analyticsBreakdownSchema),annotations:z115.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z115.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z115.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z115.array(z115.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z115.object({branch:branchNameSchema,annotations:z115.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z115.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,date:z115.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z115.string().max(500)}).strict(),outputSchema:z115.union([analyticsAnnotationResponseSchema,z115.null()]),buildRequest:__name(({projectId:projectId2,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,date:z115.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z115.null(),buildRequest:__name(({projectId:projectId2,branch,date})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z116}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z116.object({id:z116.string(),name:z116.string()}),AssetDTOSchema2=z116.object({id:z116.string(),name:z116.string(),type:z116.enum(["file","folder"]),originalFileName:z116.string().nullable(),parentId:z116.string().nullable(),mimeType:z116.string().nullable(),fileSize:z116.number().nullable(),url:z116.string().nullable(),storageKey:z116.string().nullable(),slug:z116.string(),tags:z116.array(z116.string()).nullable().optional(),createdAt:z116.string().nullable(),updatedAt:z116.string().nullable(),altText:z116.string().nullable().optional(),caption:z116.string().nullable().optional(),aiCaption:z116.string().nullable().optional(),aiAltText:z116.string().nullable().optional(),aiTags:z116.array(z116.string()).nullable().optional(),aiPrimaryColor:z116.string().nullable().optional(),aiProcessingStatus:z116.string().nullable().optional(),width:z116.number().nullable().optional(),height:z116.number().nullable().optional(),path:z116.array(assetPathItemSchema).optional(),hasChildren:z116.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z116.object({cursor:z116.string().nullable().optional(),query:z116.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z116.object({url:z116.url(),mediaType:z116.string(),filename:z116.string()}),assetReadBaseSchema=z116.object({assetId:z116.uuid(),filename:z116.string(),mediaType:z116.string(),representation:z116.enum(["text","table","document","archive","image","transcript","video","model"]),content:z116.string(),derivedFiles:z116.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z116.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z116.literal("page"),start:z116.number().int().nonnegative(),end:z116.number().int().nonnegative(),total:z116.number().int().nonnegative(),nextCursor:z116.string().nullable(),complete:z116.boolean()}),assetReadBaseSchema.extend({mode:z116.literal("query"),query:z116.string(),source:z116.enum(["original-file","canonical-text","derived-files"]),truncated:z116.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z116.object({jobId:z116.string(),status:z116.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z116.string().nullable().optional(),credits:z116.number().optional(),costUsd:z116.number().optional(),billingMode:z116.enum(["fimo-credits","provider-account"]).optional(),task:z116.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z116.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z116.object({data:z116.object({message:z116.literal("success")})}),assetGenerationInputSchema=z116.object({projectId:uuidSchema,branch:branchNameSchema,task:z116.string().min(1).optional(),model:z116.string().min(1).optional(),options:z116.record(z116.string(),z116.unknown()),name:z116.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z116.string().max(2e3).optional(),caption:z116.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z116.object({projectId:uuidSchema,sessionId:uuidSchema,url:z116.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z116.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z116.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z116.string().max(1024).refine(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z116.string().max(2e3).optional(),caption:z116.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z116.string().max(200).optional(),type:z116.enum(["file","folder"]).optional(),mimePrefix:z116.string().max(50).optional(),sortBy:z116.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z116.enum(["asc","desc"]).optional(),includePath:z116.boolean().optional(),excludeHidden:z116.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId:projectId2,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId:projectId2,branch,id,cursor:cursor3,query})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor3??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId:projectId2,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,name:z116.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z116.record(z116.string(),z116.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z116.object({data:z116.record(z116.string(),z116.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z116.record(z116.string(),z116.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z116.object({data:z116.record(z116.string(),z116.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z116.unknown(),buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z116.object({data:z116.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z116.record(z116.string(),z116.unknown()),buildRequest:__name(({projectId:projectId2,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z116.object({data:z116.record(z116.string(),z116.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z117}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z117.object({projectId:uuidSchema,organizationId:z117.string(),balance:z117.object({totalAvailable:z117.number(),nearLimit:z117.boolean(),canUseAi:z117.boolean(),buckets:z117.object({dailyFreeAvailable:z117.number(),monthlyAvailable:z117.number(),purchasedAvailable:z117.number(),awardedAvailable:z117.number()})}),allowances:z117.object({dailyCredits:z117.object({periodCap:z117.number(),dailyGrant:z117.number(),usedThisPeriod:z117.number(),remainingThisPeriod:z117.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z118}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z118.object({ok:z118.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z118.array(z118.object({surface:backendSurfaceSchema,count:z118.number().int().nonnegative()})),conflicts:z118.array(backendConflictSchema).optional(),summary:z118.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z118.object({mergeId:uuidSchema,conflicts:z118.array(backendConflictSchema),draftResolutions:z118.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z118.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z118.object({data:z118.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z118.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z118.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z118.array(backendSurfaceDeltaSchema).max(6),crossSurface:z118.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z118.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z118.string().min(1),surfaces:z118.array(backendSurfaceDeltaSchema).max(6),crossSurface:z118.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z118.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z118.enum(["provisioning","active","deleted"]),kind:z118.enum(["user","agent-session"]),createdAt:z118.string().optional(),updatedAt:z118.string().optional(),createdBy:z118.string().nullable().optional(),deletedAt:z118.string().nullable().optional()}).passthrough(),branchResponseSchema=z118.object({data:branchSchema}),branchSurfaceStatusSchema=z118.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z118.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z118.iso.datetime(),backendCrossSurfaceFindingSchema=z118.object({id:z118.string(),kind:z118.string(),description:z118.string(),severity:z118.enum(["warning","error"]),source:z118.object({surface:backendSurfaceSchema,key:z118.string()}),target:z118.object({surface:backendSurfaceSchema,key:z118.string()}),actions:z118.array(z118.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z118.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z118.number().int().nonnegative(),conflictCount:z118.number().int().nonnegative(),items:z118.array(z118.object({verb:branchDeltaVerbSchema,key:z118.string(),detail:z118.string().optional(),origin:z118.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z118.record(z118.string(),z118.unknown()).optional()})).max(1e3).optional(),truncated:z118.boolean().optional(),error:z118.string().optional()}),branchSurfaceSummarySchema=z118.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z118.number().int().nonnegative(),conflictCount:z118.number().int().nonnegative(),error:z118.string().optional(),items:z118.array(z118.object({verb:branchDeltaVerbSchema,key:z118.string(),detail:z118.string().optional(),origin:z118.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z118.record(z118.string(),z118.unknown()).optional()})).optional(),truncated:z118.boolean().optional()}),branchStatusOutputSchema=z118.object({branch:branchNameSchema,against:branchNameSchema,state:z118.enum(["clean","changed"]),syncState:z118.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z118.array(branchSurfaceSummarySchema).max(6),crossSurface:z118.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z118.object({verb:branchDeltaVerbSchema,key:z118.string(),detail:z118.string().optional(),meta:z118.record(z118.string(),z118.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z118.string().min(1),surfaces:z118.array(branchSurfaceSummarySchema.extend({truncated:z118.boolean(),items:z118.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z118.object({path:z118.string(),state:z118.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z118.string(),additions:z118.number().int().nonnegative(),deletions:z118.number().int().nonnegative()}),contentSnapshotSchema=z118.object({id:z118.string(),slug:z118.string(),contentType:z118.string(),data:z118.record(z118.string(),z118.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z118.object({collection:z118.string(),rowId:z118.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z118.object({name:z118.string(),label:z118.string(),isSingleton:z118.boolean(),description:z118.string().nullable().default(null),fields:z118.record(z118.string(),z118.unknown())}),schemaDiffOutputSchema=z118.object({typeName:z118.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z118.object({id:z118.string(),name:z118.string(),type:z118.enum(["file","folder"]),mimeType:z118.string().nullable(),storageKey:z118.string().nullable(),url:z118.string().nullable(),fileSize:z118.number().nullable(),width:z118.number().nullable(),height:z118.number().nullable(),altText:z118.string().nullable(),caption:z118.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z118.object({assetId:z118.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z118.object({locale:z118.string(),key:z118.string(),parent:z118.string().nullable(),child:z118.string().nullable()}),formSnapshotSchema=z118.object({formName:z118.string(),label:z118.string().nullable(),schemaFingerprint:z118.string(),fields:z118.record(z118.string(),z118.unknown())}),formDiffOutputSchema=z118.object({formName:z118.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z118.object({surface:backendSurfaceSchema,key:z118.string(),kind:z118.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z118.string(),parentValue:z118.unknown().optional(),childValue:z118.unknown().optional(),conflictingFields:z118.array(z118.string()).optional(),code:z118.object({path:z118.string(),unresolvable:z118.boolean().optional(),reason:z118.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z118.object({field:z118.string(),choice:z118.enum(["parent","child","pick","ai-pick"]),pickedValue:z118.unknown().optional(),aiSessionId:z118.string().optional()}),conflictResolutionSchema=z118.object({surface:branchSurfaceSchema,key:z118.string(),choice:z118.enum(["parent","child","pick"]),pickedValue:z118.unknown().optional(),fieldPicks:z118.array(fieldPickSchema).optional()}),mergeResultSchema=z118.object({ok:z118.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z118.array(z118.object({surface:branchSurfaceSchema,count:z118.number().int().nonnegative()})),conflicts:z118.array(conflictSchema).optional(),summary:z118.string().optional()}),resolvedMergeStrategySchema=z118.object({engine:z118.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z118.enum(["ff_only","ff_prefer","merge"]),squash:z118.boolean()}),mergeAcceptedSchema=z118.object({mergeId:uuidSchema,streamUrl:z118.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z118.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z118.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z118.string().nullable(),error:z118.string().nullable()}),mergeHydrationSchema=z118.object({mergeId:uuidSchema,conflicts:z118.array(conflictSchema),draftResolutions:z118.array(conflictResolutionSchema),status:z118.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z118.object({content:z118.string(),sha:z118.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z118.object({path:z118.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,includeDeleted:z118.boolean().optional(),includeAgentBranches:z118.boolean().optional()}).strict(),outputSchema:z118.object({data:z118.array(branchSchema)}),buildRequest:__name(({projectId:projectId2,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId:projectId2,from,name})=>({method:"POST",path:managementProjectPath(projectId2,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z118.object({branch:branchSchema,conflicts:z118.number().int().nonnegative()}),buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z118.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z118.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z118.unknown(),buildRequest:__name(({projectId:projectId2,branch})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z118.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z118.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,path:z118.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,path:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff/code/file"),{path:path52,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,collection:z118.string().min(1),rowId:z118.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z118.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z118.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,locale:z118.string().min(1),key:z118.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,formName:z118.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z118.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId:projectId2,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z118.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId:projectId2,mergeId})=>({method:"GET",path:managementProjectPath(projectId2,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z118.object({ok:z118.boolean()}),buildRequest:__name(({projectId:projectId2,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z118.object({ok:z118.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"GET",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z118.array(conflictResolutionSchema)}).strict(),outputSchema:z118.object({mergeId:uuidSchema,lastEditedAt:z118.string()}),buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z118.object({mergeId:uuidSchema,lastEditedAt:z118.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z118.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId:projectId2,branch,from,path:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z119}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z119.object({id:z119.string(),hostname:z119.string(),status:z119.string(),ssl:z119.record(z119.string(),z119.unknown()),cnameTarget:z119.string(),apexTargets:z119.array(z119.string()),dnsAutoConfigured:z119.boolean(),createdAt:z119.unknown(),provider:z119.enum(["cloudflare","saas_custom_domains"]),domainType:z119.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z119.object({id:uuidSchema,domain:z119.string(),status:z119.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z119.enum(["fimo","external"]),autoRenew:z119.boolean(),paymentStatus:z119.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z119.string().nullable()}).passthrough(),domainSearchResultSchema=z119.object({domain:z119.string(),available:z119.boolean(),premium:z119.boolean(),price:z119.number().nullable(),renewalPrice:z119.number().nullable(),purchaseType:z119.string().nullable()}).passthrough(),domainPricingSchema=z119.object({domain:z119.string(),price:z119.number().nullable(),renewalPrice:z119.number().nullable(),premium:z119.boolean(),allowedYears:z119.array(z119.number().int().positive())}).passthrough(),projectPath=__name((projectId2,suffix)=>`/management/projects/${encodeURIComponent(projectId2)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z119.object({}).strict(),outputSchema:z119.object({domainPurchaseEnabled:z119.boolean(),publicationDomain:z119.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,slug:z119.string().min(1).max(63)}).strict(),outputSchema:z119.object({subdomain:z119.string(),subdomainUpdatedAt:z119.string()}),buildRequest:__name(({projectId:projectId2,slug})=>({method:"PATCH",path:projectPath(projectId2,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,base:z119.string().min(1).max(63).optional(),max:z119.number().int().positive().optional()}).strict(),outputSchema:z119.array(z119.string()),buildRequest:__name(({projectId:projectId2,base,max})=>({method:"GET",path:addQuery(projectPath(projectId2,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z119.object({data:z119.object({suggestions:z119.array(z119.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema}).strict(),outputSchema:z119.array(projectDomainSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:projectPath(projectId2,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,hostname:z119.string().min(1).max(255),redirectToWww:z119.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId2,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,domainId:z119.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.setPrimary":{domain:"domains",summary:"Make a serving custom domain the primary domain of a site.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,domainId:z119.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/primary`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.setRedirect":{domain:"domains",summary:"Redirect a custom domain to another domain of the same site with 301, 302, 307 or 308 (default 307), or change an existing redirect. Redirecting the primary domain moves the primary: tell the user to publish again so canonical links use the new one.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,domainId:uuidSchema,targetDomainId:uuidSchema,status:z119.union([z119.literal(301),z119.literal(302),z119.literal(307),z119.literal(308)]).optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId,targetDomainId,status})=>({method:"PUT",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/redirect`),body:{targetDomainId,status},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.serve":{domain:"domains",summary:"Make a custom domain serve the site instead of redirecting. If it becomes the primary domain, tell the user to publish again so canonical links use it.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,domainId:uuidSchema}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/redirect`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site, together with every domain that redirects to it.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,domainId:z119.string().min(1)}).strict(),outputSchema:z119.object({success:z119.boolean(),hostname:z119.string(),removed:z119.array(z119.object({id:z119.string(),hostname:z119.string()})).optional()}),buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z119.object({keyword:z119.string().min(1).max(100),tldFilter:z119.array(z119.string().min(1)).optional()}).strict(),outputSchema:z119.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z119.object({domain:z119.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z119.object({organizationId:z119.string().min(1)}).strict(),outputSchema:z119.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z119.object({organizationId:z119.string().min(1),domain:z119.string().min(1).max(255),years:z119.number().int().min(1).max(10).optional(),autoRenew:z119.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z119.object({organizationId:z119.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z120}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z120.object({id:z120.string(),entryId:z120.string(),documentId:z120.string(),slug:z120.string(),locale:z120.string().optional(),createdAt:z120.string(),updatedAt:z120.string(),__fimo:z120.object({contentType:z120.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z120.object({data:z120.array(EntryDTOSchema2),meta:z120.object({limit:z120.number(),offset:z120.number(),total:z120.number(),hasMore:z120.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z120.union([z120.string(),z120.number(),z120.boolean(),z120.null()]),entryWhereOperatorSchema2=z120.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z120.array(entryWhereScalarSchema2).optional(),$nin:z120.array(entryWhereScalarSchema2).optional(),$contains:z120.string().optional(),$startsWith:z120.string().optional(),$null:z120.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z120.record(z120.string(),z120.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z120.record(z120.string(),z120.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z120.object({data:z120.record(z120.string(),z120.unknown()),locale:z120.string().min(1).optional(),documentId:z120.uuid().optional()}),BulkCreateEntriesResponseSchema2=z120.object({data:z120.array(EntryDTOSchema2),meta:z120.object({created:z120.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z120.object({data:z120.array(EntryDTOSchema2),meta:z120.object({updated:z120.number().int().nonnegative(),missing:z120.array(z120.string())})}),BulkDeleteEntriesResponseSchema2=z120.object({data:z120.array(EntryDTOSchema2),meta:z120.object({deleted:z120.number().int().nonnegative(),missing:z120.array(z120.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z120.string().min(1).max(255),localeSchema=z120.string().min(1),populateSchema=z120.array(z120.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z120.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,search:z120.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,search,locale,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z120.string().min(1).max(255),data:entryDataSchema,locale:z120.string().min(1).optional(),documentId:z120.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z120.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z120.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z120.record(z120.string(),z120.unknown())}).strict(),outputSchema:z120.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z120.object({data:z120.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,sql:z120.string().min(1)}).strict(),outputSchema:z120.object({data:z120.array(z120.record(z120.string(),z120.unknown())),meta:z120.object({rowCount:z120.number().int().nonnegative(),truncated:z120.boolean()})}),buildRequest:__name(({projectId:projectId2,branch,sql})=>({method:"POST",path:tenantPath(projectId2,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z120.array(z120.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z120.union([z120.object({ids:z120.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z120.object({where:EntryWhereSchema2}),z120.object({updates:z120.array(z120.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z120.union([z120.object({ids:z120.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z120.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z121}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z121.object({id:z121.literal("production"),projectId:uuidSchema,name:z121.string(),kind:z121.literal("production"),sourceBranch:z121.string().min(1),isPublished:z121.boolean(),url:z121.string().nullable()}),previewEnvironmentSchema=z121.object({id:z121.literal("preview"),projectId:uuidSchema,name:z121.string(),kind:z121.literal("preview"),matchedBranchCount:z121.number().int().nonnegative()}),customEnvironmentSchema=z121.object({id:uuidSchema,projectId:uuidSchema,name:z121.string().min(1).max(64),branchPatterns:z121.array(z121.string().min(1).max(255)).min(1),description:z121.string().max(255).nullable(),kind:z121.literal("custom"),matchedBranchCount:z121.number().int().nonnegative()}),environmentSchema=z121.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z121.string().trim().min(1).max(64),branchPatterns:z121.array(z121.string().min(1).max(255)).min(1),description:z121.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema}).strict(),outputSchema:z121.array(environmentSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/environments")}),"buildRequest"),projectOutput:__name(body=>z121.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,environmentId:z121.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,environmentId:z121.string().min(1)}).strict(),outputSchema:z121.object({deletedId:uuidSchema}),buildRequest:__name(({projectId:projectId2,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z121.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z122}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z122.object({data:z122.object({path:z122.string(),content:z122.string(),totalLines:z122.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z122.object({data:z122.object({paths:z122.array(z122.string().min(1)).max(2e3),truncated:z122.boolean()})}),fileGrepOutputSchema=z122.object({data:z122.object({matches:z122.array(z122.object({path:z122.string().min(1),line:z122.number().int().positive(),text:z122.string()})).max(200),truncated:z122.boolean()})}),fileWriteInputSchema=z122.object({projectId:uuidSchema,sessionId:uuidSchema,path:z122.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z122.boolean().optional()}).strict(),fileEditInputSchema=z122.object({projectId:uuidSchema,sessionId:uuidSchema,path:z122.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z122.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z122.object({path:z122.string(),created:z122.boolean(),tip:z122.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z122.object({projectId:uuidSchema,sessionId:uuidSchema,files:z122.array(z122.object({path:z122.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files2=>files2.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z122.array(z122.object({path:z122.string(),created:z122.boolean()}).passthrough()),tip:z122.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z122.object({path:z122.string(),replacements:z122.number().int().nonnegative(),tip:z122.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z122.object({path:z122.string(),deleted:z122.literal(!0),tip:z122.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z122.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z122.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,path:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z122.object({...fileSearchInputShape,pattern:z122.string().min(1).max(300).optional(),limit:z122.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z122.object({...fileSearchInputShape,pattern:z122.string().min(1).max(200),include:z122.string().min(1).max(300).optional(),caseInsensitive:z122.boolean().optional(),maxMatches:z122.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,sessionId:uuidSchema,path:z122.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"buildRequest")}}}});import{z as z123}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z123.object({data:z123.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page2=z123.object({data:z123.array(formSubmissionSchema),total:z123.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page2.data.length===0&&offset<page2.total)throw new Error("Expected a page that advances the cursor.");return{items:page2.data,nextCursor:offset+page2.data.length<page2.total?encodePaginationCursor(offset+page2.data.length):null,total:page2.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z123.object({type:z123.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z123.string(),placeholder:z123.string().optional(),required:z123.boolean().optional(),defaultValue:z123.string().optional(),options:z123.array(z123.string()).optional(),validation:z123.object({minLength:z123.number().optional(),maxLength:z123.number().optional(),min:z123.number().optional(),max:z123.number().optional(),pattern:z123.string().optional(),maxFileSize:z123.number().optional(),accept:z123.array(z123.string()).optional()}).optional()}),FormContentSchema2=z123.object({name:z123.string().min(1).max(255),label:z123.string().min(1).max(255),fields:z123.record(z123.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z123.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z123.record(z123.string(),z123.unknown()).nullable().optional(),createdAt:z123.string(),updatedAt:z123.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z123.object({data:formSchema}),formSubmissionSchema=z123.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z123.record(z123.string(),z123.unknown()),submittedAt:z123.string()}),formSubmissionResponseSchema=z123.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z123.object({data:z123.object({total:z123.number().int().nonnegative(),dailyCounts:z123.array(z123.object({date:z123.string(),count:z123.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z123.array(formSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId2,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255),...paginationShape,searchQuery:z123.string().max(200).optional(),sortDirection:z123.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId:projectId2,branch,id,limit,cursor:cursor3,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor:cursor3,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255),submissionId:z123.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,id:z123.string().min(1).max(255),submissionId:z123.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z124}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z124.object({costUsd:z124.number(),credits:z124.number().optional(),billingMode:z124.enum(["fimo-credits","provider-account"]).optional(),confidence:z124.enum(["exact","estimated","metered"]),basis:z124.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,model:z124.string().min(1),options:z124.record(z124.string(),z124.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId2)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,task:z124.string().min(1),options:z124.record(z124.string(),z124.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,branch,task,options})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z125}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z125.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z125.object({versionId:uuidSchema,commitHash:z125.string(),name:z125.string(),description:z125.string().nullable(),kind:historyKindSchema,createdAt:z125.iso.datetime(),expiresAt:z125.iso.datetime()}),projectVersionPageSchema=z125.object({items:z125.array(projectVersionSchema),nextCursor:z125.string().nullable()}),historySummarySchema=z125.object({usage:z125.object({versionCount:z125.number().int().nonnegative(),snapshotBytes:z125.number().int().nonnegative()}),retentionDays:z125.number().int().positive()}),restoreResultSchema=z125.object({durationMs:z125.number().nonnegative().optional(),warning:z125.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema,limit:z125.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/versions"),{limit,cursor:cursor3})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema,name:z125.string().min(1),description:z125.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z126}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page2=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page2.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page2.items.map(publicationRecord),nextCursor:page2.nextCursor,retention:page2.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z126.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z126.object({isPublished:z126.boolean(),publishedAt:z126.iso.datetime().nullable(),publishedVersion:z126.string().nullable()}),publicationOutputSchema=z126.object({id:uuidSchema,status:z126.enum(["queued","building","published","failed","canceled"]),label:z126.string().nullable(),notes:z126.string().nullable(),source:z126.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z126.string().nullable(),framework:z126.string().nullable(),commit:z126.string().nullable()}),createdAt:z126.iso.datetime(),finishedAt:z126.iso.datetime().nullable(),url:z126.string().nullable(),failureCode:z126.string().nullable()}),publicationsPageOutputSchema=z126.object({items:z126.array(publicationOutputSchema),nextCursor:z126.string().nullable(),retention:z126.object({scope:z126.literal("publication_attempt_record"),records:z126.literal("project_lifetime")})}),publicationLogsOutputSchema=z126.object({status:z126.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z126.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z126.string().nullable(),items:z126.array(z126.object({timestamp:z126.iso.datetime(),phase:z126.enum(["build","deploy"]),stream:z126.enum(["command","stdout","stderr","status","error"]),message:z126.string()}))}),sandboxLogsOutputSchema=z126.object({status:z126.enum(["ok","unavailable"]),reason:z126.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z126.string().nullable(),items:z126.array(z126.object({id:z126.string(),timestamp:z126.iso.datetime().nullable(),source:z126.enum(["install","dev-server"]),phase:z126.string(),stream:z126.enum(["combined","stdout","stderr"]),message:z126.string()})),nextCursor:z126.string().nullable(),retention:z126.object({scope:z126.literal("sandbox_process_snapshot"),timestamps:z126.literal("process_start"),droppedOldest:z126.boolean(),phases:z126.array(z126.object({phase:z126.string(),source:z126.enum(["install","dev-server"]),status:z126.string(),startedAt:z126.iso.datetime().nullable(),exitCode:z126.number().int().nullable(),events:z126.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z126.object({url:z126.string(),branch:branchNameSchema}),previewOpenOutputSchema=z126.object({url:z126.url(),expiresAt:z126.iso.datetime().nullable()}),publishOutputSchema=z126.object({success:z126.boolean(),message:z126.string().optional(),firstPublish:z126.boolean(),publicationId:z126.string().optional(),url:z126.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,limit:z126.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId:projectId2,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/publications"),{limit,before:cursor3})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,publicationId:z126.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId})=>({method:"GET",path:managementProjectPath(projectId2,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,label:z126.string().trim().min(1).max(120).optional(),notes:z126.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId:projectId2,label,notes})=>({method:"POST",path:managementProjectPath(projectId2,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,publicationId:z126.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/sandbox/logs"),{limit,before:cursor3})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";var integrationIdSchema,toolEffectSchema,integrationSchema,integrationToolSchema,integrationGuideSchema,integrationRunResultSchema,runInputShape,integrationsOperations,init_integrations=__esm({"../../packages/sdk/dist/operations/integrations.js"(){"use strict";init_common2();integrationIdSchema=z127.string().min(2).max(120).regex(/^[a-z0-9][a-z0-9_-]*$/),toolEffectSchema=z127.enum(["read","write","delete","financial"]),integrationSchema=z127.object({id:z127.string(),kind:z127.enum(["catalog","custom","builtIn"]),name:z127.string(),description:z127.string(),host:z127.string().nullable(),readOnly:z127.boolean(),installed:z127.boolean(),enabled:z127.boolean(),accountName:z127.string().nullable(),settings:z127.array(z127.object({key:z127.string(),label:z127.string(),description:z127.string().nullable(),required:z127.boolean()})),settingsValues:z127.record(z127.string(),z127.string()),missingSettings:z127.array(z127.string())}),integrationToolSchema=z127.object({integrationId:z127.string(),integrationName:z127.string(),key:z127.string(),name:z127.string(),description:z127.string(),effect:toolEffectSchema,input:z127.record(z127.string(),z127.unknown()).optional()}),integrationGuideSchema=z127.object({integrationId:z127.string(),name:z127.string(),description:z127.string(),content:z127.string()}),integrationRunResultSchema=z127.discriminatedUnion("status",[z127.object({status:z127.literal("ok"),output:z127.record(z127.string(),z127.unknown())}),z127.object({status:z127.literal("approval_required"),request:z127.string(),approveUrl:z127.string(),reason:z127.string(),integration:z127.object({id:z127.string(),name:z127.string()}),tool:z127.object({key:z127.string(),name:z127.string(),effect:toolEffectSchema}),input:z127.record(z127.string(),z127.unknown()),canAlwaysAllow:z127.boolean()}),z127.object({status:z127.literal("blocked"),reason:z127.string()})]),runInputShape={projectId:uuidSchema,integrationId:integrationIdSchema,tool:z127.string().min(1).max(120),input:z127.record(z127.string(),z127.unknown()).default({})},integrationsOperations={"integrations.list":{domain:"integrations",summary:"List the integrations this site can use, such as Google Search Console: whether each is on for the site, its connected account, and settings it still needs.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema}).strict(),outputSchema:z127.array(integrationSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/integrations/catalog")}),"buildRequest"),projectOutput:__name(body=>z127.array(integrationSchema).parse(responseData(body)),"projectOutput")},"integrations.tools":{domain:"integrations",summary:`Find the tools of the integrations on for this site by what you need, in plain words ("clicks by page", "sitemap"): the best matches, each with its key, the start of what it does and whether it reads or changes data. Pass a tool key to get that tool's input JSON schema, before you run it.`,accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,search:z127.string().max(200).optional(),integrationId:integrationIdSchema.optional(),tool:z127.string().min(1).max(120).optional()}).strict(),outputSchema:z127.array(integrationToolSchema),buildRequest:__name(({projectId:projectId2,search,integrationId,tool})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/integrations/tools"),{search,integration:integrationId,tool})}),"buildRequest"),projectOutput:__name(body=>z127.array(integrationToolSchema).parse(responseData(body)),"projectOutput")},"integrations.guide":{domain:"integrations",summary:"Read an integration's guide before running its tools the first time: which tool answers which question, and how to read its numbers.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,integrationId:integrationIdSchema}).strict(),outputSchema:integrationGuideSchema,buildRequest:__name(({projectId:projectId2,integrationId})=>({method:"GET",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/guide`)}),"buildRequest"),projectOutput:__name(body=>integrationGuideSchema.parse(responseData(body)),"projectOutput")},"integrations.run":{domain:"integrations",summary:"Run an integration tool that reads data, with the input its JSON schema describes. Tools that change data in the outside service run with integrations.write.",accessScope:"read",effect:"read",inputSchema:z127.object(runInputShape).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:{tool,input,readOnly:!0}}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.write":{domain:"integrations",summary:"Run an integration tool that changes data in the outside service, such as submitting a sitemap to Google, only when the user asked for that change. Unless the site always allows the tool, the answer is approval_required with an approveUrl to give the user; once they allowed it in Fimo, call again with the exact same tool and input plus the approval code they paste back. A code works for one hour.",accessScope:"write",effect:"mutation",inputSchema:z127.object({...runInputShape,approval:z127.string().min(1).max(4e3).optional()}).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input,approval})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:withoutUndefined({tool,input,approval})}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.setEnabled":{domain:"integrations",summary:"Turn an integration on or off for this site. Turning one on may need its account connected first.",accessScope:"write",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,integrationId:integrationIdSchema,enabled:z127.boolean()}).strict(),outputSchema:z127.object({ok:z127.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,enabled})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}`),body:{enabled}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")},"integrations.updateSettings":{domain:"integrations",summary:"Change an integration's settings for this site. A choice must be one the connected account offers.",accessScope:"write",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,integrationId:integrationIdSchema,settings:z127.record(z127.string(),z127.string().max(500))}).strict(),outputSchema:z127.object({ok:z127.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,settings:settings2})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/settings`),body:{settings:settings2}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")}}}});import{z as z128}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z128.object({content:z128.string(),updatedAt:z128.string().nullable(),updatedBy:z128.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance; pass the updatedAt you read as expectedUpdatedAt to refuse the save if someone saved since.",accessScope:"write",effect:"mutation",inputSchema:z128.object({projectId:uuidSchema,content:z128.string(),expectedUpdatedAt:z128.string().nullable().optional()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2,content:content2,expectedUpdatedAt})=>({method:"PUT",path:managementProjectPath(projectId2,"/knowledge"),body:expectedUpdatedAt===void 0?{content:content2}:{content:content2,expectedUpdatedAt}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z129}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z129.object({key:z129.string(),value:z129.string().optional(),defaultValue:z129.string(),locale:z129.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z129.object({data:z129.array(z129.union([TranslationDTOSchema2,z129.object({key:z129.string(),values:z129.record(z129.string(),z129.string())})]))}),labelUpsertOutputSchema=z129.object({created:z129.number().int().nonnegative(),updated:z129.number().int().nonnegative(),deleted:z129.number().int().nonnegative(),defaultLocale:z129.string(),locales:z129.array(z129.string())}),labelDeleteOutputSchema=z129.object({key:z129.string(),locale:z129.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z129.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z129.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z129.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"GET",path:tenantPath(projectId2,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z129.object({projectId:uuidSchema,branch:branchNameSchema,key:z129.string(),value:z129.string(),locale:z129.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId:projectId2,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId2,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z129.object({projectId:uuidSchema,branch:branchNameSchema,records:z129.array(z129.object({key:z129.string(),value:z129.string(),locale:z129.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId:projectId2,branch,records})=>({method:"POST",path:tenantPath(projectId2,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z129.object({projectId:uuidSchema,branch:branchNameSchema,locale:z129.string().optional(),key:z129.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId2,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z130}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z130.object({translated:z130.number().int().nonnegative(),total:z130.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z130.object({defaultLocale:z130.string(),locales:z130.array(z130.object({locale:z130.string(),isDefault:z130.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z130.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z130.object({locale:z130.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z130.object({locale:z130.string(),entriesDeleted:z130.number().int().nonnegative(),labelsDeleted:z130.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId2,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z131}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z131.object({id:z131.string().min(1),name:z131.string(),slug:z131.string()}),organizationMemberSchema=z131.object({id:z131.string().min(1),role:z131.string(),createdAt:z131.string().optional(),user:z131.object({id:z131.string().min(1),name:z131.string().nullable().optional(),email:z131.string().nullable().optional()}).optional()}),organizationInvitationSchema=z131.object({id:z131.string().min(1),email:z131.email(),role:z131.string(),organizationId:z131.string().min(1),inviterId:z131.string().min(1),status:z131.string(),expiresAt:z131.string(),createdAt:z131.string()}).passthrough(),referralSummarySchema=z131.object({counts:z131.object({signed_up:z131.number().int(),activated:z131.number().int()}),credits:z131.object({total:z131.number().int(),earned:z131.number().int().optional()}),canRefer:z131.boolean().optional(),eligibleAt:z131.iso.datetime().nullable().optional()}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z131.object({}).strict(),outputSchema:createResponseSchema2(z131.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z131.object({organizationId:z131.string().min(1)}).strict(),outputSchema:z131.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z131.object({members:z131.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z131.object({organizationId:z131.string().min(1),email:z131.email(),role:z131.enum(["owner","admin","member"]),resend:z131.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z131.object({userId:z131.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z132}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z132.object({id:uuidSchema,name:z132.string(),displayName:z132.string().nullable(),organizationId:z132.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z132.string().optional(),appUrl:z132.string().nullable().optional()}).passthrough(),projectResponseSchema=z132.object({data:projectSchema}),transferResultSchema=z132.object({projectId:z132.string(),sourceOrganizationId:z132.string(),targetOrganizationId:z132.string(),movedThreads:z132.number().int().nonnegative(),revokedInvites:z132.number().int().nonnegative(),revokedGrants:z132.number().int().nonnegative(),preservedGrants:z132.number().int().nonnegative(),warnings:z132.array(z132.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z132.object({organizationId:z132.string().min(1).optional()}).strict(),outputSchema:z132.object({data:z132.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z132.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z132.object({organizationId:z132.string().min(1),displayName:z132.string().min(1).optional(),origin:z132.enum(["scratch","migration"]).optional(),starter:z132.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,targetOrganizationId:z132.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId:projectId2,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId2,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,email:z132.email(),role:z132.enum(["full","edit","comment","view"])}).strict(),outputSchema:z132.object({id:z132.string().min(1)}),buildRequest:__name(({projectId:projectId2,email,role})=>({method:"POST",path:managementProjectPath(projectId2,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z132.object({id:z132.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema}).strict(),outputSchema:z132.unknown(),buildRequest:__name(({projectId:projectId2})=>({method:"DELETE",path:managementProjectPath(projectId2,""),body:{}}),"buildRequest")}}}});import{z as z133}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z133.iso.datetime(),scheduleStatusSchema=z133.enum(["ok","failed"]),runStatusSchema=z133.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z133.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z133.string().min(1),name:z133.string().min(1),cron:z133.string().min(1),command:z133.string().min(1),secretKeys:z133.array(z133.string().min(1)),enabled:z133.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z133.string().nullable(),overPolicyReasons:z133.array(z133.string()).optional()}).passthrough(),usageSchema=z133.object({runCount:z133.number().int().nonnegative(),runsWithOutput:z133.number().int().nonnegative()}),policySchema=z133.object({maxRuns:z133.number().int().positive(),retentionDays:z133.number().int().positive().nullable(),outputRetentionDays:z133.number().int().positive(),maxOutputBytes:z133.number().int().positive()}).passthrough(),planSchema=z133.object({code:z133.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z133.enum(["cached_subscription","free_fallback"]),activeSchedules:z133.object({used:z133.number().int().nonnegative(),limit:z133.number().int().positive()}),minCadenceMinutes:z133.number().int().positive(),maxRunMs:z133.number().int().positive(),concurrency:z133.object({used:z133.number().int().nonnegative(),limit:z133.number().int().positive()}),compute:z133.object({settledMs:z133.number().int().nonnegative(),activeMs:z133.number().int().nonnegative(),reservedMs:z133.number().int().nonnegative().optional(),includedMs:z133.number().int().positive(),remainingMs:z133.number().int().nonnegative(),resetsAt:dateSchema}),state:z133.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z133.array(z133.string())}).passthrough(),runSchema=z133.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z133.string().min(1),scheduleName:z133.string().min(1),command:z133.string().min(1),status:runStatusSchema,trigger:z133.enum(["cron","ui","cli"]),triggeredBy:z133.object({id:z133.string().min(1),name:z133.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z133.number().int().nullable(),errorCode:z133.string().nullable(),error:z133.string().nullable(),outputBytes:z133.number().int().nonnegative(),outputTruncated:z133.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z133.string().nullable(),secretSnapshot:z133.object({state:z133.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z133.array(z133.object({key:z133.string().min(1),updatedAt:dateSchema.nullable(),resolution:z133.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z133.object({items:z133.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z133.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z133.object({items:z133.array(runSchema),nextCursor:z133.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z133.string().min(1).max(120),cron:z133.string().min(1).max(120),command:z133.string().min(1).max(500),secretKeys:z133.array(z133.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z133.object({...scheduleContextShape}).strict(),outputSchema:z133.array(scheduleSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z133.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z133.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z133.object({...scheduleContextShape,...scheduleWriteShape,enabled:z133.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z133.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z133.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,limit,cursor:cursor3,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor:cursor3,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z133.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId:projectId2,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z133.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z133.object({ok:z133.literal(!0)}),buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z133.object({ok:z133.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z134}from"zod";function projectSchemaDefinition(body){return z134.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z134.object({id:z134.string(),name:z134.string(),label:z134.string(),isSingleton:z134.boolean(),slugUnique:z134.boolean(),i18n:z134.record(z134.string(),z134.unknown()),description:z134.string().nullable().default(null),groups:z134.array(z134.record(z134.string(),z134.unknown())),fields:z134.record(z134.string(),z134.unknown()),createdAt:z134.string(),updatedAt:z134.string()}).passthrough(),schemaListOutputSchema=z134.object({contentTypes:z134.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z134.object({typeName:z134.string().min(1).max(255),generatedPaths:z134.array(z134.string().min(1)).max(1e3),tip:z134.string().min(1)})}),schemaDefinitionInputSchema=z134.record(z134.string(),z134.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z134.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z134.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z134.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"GET",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z134.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z134.array(schemaDefinitionInputSchema).min(1).max(100),operations:z134.array(z134.record(z134.string(),z134.unknown())).optional()}).strict(),outputSchema:z134.array(z134.unknown()),buildRequest:__name(({projectId:projectId2,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId2,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z134.object({data:z134.array(z134.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z134.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z134.string().min(1).max(255)}).strict(),outputSchema:z134.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z134.object({data:z134.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z134.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z134.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z134.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z134.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z134.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z134.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z134.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z135}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z135.union([z135.literal("production"),z135.literal("preview"),uuidSchema]),secretKindSchema=z135.enum(["variable","secret"]),projectSecretSchema=z135.object({id:z135.string().min(1),projectId:z135.string().min(1),key:z135.string().min(1),kind:secretKindSchema,exposure:z135.enum(["public","private"]),environment:environmentSchema2,value:z135.string().optional(),maskedValue:z135.string().optional(),createdAt:z135.string(),updatedAt:z135.string()}),secretWriteInputSchema=z135.object({projectId:uuidSchema,key:z135.string().min(1).max(255),kind:secretKindSchema,value:z135.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z135.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z135.array(projectSecretSchema),buildRequest:__name(({projectId:projectId2,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z135.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z135.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,key:z135.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z135.unknown(),buildRequest:__name(({projectId:projectId2,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z135.object({projectId:uuidSchema,branch:z135.string().min(1)}).strict(),outputSchema:z135.object({branch:z135.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z135.array(z135.object({branch:z135.string().optional(),env:z135.string().optional(),parentBranch:z135.string().nullable().optional(),parentEnv:z135.string().nullable().optional(),resolvedEnvironment:z135.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z136}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z136.object({status:z136.literal("passed")}).passthrough(),sessionConflictSummarySchema=z136.object({surface:surfaceNameSchema,key:z136.string().min(1),kind:z136.string().optional(),description:z136.string(),path:z136.string().optional()}).passthrough(),surfaceDeltaItemSchema=z136.object({verb:z136.enum(["added","removed","changed","conflict"]),key:z136.string(),detail:z136.string().optional(),origin:z136.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z136.record(z136.string(),z136.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z136.object({surface:surfaceNameSchema,status:z136.enum(["ok","timed_out","failed","unchanged"]),durationMs:z136.number().int().nonnegative().optional(),changedCount:z136.number().int().nonnegative(),conflictCount:z136.number().int().nonnegative(),items:z136.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z136.boolean().optional(),error:z136.string().optional()}).passthrough(),sessionChangesSchema=z136.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z136.iso.datetime(),surfaces:z136.array(perSurfaceDeltaSchema),crossSurface:z136.array(crossSurfaceFindingSchema).optional(),fingerprint:z136.string()}).passthrough(),projectScriptStatusSchema=z136.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z136.discriminatedUnion("operation",[z136.object({operation:z136.literal("dependencies_install"),repairedInstallPolicy:z136.boolean(),tip:z136.string()}),z136.object({operation:z136.literal("schemas_sync"),tip:z136.string()}),z136.object({operation:z136.literal("typecheck"),status:projectScriptStatusSchema,output:z136.string()}),z136.object({operation:z136.literal("lint"),status:projectScriptStatusSchema,output:z136.string()})]),conflictSchema2=z136.object({surface:surfaceNameSchema,key:z136.string(),kind:z136.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z136.string(),parentValue:z136.unknown().optional(),childValue:z136.unknown().optional(),conflictingFields:z136.array(z136.string()).optional(),code:z136.object({path:z136.string(),unresolvable:z136.boolean().optional(),reason:z136.string().optional(),targetCommits:z136.array(z136.object({sha:z136.string(),subject:z136.string(),body:z136.string().optional(),author:z136.string(),date:z136.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z136.object({oid:z136.string().optional(),content:z136.string().optional(),truncated:z136.boolean(),binary:z136.boolean()}),codeConflictDetailSchema=z136.object({path:z136.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z136.string(),targetTipSha:z136.string(),mergeBaseSha:z136.string().optional()}),resolutionChoiceSchema=z136.enum(["parent","child","pick"]),conflictResolutionSchema2=z136.object({surface:surfaceNameSchema,key:z136.string().min(1),choice:resolutionChoiceSchema,pickedValue:z136.unknown().optional(),fieldPicks:z136.array(z136.object({field:z136.string().min(1),choice:resolutionChoiceSchema,pickedValue:z136.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z136.string().trim().min(1).max(120).optional(),goal:z136.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z136.object({session:sessionEnvelopeSchema,adopted:z136.boolean()}),buildRequest:__name(({projectId:projectId2,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId2,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"GET",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z136.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z136.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z136.number().int().min(1).max(100).optional()}).strict(),outputSchema:z136.object({items:z136.array(sessionEnvelopeSchema),nextCursor:z136.string().nullable()}),buildRequest:__name(({projectId:projectId2,status,cursor:cursor3,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/sessions"),{status,cursor:cursor3,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z136.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId:projectId2,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z136.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z136.object({requested:z136.literal(!0),alreadyRequested:z136.boolean(),reviewId:uuidSchema,reviewUrl:z136.url(),status:z136.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z136.string().min(1),savedRevision:z136.string().min(1),fingerprint:z136.string().min(1),visibility:z136.literal("user-visible"),retention:z136.literal("durable"),expiresAt:z136.null(),merged:z136.literal(!1),published:z136.literal(!1),links:z136.object({preview:z136.url(),changes:z136.url(),conversation:z136.url().nullable()})}),buildRequest:__name(({projectId:projectId2,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z136.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z136.literal("temporary"),visibility:z136.enum(["internal","user-visible"]),expiresAt:z136.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z136.string().min(1).max(100),args:z136.record(z136.string(),z136.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId:projectId2,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,action:z136.enum(["merge","discard"]),message:z136.string().max(1e3).optional(),description:z136.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z136.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z136.boolean(),mergeId:uuidSchema.optional(),conflictCount:z136.number().int().nonnegative().optional(),conflicts:z136.array(sessionConflictSummarySchema).optional(),parentAdvanced:z136.boolean().optional(),code:z136.string().optional(),summary:z136.string().nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z136.number().int().min(1).max(100).optional(),codePath:z136.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z136.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z136.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z136.number().int().nonnegative(),error:z136.string().nullable()}),conflicts:z136.array(conflictSchema2).max(100),nextCursor:z136.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,cursor:cursor3,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor:cursor3,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z136.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z136.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z136.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z137}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z137.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z138}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z138.object({message:z138.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z138.object({id:uuidSchema,deliveryStatus:z138.enum(["pending","delivered","failed"]),message:z138.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z138.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId:projectId2,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId:projectId2,branch})}),"buildRequest")}}}});import{z as z139}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z139.record(z139.string(),z139.unknown()),deliveryStatusSchema=z139.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z139.object({id:uuidSchema,projectId:uuidSchema,name:z139.string(),eventType:z139.string().min(1),enabled:z139.boolean(),destination:z139.object({host:z139.string(),maskedUrl:z139.string(),kind:z139.string()}),filter:jsonObjectSchema,headers:z139.array(jsonObjectSchema),bodyTemplate:z139.unknown().nullable(),signingEnabled:z139.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z139.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z139.string().min(1),status:deliveryStatusSchema,attemptCount:z139.number().int().nonnegative(),responseStatus:z139.number().int().nullable(),createdAt:z139.iso.datetime()}).passthrough(),attemptSchema=z139.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z139.number().int().positive(),status:z139.enum(["delivering","succeeded","failed"]),createdAt:z139.iso.datetime()}).passthrough(),deliveriesPageSchema=z139.object({items:z139.array(deliverySchema),pagination:z139.object({page:z139.number().int().positive(),limit:z139.number().int().positive(),total:z139.number().int().nonnegative(),totalPages:z139.number().int().positive(),hasMore:z139.boolean()}),stats:z139.object({total:z139.number().int().nonnegative(),succeeded:z139.number().int().nonnegative(),failed:z139.number().int().nonnegative()})}),eventSchema=z139.object({type:z139.string().min(1),family:z139.string(),description:z139.string(),variables:z139.array(z139.string()),data:z139.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z139.object({projectId:uuidSchema}).strict(),outputSchema:z139.array(eventSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z139.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z139.object({projectId:uuidSchema}).strict(),outputSchema:z139.array(webhookSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z139.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z139.object({webhook:webhookSchema,signingSecret:z139.string().min(1)}),buildRequest:__name(({projectId:projectId2,webhook})=>({method:"POST",path:managementProjectPath(projectId2,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z139.object({webhook:webhookSchema,signingSecret:z139.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z139.unknown(),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z139.string().min(1),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z139.object({signingSecret:z139.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z139.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z139.string().nullable()}),buildRequest:__name(({projectId:projectId2,webhookId,page:page2,cursor:cursor3,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page:page2,cursor:cursor3}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z139.object({delivery:deliverySchema,attempts:z139.array(attemptSchema)}),buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z139.object({delivery:deliverySchema,attempts:z139.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z139.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z140}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_integrations();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...integrationsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z140.object({id:z140.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z140.string().min(1),summary:z140.string().min(1),accessScope:z140.enum(["read","write","code","agents"]),effect:z140.enum(["read","mutation"]),inputJsonSchema:z140.record(z140.string(),z140.unknown()),outputJsonSchema:z140.record(z140.string(),z140.unknown())}).strict(),fimoOperationManifestSchema=z140.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z140.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z140.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.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:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.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 root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.join(root,"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=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.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 path4 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=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}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,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue2=>{let{path:path52,message}=issue2;return`${Array.isArray(path52)&&path52.length>0?`${path52.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatFieldErrors(parsed){if(!Array.isArray(parsed.errors))return null;let fields=parsed.errors.flatMap(error=>{if(!error||typeof error!="object")return[];let{path:path52,message}=error;return typeof message!="string"||!message?[]:[typeof path52=="string"&&path52?`${path52}: ${message}`:message]});return fields.length>0?fields.join("; "):null}function formatError(status,text2,body){if(!text2)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let fields=formatFieldErrors(parsed),message=fields?`${parsed.message}: ${fields}`:parsed.message,partial=formatPartialResult(parsed);return partial?`${message} ${partial}`: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 text2}async function parseError(response){let text2=await response.text(),body;try{body=text2?JSON.parse(text2):void 0}catch{return{detail:formatError(response.status,text2)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text2,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message),server.body=body}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,this.status=status,this.detail=detail,this.code=code2,this.body=body}},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}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;body;constructor(apiUrl,required=[],message,server={}){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,this.code=server.code,this.detail=server.detail,this.body=server.body}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatFieldErrors,"formatFieldErrors");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});function recoverTenantApiBaseUrl(tenantApiUrl,projectId2,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId2}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId2,branch,base)===normalized?base:void 0}catch{return}}function createIdentityService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{getCurrentSession(){return transport.request("/api/auth/get-session")}}}function createGitService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getRemote(projectId2,branch){let body=await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-remote`,{},{preserveForbidden:!0});if(!body.data.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(body.data.tenantApiUrl,projectId2,branch);if(recovered)return{...body.data,tenantApiBaseUrl:recovered}}return body.data},async getCredential(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-credential`,{},{preserveForbidden:!0})).data}}}function createPublicationControlService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return{async publish(projectId2,request={}){return(await transport.request(`/api/management/projects/${projectId2}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null},async unpublish(projectId2){await transport.request(`/api/management/projects/${projectId2}/unpublish`,{method:"POST"})}}}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 transferBlockersFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return[];let blockers=body.blockers;return Array.isArray(blockers)?blockers:[]}function createSandboxService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getHostedPreview(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeBranchPathSegment(branch)}/hosted-preview`)).data},async pull(projectId2,onProgress,branch,options={}){let params=new URLSearchParams;options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),response=await transport.response(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/sandbox/pull${search?`?${search}`:""}`,{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="",failure=null,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(`
49
+ `)}function resolveAuth(cfg=loadConfig()){return explicitAuth(cfg)??projectTokenFileAuth(cfg)??sessionAuth(cfg)}function resolveAccountAuth(cfg=loadConfig()){return explicitAuth(cfg)??sessionAuth(cfg)}function explicitAuth(cfg){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();return bearer?bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer}:null}function projectTokenFileAuth(cfg){let tokenFile=findProjectToken(cfg);return tokenFile?{kind:"project",token:tokenFile.file.token,tokenFile}:null}function sessionAuth(cfg){let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,LOCAL_CREDENTIALS_RULE,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),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}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");LOCAL_CREDENTIALS_RULE="*.local.json";__name(ignoreLocalCredentials,"ignoreLocalCredentials");__name(resolveAuth,"resolveAuth");__name(resolveAccountAuth,"resolveAccountAuth");__name(explicitAuth,"explicitAuth");__name(projectTokenFileAuth,"projectTokenFileAuth");__name(sessionAuth,"sessionAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});import{z as z114}from"zod";function createResponseSchema2(dataSchema){return z114.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId2,suffix){return`/management/projects/${encodeURIComponent(projectId2)}${suffix}`}function managementBranchPath(projectId2,branch,suffix){return managementProjectPath(projectId2,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId2,branch,suffix){return`/tenant/${encodeURIComponent(projectId2)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&&params.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z114.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor3){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor3))throw new Error("Invalid pagination cursor.");let base64=cursor3.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z114.object({items:z114.array(itemSchema),nextCursor:z114.string().nullable(),total:z114.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId2,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId2,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z114.uuid(),sessionStatusSchema=z114.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z114.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z114.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z114.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z114.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z114.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z114.string().nullable().optional(),goal:z114.string().nullable().optional(),provenance:z114.object({source:z114.enum(["studio","slack","mcp"]),creator:z114.object({kind:z114.enum(["user","slack","agent","oauth","conversation"]),id:z114.string()}),conversationId:z114.string().nullable(),runId:z114.string().nullable()}).nullable().optional(),createdBy:z114.string().optional(),createdAt:z114.iso.datetime().optional(),savedRevision:z114.string().nullable().optional(),targetBranch:z114.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z114.string().min(1)}),workingBranch:z114.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z114.url().nullable(),lastActivityAt:z114.iso.datetime(),expiresAt:z114.iso.datetime().nullable(),retention:z114.enum(["temporary","durable"]).optional(),visibility:z114.enum(["internal","user-visible"]).optional(),onExpire:z114.enum(["discard","keep"]),nextOperations:z114.array(z114.string())}),paginationShape={limit:z114.number().int().min(1).max(100).optional(),cursor:z114.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z114.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z114.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor3=>cursor3==null||/^[1-9]\d*$/.test(cursor3)&&Number.isSafeInteger(Number(cursor3)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z114.object({data:z114.array(z114.unknown()),meta:z114.object({limit:z114.number().int().positive(),offset:z114.number().int().nonnegative(),total:z114.number().int().nonnegative(),hasMore:z114.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z115}from"zod";var agent,chats,routines,routineRun,routineRuns,routineRunLedger,projectChats,chatAuthor,liveTurn,chatMessages,chatSearch,isoTime,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z115.object({id:uuidSchema,kind:z115.string(),title:z115.string().nullable(),description:z115.string().nullable()}),chats=z115.object({chats:z115.array(agent)}),routines=z115.object({routines:z115.array(z115.object({id:uuidSchema,name:z115.string(),instructions:z115.string(),paused:z115.boolean(),triggers:z115.object({schedule:z115.object({cron:z115.string(),timezone:z115.string()}).nullable(),event:z115.object({text:z115.string()}).nullable()}),nextRunAt:z115.string().nullable(),lastRunAt:z115.string().nullable(),lastOutcome:z115.string().nullable(),outOfAgentHoursUntil:z115.string().nullable()}))}),routineRun=z115.object({startedAt:z115.string(),trigger:z115.enum(["schedule","hand","event"]),startedBy:z115.object({kind:z115.enum(["person","agent"]),name:z115.string().nullable()}).nullable(),status:z115.enum(["queued","running","finished","failed","cancelled"]),outcome:z115.string().nullable(),summary:z115.string().nullable(),durationMs:z115.number().nullable(),credits:z115.number().nullable()}),routineRuns=z115.object({runs:z115.array(routineRun)}),routineRunLedger=z115.object({runs:z115.array(routineRun.extend({messageId:uuidSchema}))}),projectChats=z115.object({chats:z115.array(agent.extend({createdAt:z115.string(),lastMessageAt:z115.string().nullable(),running:z115.boolean(),awaitingAnswer:z115.boolean()}))}),chatAuthor=z115.object({kind:z115.enum(["person","agent","routine","system"]),id:z115.string().nullable()}),liveTurn=z115.object({invocationId:z115.string(),step:z115.string(),startedAt:z115.string()}).nullable().default(null),chatMessages=z115.object({threadId:z115.string().nullable(),title:z115.string().nullable(),messages:z115.array(z115.object({id:uuidSchema,role:z115.enum(["user","assistant"]),parts:z115.array(z115.unknown()),metadata:z115.record(z115.string(),z115.unknown()).nullable(),createdAt:z115.string(),author:chatAuthor,invocationId:z115.string().nullable().optional(),invocationStatus:z115.string().nullable().optional(),invocationTerminalReason:z115.string().nullable().optional()})),nextCursor:z115.string().nullable(),liveTurn,queue:z115.array(z115.object({id:uuidSchema,author:chatAuthor,failed:z115.boolean(),queuedAt:z115.string()})).default([]),queuePaused:z115.boolean().default(!1),queueWaitUntil:z115.string().nullable().default(null)}),chatSearch=z115.object({hits:z115.array(z115.object({chatId:uuidSchema,chatTitle:z115.string().nullable(),messageId:uuidSchema,role:z115.string(),authorKind:chatAuthor.shape.kind,createdAt:z115.string(),snippet:z115.string()}))}),isoTime=z115.iso.datetime({offset:!0}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId:projectId2,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId:projectId2})}),"buildRequest")},"agents.routineRuns":{domain:"agents",summary:"Read a routine\u2019s newest runs: when each started, what started it and how it ended.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRuns,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")},"agents.chats":{domain:"agents",summary:"Read every chat of the project, agents and regular chats, newest activity first.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:projectChats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest")},"agents.messages":{domain:"agents",summary:"Read a page of a chat, newest first, with whether a turn runs and what waits in its queue.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,cursor:z115.string().min(1).optional(),limit:z115.number().int().min(1).max(200).optional()}).strict(),outputSchema:chatMessages,buildRequest:__name(({projectId:projectId2,branch,threadId,cursor:cursor3,limit})=>({method:"GET",context:{branch},path:addQuery("/chat/project/messages",{projectId:projectId2,threadId,cursor:cursor3,limit})}),"buildRequest")},"agents.search":{domain:"agents",summary:"Search the words of the project\u2019s chats, best match first, with the ids to read around each hit.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,query:z115.string().trim().min(1).max(500),chatId:uuidSchema.optional(),after:isoTime.optional(),before:isoTime.optional(),limit:z115.number().int().min(1).max(50).optional()}).strict(),outputSchema:chatSearch,buildRequest:__name(({projectId:projectId2,branch,...query})=>({method:"GET",context:{branch},path:addQuery("/chat/project/search",{projectId:projectId2,...query})}),"buildRequest")},"agents.createChat":{domain:"agents",summary:"Open a new regular chat; it is listed once its first message is sent.",accessScope:"agents",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,title:z115.string().trim().min(1).max(120).optional()}).strict(),outputSchema:z115.object({id:uuidSchema}),buildRequest:__name(({projectId:projectId2,branch,id,title})=>({method:"POST",context:{branch},path:"/chat/project/threads",body:{projectId:projectId2,id,kind:"chat",...title?{title}:{}}}),"buildRequest")},"agents.runRoutine":{domain:"agents",summary:"Start a routine now, with an optional message for its run.",accessScope:"agents",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema,message:z115.string().trim().min(1).max(2e4).optional()}).strict(),outputSchema:z115.object({kind:z115.enum(["published","queued","replay","streaming","busy","refused"]),messageId:uuidSchema.nullable()}),buildRequest:__name(({projectId:projectId2,branch,threadId,routineId,message})=>({method:"POST",context:{branch},path:`/chat/project/threads/${threadId}/routines/${routineId}/run`,body:{projectId:projectId2,...message?{message}:{}}}),"buildRequest")},"agents.routineRunLedger":{domain:"agents",summary:"Read a routine\u2019s newest runs with the message that started each and the credits it spent.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRunLedger,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")}}}});import{z as z116}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z116.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z116.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z116.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z116.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z116.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z116.union([z116.literal(7),z116.literal(30),z116.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z116.object({date:z116.string(),content:z116.string(),updatedAt:z116.string(),updatedByUserId:z116.string()}),analyticsBreakdownSchema=z116.object({key:z116.string(),visitors:z116.number().int().nonnegative(),pageviews:z116.number().int().nonnegative()}),analyticsPageBreakdownSchema=z116.object({path:z116.string(),pageName:z116.string().nullable().optional(),visitors:z116.number().int().nonnegative(),pageviews:z116.number().int().nonnegative()}),analyticsPageviewsSchema=z116.object({range:z116.object({preset:analyticsPresetSchema,requestedFrom:z116.string(),requestedTo:z116.string(),effectiveFrom:z116.string(),effectiveTo:z116.string(),isRetentionLimited:z116.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z116.number().int().nonnegative(),pageviews:z116.number().int().nonnegative(),botPageviews:z116.number().int().nonnegative().default(0),botVisitors:z116.number().int().nonnegative().default(0),bounceRate:z116.number().min(0).max(100),viewsPerVisit:z116.number().nonnegative(),averageVisitDurationSeconds:z116.number().nonnegative(),visitorsSeries:z116.array(z116.object({date:z116.string(),visitors:z116.number().int().nonnegative()})),topPages:z116.array(analyticsPageBreakdownSchema),topBrowsers:z116.array(analyticsBreakdownSchema),topDevices:z116.array(analyticsBreakdownSchema),topBots:z116.array(analyticsBreakdownSchema).default([]),topAiAssistants:z116.array(analyticsBreakdownSchema).default([]),topCountries:z116.array(analyticsBreakdownSchema),topSources:z116.array(analyticsBreakdownSchema),annotations:z116.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z116.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z116.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z116.array(z116.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z116.object({branch:branchNameSchema,annotations:z116.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z116.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,date:z116.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z116.string().max(500)}).strict(),outputSchema:z116.union([analyticsAnnotationResponseSchema,z116.null()]),buildRequest:__name(({projectId:projectId2,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,date:z116.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z116.null(),buildRequest:__name(({projectId:projectId2,branch,date})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z117}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z117.object({id:z117.string(),name:z117.string()}),AssetDTOSchema2=z117.object({id:z117.string(),name:z117.string(),type:z117.enum(["file","folder"]),originalFileName:z117.string().nullable(),parentId:z117.string().nullable(),mimeType:z117.string().nullable(),fileSize:z117.number().nullable(),url:z117.string().nullable(),storageKey:z117.string().nullable(),slug:z117.string(),tags:z117.array(z117.string()).nullable().optional(),createdAt:z117.string().nullable(),updatedAt:z117.string().nullable(),altText:z117.string().nullable().optional(),caption:z117.string().nullable().optional(),aiCaption:z117.string().nullable().optional(),aiAltText:z117.string().nullable().optional(),aiTags:z117.array(z117.string()).nullable().optional(),aiPrimaryColor:z117.string().nullable().optional(),aiProcessingStatus:z117.string().nullable().optional(),width:z117.number().nullable().optional(),height:z117.number().nullable().optional(),path:z117.array(assetPathItemSchema).optional(),hasChildren:z117.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z117.object({cursor:z117.string().nullable().optional(),query:z117.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z117.object({url:z117.url(),mediaType:z117.string(),filename:z117.string()}),assetReadBaseSchema=z117.object({assetId:z117.uuid(),filename:z117.string(),mediaType:z117.string(),representation:z117.enum(["text","table","document","archive","image","transcript","video","model"]),content:z117.string(),derivedFiles:z117.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z117.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z117.literal("page"),start:z117.number().int().nonnegative(),end:z117.number().int().nonnegative(),total:z117.number().int().nonnegative(),nextCursor:z117.string().nullable(),complete:z117.boolean()}),assetReadBaseSchema.extend({mode:z117.literal("query"),query:z117.string(),source:z117.enum(["original-file","canonical-text","derived-files"]),truncated:z117.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z117.object({jobId:z117.string(),status:z117.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z117.string().nullable().optional(),credits:z117.number().optional(),costUsd:z117.number().optional(),billingMode:z117.enum(["fimo-credits","provider-account"]).optional(),task:z117.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z117.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z117.object({data:z117.object({message:z117.literal("success")})}),assetGenerationInputSchema=z117.object({projectId:uuidSchema,branch:branchNameSchema,task:z117.string().min(1).optional(),model:z117.string().min(1).optional(),options:z117.record(z117.string(),z117.unknown()),name:z117.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z117.string().max(2e3).optional(),caption:z117.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z117.object({projectId:uuidSchema,sessionId:uuidSchema,url:z117.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z117.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z117.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z117.string().max(1024).refine(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z117.string().max(2e3).optional(),caption:z117.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z117.string().max(200).optional(),type:z117.enum(["file","folder"]).optional(),mimePrefix:z117.string().max(50).optional(),sortBy:z117.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z117.enum(["asc","desc"]).optional(),includePath:z117.boolean().optional(),excludeHidden:z117.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId:projectId2,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId:projectId2,branch,id,cursor:cursor3,query})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor3??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId:projectId2,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,name:z117.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z117.record(z117.string(),z117.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z117.object({data:z117.record(z117.string(),z117.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z117.record(z117.string(),z117.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z117.object({data:z117.record(z117.string(),z117.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z117.unknown(),buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z117.object({data:z117.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z117.record(z117.string(),z117.unknown()),buildRequest:__name(({projectId:projectId2,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z117.object({data:z117.record(z117.string(),z117.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z118}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z118.object({projectId:uuidSchema,organizationId:z118.string(),balance:z118.object({totalAvailable:z118.number(),nearLimit:z118.boolean(),canUseAi:z118.boolean(),buckets:z118.object({dailyFreeAvailable:z118.number(),monthlyAvailable:z118.number(),purchasedAvailable:z118.number(),awardedAvailable:z118.number()})}),allowances:z118.object({dailyCredits:z118.object({periodCap:z118.number(),dailyGrant:z118.number(),usedThisPeriod:z118.number(),remainingThisPeriod:z118.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z119}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z119.object({ok:z119.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z119.array(z119.object({surface:backendSurfaceSchema,count:z119.number().int().nonnegative()})),conflicts:z119.array(backendConflictSchema).optional(),summary:z119.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z119.object({mergeId:uuidSchema,conflicts:z119.array(backendConflictSchema),draftResolutions:z119.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z119.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z119.object({data:z119.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z119.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z119.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z119.array(backendSurfaceDeltaSchema).max(6),crossSurface:z119.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z119.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z119.string().min(1),surfaces:z119.array(backendSurfaceDeltaSchema).max(6),crossSurface:z119.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z119.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z119.enum(["provisioning","active","deleted"]),kind:z119.enum(["user","agent-session"]),createdAt:z119.string().optional(),updatedAt:z119.string().optional(),createdBy:z119.string().nullable().optional(),deletedAt:z119.string().nullable().optional()}).passthrough(),branchResponseSchema=z119.object({data:branchSchema}),branchSurfaceStatusSchema=z119.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z119.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z119.iso.datetime(),backendCrossSurfaceFindingSchema=z119.object({id:z119.string(),kind:z119.string(),description:z119.string(),severity:z119.enum(["warning","error"]),source:z119.object({surface:backendSurfaceSchema,key:z119.string()}),target:z119.object({surface:backendSurfaceSchema,key:z119.string()}),actions:z119.array(z119.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z119.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z119.number().int().nonnegative(),conflictCount:z119.number().int().nonnegative(),items:z119.array(z119.object({verb:branchDeltaVerbSchema,key:z119.string(),detail:z119.string().optional(),origin:z119.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z119.record(z119.string(),z119.unknown()).optional()})).max(1e3).optional(),truncated:z119.boolean().optional(),error:z119.string().optional()}),branchSurfaceSummarySchema=z119.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z119.number().int().nonnegative(),conflictCount:z119.number().int().nonnegative(),error:z119.string().optional(),items:z119.array(z119.object({verb:branchDeltaVerbSchema,key:z119.string(),detail:z119.string().optional(),origin:z119.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z119.record(z119.string(),z119.unknown()).optional()})).optional(),truncated:z119.boolean().optional()}),branchStatusOutputSchema=z119.object({branch:branchNameSchema,against:branchNameSchema,state:z119.enum(["clean","changed"]),syncState:z119.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z119.array(branchSurfaceSummarySchema).max(6),crossSurface:z119.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z119.object({verb:branchDeltaVerbSchema,key:z119.string(),detail:z119.string().optional(),meta:z119.record(z119.string(),z119.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z119.string().min(1),surfaces:z119.array(branchSurfaceSummarySchema.extend({truncated:z119.boolean(),items:z119.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z119.object({path:z119.string(),state:z119.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z119.string(),additions:z119.number().int().nonnegative(),deletions:z119.number().int().nonnegative()}),contentSnapshotSchema=z119.object({id:z119.string(),slug:z119.string(),contentType:z119.string(),data:z119.record(z119.string(),z119.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z119.object({collection:z119.string(),rowId:z119.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z119.object({name:z119.string(),label:z119.string(),isSingleton:z119.boolean(),description:z119.string().nullable().default(null),fields:z119.record(z119.string(),z119.unknown())}),schemaDiffOutputSchema=z119.object({typeName:z119.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z119.object({id:z119.string(),name:z119.string(),type:z119.enum(["file","folder"]),mimeType:z119.string().nullable(),storageKey:z119.string().nullable(),url:z119.string().nullable(),fileSize:z119.number().nullable(),width:z119.number().nullable(),height:z119.number().nullable(),altText:z119.string().nullable(),caption:z119.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z119.object({assetId:z119.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z119.object({locale:z119.string(),key:z119.string(),parent:z119.string().nullable(),child:z119.string().nullable()}),formSnapshotSchema=z119.object({formName:z119.string(),label:z119.string().nullable(),schemaFingerprint:z119.string(),fields:z119.record(z119.string(),z119.unknown())}),formDiffOutputSchema=z119.object({formName:z119.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z119.object({surface:backendSurfaceSchema,key:z119.string(),kind:z119.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z119.string(),parentValue:z119.unknown().optional(),childValue:z119.unknown().optional(),conflictingFields:z119.array(z119.string()).optional(),code:z119.object({path:z119.string(),unresolvable:z119.boolean().optional(),reason:z119.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z119.object({field:z119.string(),choice:z119.enum(["parent","child","pick","ai-pick"]),pickedValue:z119.unknown().optional(),aiSessionId:z119.string().optional()}),conflictResolutionSchema=z119.object({surface:branchSurfaceSchema,key:z119.string(),choice:z119.enum(["parent","child","pick"]),pickedValue:z119.unknown().optional(),fieldPicks:z119.array(fieldPickSchema).optional()}),mergeResultSchema=z119.object({ok:z119.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z119.array(z119.object({surface:branchSurfaceSchema,count:z119.number().int().nonnegative()})),conflicts:z119.array(conflictSchema).optional(),summary:z119.string().optional()}),resolvedMergeStrategySchema=z119.object({engine:z119.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z119.enum(["ff_only","ff_prefer","merge"]),squash:z119.boolean()}),mergeAcceptedSchema=z119.object({mergeId:uuidSchema,streamUrl:z119.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z119.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z119.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z119.string().nullable(),error:z119.string().nullable()}),mergeHydrationSchema=z119.object({mergeId:uuidSchema,conflicts:z119.array(conflictSchema),draftResolutions:z119.array(conflictResolutionSchema),status:z119.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z119.object({content:z119.string(),sha:z119.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z119.object({path:z119.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,includeDeleted:z119.boolean().optional(),includeAgentBranches:z119.boolean().optional()}).strict(),outputSchema:z119.object({data:z119.array(branchSchema)}),buildRequest:__name(({projectId:projectId2,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId:projectId2,from,name})=>({method:"POST",path:managementProjectPath(projectId2,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z119.object({branch:branchSchema,conflicts:z119.number().int().nonnegative()}),buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z119.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z119.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z119.unknown(),buildRequest:__name(({projectId:projectId2,branch})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z119.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z119.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,path:z119.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,path:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff/code/file"),{path:path52,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,collection:z119.string().min(1),rowId:z119.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z119.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z119.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,locale:z119.string().min(1),key:z119.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,formName:z119.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z119.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId:projectId2,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z119.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId:projectId2,mergeId})=>({method:"GET",path:managementProjectPath(projectId2,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z119.object({ok:z119.boolean()}),buildRequest:__name(({projectId:projectId2,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z119.object({ok:z119.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"GET",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z119.array(conflictResolutionSchema)}).strict(),outputSchema:z119.object({mergeId:uuidSchema,lastEditedAt:z119.string()}),buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z119.object({mergeId:uuidSchema,lastEditedAt:z119.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z119.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId:projectId2,branch,from,path:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z120}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z120.object({id:z120.string(),hostname:z120.string(),status:z120.string(),ssl:z120.record(z120.string(),z120.unknown()),cnameTarget:z120.string(),apexTargets:z120.array(z120.string()),dnsAutoConfigured:z120.boolean(),createdAt:z120.unknown(),provider:z120.enum(["cloudflare","saas_custom_domains"]),domainType:z120.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z120.object({id:uuidSchema,domain:z120.string(),status:z120.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z120.enum(["fimo","external"]),autoRenew:z120.boolean(),paymentStatus:z120.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z120.string().nullable()}).passthrough(),domainSearchResultSchema=z120.object({domain:z120.string(),available:z120.boolean(),premium:z120.boolean(),price:z120.number().nullable(),renewalPrice:z120.number().nullable(),purchaseType:z120.string().nullable()}).passthrough(),domainPricingSchema=z120.object({domain:z120.string(),price:z120.number().nullable(),renewalPrice:z120.number().nullable(),premium:z120.boolean(),allowedYears:z120.array(z120.number().int().positive())}).passthrough(),projectPath=__name((projectId2,suffix)=>`/management/projects/${encodeURIComponent(projectId2)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z120.object({}).strict(),outputSchema:z120.object({domainPurchaseEnabled:z120.boolean(),publicationDomain:z120.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,slug:z120.string().min(1).max(63)}).strict(),outputSchema:z120.object({subdomain:z120.string(),subdomainUpdatedAt:z120.string()}),buildRequest:__name(({projectId:projectId2,slug})=>({method:"PATCH",path:projectPath(projectId2,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,base:z120.string().min(1).max(63).optional(),max:z120.number().int().positive().optional()}).strict(),outputSchema:z120.array(z120.string()),buildRequest:__name(({projectId:projectId2,base,max})=>({method:"GET",path:addQuery(projectPath(projectId2,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z120.object({data:z120.object({suggestions:z120.array(z120.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema}).strict(),outputSchema:z120.array(projectDomainSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:projectPath(projectId2,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,hostname:z120.string().min(1).max(255),redirectToWww:z120.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId2,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,domainId:z120.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.setPrimary":{domain:"domains",summary:"Make a serving custom domain the primary domain of a site.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,domainId:z120.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/primary`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.setRedirect":{domain:"domains",summary:"Redirect a custom domain to another domain of the same site with 301, 302, 307 or 308 (default 307), or change an existing redirect. Redirecting the primary domain moves the primary: tell the user to publish again so canonical links use the new one.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,domainId:uuidSchema,targetDomainId:uuidSchema,status:z120.union([z120.literal(301),z120.literal(302),z120.literal(307),z120.literal(308)]).optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId,targetDomainId,status})=>({method:"PUT",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/redirect`),body:{targetDomainId,status},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.serve":{domain:"domains",summary:"Make a custom domain serve the site instead of redirecting. If it becomes the primary domain, tell the user to publish again so canonical links use it.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,domainId:uuidSchema}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}/redirect`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site, together with every domain that redirects to it.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,domainId:z120.string().min(1)}).strict(),outputSchema:z120.object({success:z120.boolean(),hostname:z120.string(),removed:z120.array(z120.object({id:z120.string(),hostname:z120.string()})).optional()}),buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z120.object({keyword:z120.string().min(1).max(100),tldFilter:z120.array(z120.string().min(1)).optional()}).strict(),outputSchema:z120.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z120.object({domain:z120.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z120.object({organizationId:z120.string().min(1)}).strict(),outputSchema:z120.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z120.object({organizationId:z120.string().min(1),domain:z120.string().min(1).max(255),years:z120.number().int().min(1).max(10).optional(),autoRenew:z120.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z120.object({organizationId:z120.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z121}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z121.object({id:z121.string(),entryId:z121.string(),documentId:z121.string(),slug:z121.string(),locale:z121.string().optional(),createdAt:z121.string(),updatedAt:z121.string(),__fimo:z121.object({contentType:z121.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z121.object({data:z121.array(EntryDTOSchema2),meta:z121.object({limit:z121.number(),offset:z121.number(),total:z121.number(),hasMore:z121.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z121.union([z121.string(),z121.number(),z121.boolean(),z121.null()]),entryWhereOperatorSchema2=z121.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z121.array(entryWhereScalarSchema2).optional(),$nin:z121.array(entryWhereScalarSchema2).optional(),$contains:z121.string().optional(),$startsWith:z121.string().optional(),$null:z121.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z121.record(z121.string(),z121.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z121.record(z121.string(),z121.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z121.object({data:z121.record(z121.string(),z121.unknown()),locale:z121.string().min(1).optional(),documentId:z121.uuid().optional()}),BulkCreateEntriesResponseSchema2=z121.object({data:z121.array(EntryDTOSchema2),meta:z121.object({created:z121.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z121.object({data:z121.array(EntryDTOSchema2),meta:z121.object({updated:z121.number().int().nonnegative(),missing:z121.array(z121.string())})}),BulkDeleteEntriesResponseSchema2=z121.object({data:z121.array(EntryDTOSchema2),meta:z121.object({deleted:z121.number().int().nonnegative(),missing:z121.array(z121.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z121.string().min(1).max(255),localeSchema=z121.string().min(1),populateSchema=z121.array(z121.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z121.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,search:z121.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,search,locale,limit,cursor:cursor3,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor:cursor3,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255),data:entryDataSchema,locale:z121.string().min(1).optional(),documentId:z121.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z121.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z121.record(z121.string(),z121.unknown())}).strict(),outputSchema:z121.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z121.object({data:z121.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,sql:z121.string().min(1)}).strict(),outputSchema:z121.object({data:z121.array(z121.record(z121.string(),z121.unknown())),meta:z121.object({rowCount:z121.number().int().nonnegative(),truncated:z121.boolean()})}),buildRequest:__name(({projectId:projectId2,branch,sql})=>({method:"POST",path:tenantPath(projectId2,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z121.array(z121.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z121.union([z121.object({ids:z121.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z121.object({where:EntryWhereSchema2}),z121.object({updates:z121.array(z121.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z121.union([z121.object({ids:z121.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z121.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z122}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z122.object({id:z122.literal("production"),projectId:uuidSchema,name:z122.string(),kind:z122.literal("production"),sourceBranch:z122.string().min(1),isPublished:z122.boolean(),url:z122.string().nullable()}),previewEnvironmentSchema=z122.object({id:z122.literal("preview"),projectId:uuidSchema,name:z122.string(),kind:z122.literal("preview"),matchedBranchCount:z122.number().int().nonnegative()}),customEnvironmentSchema=z122.object({id:uuidSchema,projectId:uuidSchema,name:z122.string().min(1).max(64),branchPatterns:z122.array(z122.string().min(1).max(255)).min(1),description:z122.string().max(255).nullable(),kind:z122.literal("custom"),matchedBranchCount:z122.number().int().nonnegative()}),environmentSchema=z122.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z122.string().trim().min(1).max(64),branchPatterns:z122.array(z122.string().min(1).max(255)).min(1),description:z122.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema}).strict(),outputSchema:z122.array(environmentSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/environments")}),"buildRequest"),projectOutput:__name(body=>z122.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,environmentId:z122.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,environmentId:z122.string().min(1)}).strict(),outputSchema:z122.object({deletedId:uuidSchema}),buildRequest:__name(({projectId:projectId2,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z122.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z123}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z123.object({data:z123.object({path:z123.string(),content:z123.string(),totalLines:z123.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z123.object({data:z123.object({paths:z123.array(z123.string().min(1)).max(2e3),truncated:z123.boolean()})}),fileGrepOutputSchema=z123.object({data:z123.object({matches:z123.array(z123.object({path:z123.string().min(1),line:z123.number().int().positive(),text:z123.string()})).max(200),truncated:z123.boolean()})}),fileWriteInputSchema=z123.object({projectId:uuidSchema,sessionId:uuidSchema,path:z123.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z123.boolean().optional()}).strict(),fileEditInputSchema=z123.object({projectId:uuidSchema,sessionId:uuidSchema,path:z123.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z123.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z123.object({path:z123.string(),created:z123.boolean(),tip:z123.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z123.object({projectId:uuidSchema,sessionId:uuidSchema,files:z123.array(z123.object({path:z123.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files2=>files2.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z123.array(z123.object({path:z123.string(),created:z123.boolean()}).passthrough()),tip:z123.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z123.object({path:z123.string(),replacements:z123.number().int().nonnegative(),tip:z123.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z123.object({path:z123.string(),deleted:z123.literal(!0),tip:z123.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z123.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z123.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,path:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z123.object({...fileSearchInputShape,pattern:z123.string().min(1).max(300).optional(),limit:z123.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z123.object({...fileSearchInputShape,pattern:z123.string().min(1).max(200),include:z123.string().min(1).max(300).optional(),caseInsensitive:z123.boolean().optional(),maxMatches:z123.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,path:z123.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"buildRequest")}}}});import{z as z124}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z124.object({data:z124.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page2=z124.object({data:z124.array(formSubmissionSchema),total:z124.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page2.data.length===0&&offset<page2.total)throw new Error("Expected a page that advances the cursor.");return{items:page2.data,nextCursor:offset+page2.data.length<page2.total?encodePaginationCursor(offset+page2.data.length):null,total:page2.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z124.object({type:z124.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z124.string(),placeholder:z124.string().optional(),required:z124.boolean().optional(),defaultValue:z124.string().optional(),options:z124.array(z124.string()).optional(),validation:z124.object({minLength:z124.number().optional(),maxLength:z124.number().optional(),min:z124.number().optional(),max:z124.number().optional(),pattern:z124.string().optional(),maxFileSize:z124.number().optional(),accept:z124.array(z124.string()).optional()}).optional()}),FormContentSchema2=z124.object({name:z124.string().min(1).max(255),label:z124.string().min(1).max(255),fields:z124.record(z124.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z124.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z124.record(z124.string(),z124.unknown()).nullable().optional(),createdAt:z124.string(),updatedAt:z124.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z124.object({data:formSchema}),formSubmissionSchema=z124.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z124.record(z124.string(),z124.unknown()),submittedAt:z124.string()}),formSubmissionResponseSchema=z124.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z124.object({data:z124.object({total:z124.number().int().nonnegative(),dailyCounts:z124.array(z124.object({date:z124.string(),count:z124.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z124.array(formSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId2,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255),...paginationShape,searchQuery:z124.string().max(200).optional(),sortDirection:z124.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId:projectId2,branch,id,limit,cursor:cursor3,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor:cursor3,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255),submissionId:z124.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,id:z124.string().min(1).max(255),submissionId:z124.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z125}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z125.object({costUsd:z125.number(),credits:z125.number().optional(),billingMode:z125.enum(["fimo-credits","provider-account"]).optional(),confidence:z125.enum(["exact","estimated","metered"]),basis:z125.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z125.object({projectId:uuidSchema,model:z125.string().min(1),options:z125.record(z125.string(),z125.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId2)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z125.object({projectId:uuidSchema,branch:branchNameSchema,task:z125.string().min(1),options:z125.record(z125.string(),z125.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,branch,task,options})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z126}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z126.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z126.object({versionId:uuidSchema,commitHash:z126.string(),name:z126.string(),description:z126.string().nullable(),kind:historyKindSchema,createdAt:z126.iso.datetime(),expiresAt:z126.iso.datetime()}),projectVersionPageSchema=z126.object({items:z126.array(projectVersionSchema),nextCursor:z126.string().nullable()}),historySummarySchema=z126.object({usage:z126.object({versionCount:z126.number().int().nonnegative(),snapshotBytes:z126.number().int().nonnegative()}),retentionDays:z126.number().int().positive()}),restoreResultSchema=z126.object({durationMs:z126.number().nonnegative().optional(),warning:z126.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema,limit:z126.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/versions"),{limit,cursor:cursor3})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema,name:z126.string().min(1),description:z126.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page2=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page2.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page2.items.map(publicationRecord),nextCursor:page2.nextCursor,retention:page2.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z127.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z127.object({isPublished:z127.boolean(),publishedAt:z127.iso.datetime().nullable(),publishedVersion:z127.string().nullable()}),publicationOutputSchema=z127.object({id:uuidSchema,status:z127.enum(["queued","building","published","failed","canceled"]),label:z127.string().nullable(),notes:z127.string().nullable(),source:z127.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z127.string().nullable(),framework:z127.string().nullable(),commit:z127.string().nullable()}),createdAt:z127.iso.datetime(),finishedAt:z127.iso.datetime().nullable(),url:z127.string().nullable(),failureCode:z127.string().nullable()}),publicationsPageOutputSchema=z127.object({items:z127.array(publicationOutputSchema),nextCursor:z127.string().nullable(),retention:z127.object({scope:z127.literal("publication_attempt_record"),records:z127.literal("project_lifetime")})}),publicationLogsOutputSchema=z127.object({status:z127.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z127.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z127.string().nullable(),items:z127.array(z127.object({timestamp:z127.iso.datetime(),phase:z127.enum(["build","deploy"]),stream:z127.enum(["command","stdout","stderr","status","error"]),message:z127.string()}))}),sandboxLogsOutputSchema=z127.object({status:z127.enum(["ok","unavailable"]),reason:z127.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z127.string().nullable(),items:z127.array(z127.object({id:z127.string(),timestamp:z127.iso.datetime().nullable(),source:z127.enum(["install","dev-server"]),phase:z127.string(),stream:z127.enum(["combined","stdout","stderr"]),message:z127.string()})),nextCursor:z127.string().nullable(),retention:z127.object({scope:z127.literal("sandbox_process_snapshot"),timestamps:z127.literal("process_start"),droppedOldest:z127.boolean(),phases:z127.array(z127.object({phase:z127.string(),source:z127.enum(["install","dev-server"]),status:z127.string(),startedAt:z127.iso.datetime().nullable(),exitCode:z127.number().int().nullable(),events:z127.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z127.object({url:z127.string(),branch:branchNameSchema}),previewOpenOutputSchema=z127.object({url:z127.url(),expiresAt:z127.iso.datetime().nullable()}),publishOutputSchema=z127.object({success:z127.boolean(),message:z127.string().optional(),firstPublish:z127.boolean(),publicationId:z127.string().optional(),url:z127.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,limit:z127.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId:projectId2,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/publications"),{limit,before:cursor3})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,publicationId:z127.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId})=>({method:"GET",path:managementProjectPath(projectId2,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,label:z127.string().trim().min(1).max(120).optional(),notes:z127.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId:projectId2,label,notes})=>({method:"POST",path:managementProjectPath(projectId2,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,publicationId:z127.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor:cursor3})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/sandbox/logs"),{limit,before:cursor3})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z128}from"zod";var integrationIdSchema,toolEffectSchema,integrationSchema,integrationToolSchema,integrationGuideSchema,integrationRunResultSchema,runInputShape,integrationsOperations,init_integrations=__esm({"../../packages/sdk/dist/operations/integrations.js"(){"use strict";init_common2();integrationIdSchema=z128.string().min(2).max(120).regex(/^[a-z0-9][a-z0-9_-]*$/),toolEffectSchema=z128.enum(["read","write","delete","financial"]),integrationSchema=z128.object({id:z128.string(),kind:z128.enum(["catalog","custom","builtIn"]),name:z128.string(),description:z128.string(),host:z128.string().nullable(),readOnly:z128.boolean(),installed:z128.boolean(),enabled:z128.boolean(),accountName:z128.string().nullable(),settings:z128.array(z128.object({key:z128.string(),label:z128.string(),description:z128.string().nullable(),required:z128.boolean()})),settingsValues:z128.record(z128.string(),z128.string()),missingSettings:z128.array(z128.string())}),integrationToolSchema=z128.object({integrationId:z128.string(),integrationName:z128.string(),key:z128.string(),name:z128.string(),description:z128.string(),effect:toolEffectSchema,input:z128.record(z128.string(),z128.unknown()).optional()}),integrationGuideSchema=z128.object({integrationId:z128.string(),name:z128.string(),description:z128.string(),content:z128.string()}),integrationRunResultSchema=z128.discriminatedUnion("status",[z128.object({status:z128.literal("ok"),output:z128.record(z128.string(),z128.unknown())}),z128.object({status:z128.literal("approval_required"),request:z128.string(),approveUrl:z128.string(),reason:z128.string(),integration:z128.object({id:z128.string(),name:z128.string()}),tool:z128.object({key:z128.string(),name:z128.string(),effect:toolEffectSchema}),input:z128.record(z128.string(),z128.unknown()),canAlwaysAllow:z128.boolean()}),z128.object({status:z128.literal("blocked"),reason:z128.string()})]),runInputShape={projectId:uuidSchema,integrationId:integrationIdSchema,tool:z128.string().min(1).max(120),input:z128.record(z128.string(),z128.unknown()).default({})},integrationsOperations={"integrations.list":{domain:"integrations",summary:"List the integrations this site can use, such as Google Search Console: whether each is on for the site, its connected account, and settings it still needs.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema}).strict(),outputSchema:z128.array(integrationSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/integrations/catalog")}),"buildRequest"),projectOutput:__name(body=>z128.array(integrationSchema).parse(responseData(body)),"projectOutput")},"integrations.tools":{domain:"integrations",summary:`Find the tools of the integrations on for this site by what you need, in plain words ("clicks by page", "sitemap"): the best matches, each with its key, the start of what it does and whether it reads or changes data. Pass a tool key to get that tool's input JSON schema, before you run it.`,accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,search:z128.string().max(200).optional(),integrationId:integrationIdSchema.optional(),tool:z128.string().min(1).max(120).optional()}).strict(),outputSchema:z128.array(integrationToolSchema),buildRequest:__name(({projectId:projectId2,search,integrationId,tool})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/integrations/tools"),{search,integration:integrationId,tool})}),"buildRequest"),projectOutput:__name(body=>z128.array(integrationToolSchema).parse(responseData(body)),"projectOutput")},"integrations.guide":{domain:"integrations",summary:"Read an integration's guide before running its tools the first time: which tool answers which question, and how to read its numbers.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,integrationId:integrationIdSchema}).strict(),outputSchema:integrationGuideSchema,buildRequest:__name(({projectId:projectId2,integrationId})=>({method:"GET",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/guide`)}),"buildRequest"),projectOutput:__name(body=>integrationGuideSchema.parse(responseData(body)),"projectOutput")},"integrations.run":{domain:"integrations",summary:"Run an integration tool that reads data, with the input its JSON schema describes. Tools that change data in the outside service run with integrations.write.",accessScope:"read",effect:"read",inputSchema:z128.object(runInputShape).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:{tool,input,readOnly:!0}}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.write":{domain:"integrations",summary:"Run an integration tool that changes data in the outside service, such as submitting a sitemap to Google, only when the user asked for that change. Unless the site always allows the tool, the answer is approval_required with an approveUrl to give the user; once they allowed it in Fimo, call again with the exact same tool and input plus the approval code they paste back. A code works for one hour.",accessScope:"write",effect:"mutation",inputSchema:z128.object({...runInputShape,approval:z128.string().min(1).max(4e3).optional()}).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input,approval})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:withoutUndefined({tool,input,approval})}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.setEnabled":{domain:"integrations",summary:"Turn an integration on or off for this site. Turning one on may need its account connected first.",accessScope:"write",effect:"mutation",inputSchema:z128.object({projectId:uuidSchema,integrationId:integrationIdSchema,enabled:z128.boolean()}).strict(),outputSchema:z128.object({ok:z128.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,enabled})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}`),body:{enabled}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")},"integrations.updateSettings":{domain:"integrations",summary:"Change an integration's settings for this site. A choice must be one the connected account offers.",accessScope:"write",effect:"mutation",inputSchema:z128.object({projectId:uuidSchema,integrationId:integrationIdSchema,settings:z128.record(z128.string(),z128.string().max(500))}).strict(),outputSchema:z128.object({ok:z128.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,settings:settings2})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/settings`),body:{settings:settings2}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")}}}});import{z as z129}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z129.object({content:z129.string(),updatedAt:z129.string().nullable(),updatedBy:z129.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z129.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance; pass the updatedAt you read as expectedUpdatedAt to refuse the save if someone saved since.",accessScope:"write",effect:"mutation",inputSchema:z129.object({projectId:uuidSchema,content:z129.string(),expectedUpdatedAt:z129.string().nullable().optional()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2,content:content2,expectedUpdatedAt})=>({method:"PUT",path:managementProjectPath(projectId2,"/knowledge"),body:expectedUpdatedAt===void 0?{content:content2}:{content:content2,expectedUpdatedAt}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z130}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z130.object({key:z130.string(),value:z130.string().optional(),defaultValue:z130.string(),locale:z130.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z130.object({data:z130.array(z130.union([TranslationDTOSchema2,z130.object({key:z130.string(),values:z130.record(z130.string(),z130.string())})]))}),labelUpsertOutputSchema=z130.object({created:z130.number().int().nonnegative(),updated:z130.number().int().nonnegative(),deleted:z130.number().int().nonnegative(),defaultLocale:z130.string(),locales:z130.array(z130.string())}),labelDeleteOutputSchema=z130.object({key:z130.string(),locale:z130.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z130.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"GET",path:tenantPath(projectId2,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,key:z130.string(),value:z130.string(),locale:z130.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId:projectId2,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId2,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,records:z130.array(z130.object({key:z130.string(),value:z130.string(),locale:z130.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId:projectId2,branch,records})=>({method:"POST",path:tenantPath(projectId2,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z130.object({projectId:uuidSchema,branch:branchNameSchema,locale:z130.string().optional(),key:z130.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId2,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z131}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z131.object({translated:z131.number().int().nonnegative(),total:z131.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z131.object({defaultLocale:z131.string(),locales:z131.array(z131.object({locale:z131.string(),isDefault:z131.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z131.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z131.object({locale:z131.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z131.object({locale:z131.string(),entriesDeleted:z131.number().int().nonnegative(),labelsDeleted:z131.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z131.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z131.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z131.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId2,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z131.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z132}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z132.object({id:z132.string().min(1),name:z132.string(),slug:z132.string()}),organizationMemberSchema=z132.object({id:z132.string().min(1),role:z132.string(),createdAt:z132.string().optional(),user:z132.object({id:z132.string().min(1),name:z132.string().nullable().optional(),email:z132.string().nullable().optional()}).optional()}),organizationInvitationSchema=z132.object({id:z132.string().min(1),email:z132.email(),role:z132.string(),organizationId:z132.string().min(1),inviterId:z132.string().min(1),status:z132.string(),expiresAt:z132.string(),createdAt:z132.string()}).passthrough(),referralSummarySchema=z132.object({counts:z132.object({signed_up:z132.number().int(),activated:z132.number().int()}),credits:z132.object({total:z132.number().int(),earned:z132.number().int().optional()}),canRefer:z132.boolean().optional(),eligibleAt:z132.iso.datetime().nullable().optional()}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z132.object({}).strict(),outputSchema:createResponseSchema2(z132.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z132.object({organizationId:z132.string().min(1)}).strict(),outputSchema:z132.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z132.object({members:z132.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z132.object({organizationId:z132.string().min(1),email:z132.email(),role:z132.enum(["owner","admin","member"]),resend:z132.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z132.object({userId:z132.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z133}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z133.object({id:uuidSchema,name:z133.string(),displayName:z133.string().nullable(),organizationId:z133.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z133.string().optional(),appUrl:z133.string().nullable().optional()}).passthrough(),projectResponseSchema=z133.object({data:projectSchema}),transferResultSchema=z133.object({projectId:z133.string(),sourceOrganizationId:z133.string(),targetOrganizationId:z133.string(),movedThreads:z133.number().int().nonnegative(),revokedInvites:z133.number().int().nonnegative(),revokedGrants:z133.number().int().nonnegative(),preservedGrants:z133.number().int().nonnegative(),warnings:z133.array(z133.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z133.object({organizationId:z133.string().min(1).optional()}).strict(),outputSchema:z133.object({data:z133.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z133.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z133.object({organizationId:z133.string().min(1),displayName:z133.string().min(1).optional(),origin:z133.enum(["scratch","migration"]).optional(),starter:z133.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z133.object({projectId:uuidSchema,targetOrganizationId:z133.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId:projectId2,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId2,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z133.object({projectId:uuidSchema,email:z133.email(),role:z133.enum(["full","edit","comment","view"])}).strict(),outputSchema:z133.object({id:z133.string().min(1)}),buildRequest:__name(({projectId:projectId2,email,role})=>({method:"POST",path:managementProjectPath(projectId2,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z133.object({id:z133.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z133.object({projectId:uuidSchema}).strict(),outputSchema:z133.unknown(),buildRequest:__name(({projectId:projectId2})=>({method:"DELETE",path:managementProjectPath(projectId2,""),body:{}}),"buildRequest")}}}});import{z as z134}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z134.iso.datetime(),scheduleStatusSchema=z134.enum(["ok","failed"]),runStatusSchema=z134.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z134.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z134.string().min(1),name:z134.string().min(1),cron:z134.string().min(1),command:z134.string().min(1),secretKeys:z134.array(z134.string().min(1)),enabled:z134.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z134.string().nullable(),overPolicyReasons:z134.array(z134.string()).optional()}).passthrough(),usageSchema=z134.object({runCount:z134.number().int().nonnegative(),runsWithOutput:z134.number().int().nonnegative()}),policySchema=z134.object({maxRuns:z134.number().int().positive(),retentionDays:z134.number().int().positive().nullable(),outputRetentionDays:z134.number().int().positive(),maxOutputBytes:z134.number().int().positive()}).passthrough(),planSchema=z134.object({code:z134.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z134.enum(["cached_subscription","free_fallback"]),activeSchedules:z134.object({used:z134.number().int().nonnegative(),limit:z134.number().int().positive()}),minCadenceMinutes:z134.number().int().positive(),maxRunMs:z134.number().int().positive(),concurrency:z134.object({used:z134.number().int().nonnegative(),limit:z134.number().int().positive()}),compute:z134.object({settledMs:z134.number().int().nonnegative(),activeMs:z134.number().int().nonnegative(),reservedMs:z134.number().int().nonnegative().optional(),includedMs:z134.number().int().positive(),remainingMs:z134.number().int().nonnegative(),resetsAt:dateSchema}),state:z134.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z134.array(z134.string())}).passthrough(),runSchema=z134.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z134.string().min(1),scheduleName:z134.string().min(1),command:z134.string().min(1),status:runStatusSchema,trigger:z134.enum(["cron","ui","cli"]),triggeredBy:z134.object({id:z134.string().min(1),name:z134.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z134.number().int().nullable(),errorCode:z134.string().nullable(),error:z134.string().nullable(),outputBytes:z134.number().int().nonnegative(),outputTruncated:z134.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z134.string().nullable(),secretSnapshot:z134.object({state:z134.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z134.array(z134.object({key:z134.string().min(1),updatedAt:dateSchema.nullable(),resolution:z134.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z134.object({items:z134.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z134.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z134.object({items:z134.array(runSchema),nextCursor:z134.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z134.string().min(1).max(120),cron:z134.string().min(1).max(120),command:z134.string().min(1).max(500),secretKeys:z134.array(z134.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z134.object({...scheduleContextShape}).strict(),outputSchema:z134.array(scheduleSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z134.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z134.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z134.object({...scheduleContextShape,...scheduleWriteShape,enabled:z134.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z134.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z134.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,limit,cursor:cursor3,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor:cursor3,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z134.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId:projectId2,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z134.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z134.object({ok:z134.literal(!0)}),buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z134.object({ok:z134.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z135}from"zod";function projectSchemaDefinition(body){return z135.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z135.object({id:z135.string(),name:z135.string(),label:z135.string(),isSingleton:z135.boolean(),slugUnique:z135.boolean(),i18n:z135.record(z135.string(),z135.unknown()),description:z135.string().nullable().default(null),groups:z135.array(z135.record(z135.string(),z135.unknown())),fields:z135.record(z135.string(),z135.unknown()),createdAt:z135.string(),updatedAt:z135.string()}).passthrough(),schemaListOutputSchema=z135.object({contentTypes:z135.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z135.object({typeName:z135.string().min(1).max(255),generatedPaths:z135.array(z135.string().min(1)).max(1e3),tip:z135.string().min(1)})}),schemaDefinitionInputSchema=z135.record(z135.string(),z135.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z135.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z135.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z135.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"GET",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z135.array(schemaDefinitionInputSchema).min(1).max(100),operations:z135.array(z135.record(z135.string(),z135.unknown())).optional()}).strict(),outputSchema:z135.array(z135.unknown()),buildRequest:__name(({projectId:projectId2,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId2,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z135.object({data:z135.array(z135.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z135.string().min(1).max(255)}).strict(),outputSchema:z135.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z135.object({data:z135.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z135.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z135.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z135.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z135.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z135.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z136}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z136.union([z136.literal("production"),z136.literal("preview"),uuidSchema]),secretKindSchema=z136.enum(["variable","secret"]),projectSecretSchema=z136.object({id:z136.string().min(1),projectId:z136.string().min(1),key:z136.string().min(1),kind:secretKindSchema,exposure:z136.enum(["public","private"]),environment:environmentSchema2,value:z136.string().optional(),maskedValue:z136.string().optional(),createdAt:z136.string(),updatedAt:z136.string()}),secretWriteInputSchema=z136.object({projectId:uuidSchema,key:z136.string().min(1).max(255),kind:secretKindSchema,value:z136.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z136.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z136.array(projectSecretSchema),buildRequest:__name(({projectId:projectId2,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z136.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z136.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z136.object({projectId:uuidSchema,key:z136.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z136.unknown(),buildRequest:__name(({projectId:projectId2,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z136.object({projectId:uuidSchema,branch:z136.string().min(1)}).strict(),outputSchema:z136.object({branch:z136.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z136.array(z136.object({branch:z136.string().optional(),env:z136.string().optional(),parentBranch:z136.string().nullable().optional(),parentEnv:z136.string().nullable().optional(),resolvedEnvironment:z136.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z137}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z137.object({status:z137.literal("passed")}).passthrough(),sessionConflictSummarySchema=z137.object({surface:surfaceNameSchema,key:z137.string().min(1),kind:z137.string().optional(),description:z137.string(),path:z137.string().optional()}).passthrough(),surfaceDeltaItemSchema=z137.object({verb:z137.enum(["added","removed","changed","conflict"]),key:z137.string(),detail:z137.string().optional(),origin:z137.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z137.record(z137.string(),z137.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z137.object({surface:surfaceNameSchema,status:z137.enum(["ok","timed_out","failed","unchanged"]),durationMs:z137.number().int().nonnegative().optional(),changedCount:z137.number().int().nonnegative(),conflictCount:z137.number().int().nonnegative(),items:z137.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z137.boolean().optional(),error:z137.string().optional()}).passthrough(),sessionChangesSchema=z137.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z137.iso.datetime(),surfaces:z137.array(perSurfaceDeltaSchema),crossSurface:z137.array(crossSurfaceFindingSchema).optional(),fingerprint:z137.string()}).passthrough(),projectScriptStatusSchema=z137.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z137.discriminatedUnion("operation",[z137.object({operation:z137.literal("dependencies_install"),repairedInstallPolicy:z137.boolean(),tip:z137.string()}),z137.object({operation:z137.literal("schemas_sync"),tip:z137.string()}),z137.object({operation:z137.literal("typecheck"),status:projectScriptStatusSchema,output:z137.string()}),z137.object({operation:z137.literal("lint"),status:projectScriptStatusSchema,output:z137.string()})]),conflictSchema2=z137.object({surface:surfaceNameSchema,key:z137.string(),kind:z137.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z137.string(),parentValue:z137.unknown().optional(),childValue:z137.unknown().optional(),conflictingFields:z137.array(z137.string()).optional(),code:z137.object({path:z137.string(),unresolvable:z137.boolean().optional(),reason:z137.string().optional(),targetCommits:z137.array(z137.object({sha:z137.string(),subject:z137.string(),body:z137.string().optional(),author:z137.string(),date:z137.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z137.object({oid:z137.string().optional(),content:z137.string().optional(),truncated:z137.boolean(),binary:z137.boolean()}),codeConflictDetailSchema=z137.object({path:z137.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z137.string(),targetTipSha:z137.string(),mergeBaseSha:z137.string().optional()}),resolutionChoiceSchema=z137.enum(["parent","child","pick"]),conflictResolutionSchema2=z137.object({surface:surfaceNameSchema,key:z137.string().min(1),choice:resolutionChoiceSchema,pickedValue:z137.unknown().optional(),fieldPicks:z137.array(z137.object({field:z137.string().min(1),choice:resolutionChoiceSchema,pickedValue:z137.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z137.string().trim().min(1).max(120).optional(),goal:z137.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z137.object({session:sessionEnvelopeSchema,adopted:z137.boolean()}),buildRequest:__name(({projectId:projectId2,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId2,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"GET",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z137.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z137.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z137.number().int().min(1).max(100).optional()}).strict(),outputSchema:z137.object({items:z137.array(sessionEnvelopeSchema),nextCursor:z137.string().nullable()}),buildRequest:__name(({projectId:projectId2,status,cursor:cursor3,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/sessions"),{status,cursor:cursor3,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z137.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId:projectId2,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z137.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z137.object({requested:z137.literal(!0),alreadyRequested:z137.boolean(),reviewId:uuidSchema,reviewUrl:z137.url(),status:z137.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z137.string().min(1),savedRevision:z137.string().min(1),fingerprint:z137.string().min(1),visibility:z137.literal("user-visible"),retention:z137.literal("durable"),expiresAt:z137.null(),merged:z137.literal(!1),published:z137.literal(!1),links:z137.object({preview:z137.url(),changes:z137.url(),conversation:z137.url().nullable()})}),buildRequest:__name(({projectId:projectId2,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z137.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z137.literal("temporary"),visibility:z137.enum(["internal","user-visible"]),expiresAt:z137.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z137.string().min(1).max(100),args:z137.record(z137.string(),z137.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId:projectId2,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,action:z137.enum(["merge","discard"]),message:z137.string().max(1e3).optional(),description:z137.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z137.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z137.boolean(),mergeId:uuidSchema.optional(),conflictCount:z137.number().int().nonnegative().optional(),conflicts:z137.array(sessionConflictSummarySchema).optional(),parentAdvanced:z137.boolean().optional(),code:z137.string().optional(),summary:z137.string().nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z137.number().int().min(1).max(100).optional(),codePath:z137.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z137.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z137.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z137.number().int().nonnegative(),error:z137.string().nullable()}),conflicts:z137.array(conflictSchema2).max(100),nextCursor:z137.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,cursor:cursor3,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor:cursor3,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z137.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z137.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z137.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z137.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z138}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z138.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z138.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z139}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z139.object({message:z139.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z139.object({id:uuidSchema,deliveryStatus:z139.enum(["pending","delivered","failed"]),message:z139.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z139.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId:projectId2,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId:projectId2,branch})}),"buildRequest")}}}});import{z as z140}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z140.record(z140.string(),z140.unknown()),deliveryStatusSchema=z140.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z140.object({id:uuidSchema,projectId:uuidSchema,name:z140.string(),eventType:z140.string().min(1),enabled:z140.boolean(),destination:z140.object({host:z140.string(),maskedUrl:z140.string(),kind:z140.string()}),filter:jsonObjectSchema,headers:z140.array(jsonObjectSchema),bodyTemplate:z140.unknown().nullable(),signingEnabled:z140.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z140.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z140.string().min(1),status:deliveryStatusSchema,attemptCount:z140.number().int().nonnegative(),responseStatus:z140.number().int().nullable(),createdAt:z140.iso.datetime()}).passthrough(),attemptSchema=z140.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z140.number().int().positive(),status:z140.enum(["delivering","succeeded","failed"]),createdAt:z140.iso.datetime()}).passthrough(),deliveriesPageSchema=z140.object({items:z140.array(deliverySchema),pagination:z140.object({page:z140.number().int().positive(),limit:z140.number().int().positive(),total:z140.number().int().nonnegative(),totalPages:z140.number().int().positive(),hasMore:z140.boolean()}),stats:z140.object({total:z140.number().int().nonnegative(),succeeded:z140.number().int().nonnegative(),failed:z140.number().int().nonnegative()})}),eventSchema=z140.object({type:z140.string().min(1),family:z140.string(),description:z140.string(),variables:z140.array(z140.string()),data:z140.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z140.object({projectId:uuidSchema}).strict(),outputSchema:z140.array(eventSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z140.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z140.object({projectId:uuidSchema}).strict(),outputSchema:z140.array(webhookSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z140.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z140.object({webhook:webhookSchema,signingSecret:z140.string().min(1)}),buildRequest:__name(({projectId:projectId2,webhook})=>({method:"POST",path:managementProjectPath(projectId2,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z140.object({webhook:webhookSchema,signingSecret:z140.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z140.unknown(),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z140.string().min(1),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z140.object({signingSecret:z140.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z140.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z140.string().nullable()}),buildRequest:__name(({projectId:projectId2,webhookId,page:page2,cursor:cursor3,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page:page2,cursor:cursor3}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z140.object({delivery:deliverySchema,attempts:z140.array(attemptSchema)}),buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z140.object({delivery:deliverySchema,attempts:z140.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z140.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z141}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_integrations();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...integrationsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z141.object({id:z141.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z141.string().min(1),summary:z141.string().min(1),accessScope:z141.enum(["read","write","code","agents"]),effect:z141.enum(["read","mutation"]),inputJsonSchema:z141.record(z141.string(),z141.unknown()),outputJsonSchema:z141.record(z141.string(),z141.unknown())}).strict(),fimoOperationManifestSchema=z141.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z141.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z141.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.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:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.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 root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.join(root,"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=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.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 path4 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=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}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,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue2=>{let{path:path52,message}=issue2;return`${Array.isArray(path52)&&path52.length>0?`${path52.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatFieldErrors(parsed){if(!Array.isArray(parsed.errors))return null;let fields=parsed.errors.flatMap(error=>{if(!error||typeof error!="object")return[];let{path:path52,message}=error;return typeof message!="string"||!message?[]:[typeof path52=="string"&&path52?`${path52}: ${message}`:message]});return fields.length>0?fields.join("; "):null}function formatError(status,text2,body){if(!text2)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let fields=formatFieldErrors(parsed),message=fields?`${parsed.message}: ${fields}`:parsed.message,partial=formatPartialResult(parsed);return partial?`${message} ${partial}`: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 text2}async function parseError(response){let text2=await response.text(),body;try{body=text2?JSON.parse(text2):void 0}catch{return{detail:formatError(response.status,text2)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text2,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message),server.body=body}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path52,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,this.status=status,this.detail=detail,this.code=code2,this.body=body}},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}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;body;constructor(apiUrl,required=[],message,server={}){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,this.code=server.code,this.detail=server.detail,this.body=server.body}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatFieldErrors,"formatFieldErrors");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});function recoverTenantApiBaseUrl(tenantApiUrl,projectId2,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId2}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId2,branch,base)===normalized?base:void 0}catch{return}}function createIdentityService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{getCurrentSession(){return transport.request("/api/auth/get-session")}}}function createGitService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getRemote(projectId2,branch){let body=await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-remote`,{},{preserveForbidden:!0});if(!body.data.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(body.data.tenantApiUrl,projectId2,branch);if(recovered)return{...body.data,tenantApiBaseUrl:recovered}}return body.data},async getCredential(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-credential`,{},{preserveForbidden:!0})).data}}}function createPublicationControlService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return{async publish(projectId2,request={}){return(await transport.request(`/api/management/projects/${projectId2}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null},async unpublish(projectId2){await transport.request(`/api/management/projects/${projectId2}/unpublish`,{method:"POST"})}}}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 transferBlockersFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return[];let blockers=body.blockers;return Array.isArray(blockers)?blockers:[]}function createSandboxService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getHostedPreview(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeBranchPathSegment(branch)}/hosted-preview`)).data},async pull(projectId2,onProgress,branch,options={}){let params=new URLSearchParams;options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),response=await transport.response(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/sandbox/pull${search?`?${search}`:""}`,{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="",failure=null,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(`
50
50
 
51
51
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
52
52
 
@@ -272,7 +272,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
272
272
  ${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(p,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p.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(`
273
273
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path52=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path52,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch),git=createGitService(loadConfig(),ctx.branch),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(git,ctx.projectId,ctx.branch,cwd),serverPromise=withSoftTimeout(fimo.execute("branches.status",{projectId:ctx.projectId,branch:ctx.branch,against:options.vs,surfaces:surfaces?.map(surface=>surface==="translations"?"labels":surface)}),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 portableServer=serverResult.value,server={branch:portableServer.branch,env:portableServer.branch,vs:portableServer.against,syncState:portableServer.syncState??(portableServer.state==="clean"?"in-sync":"diverged"),generatedAt:portableServer.generatedAt,surfaces:portableServer.surfaces.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),crossSurface:portableServer.crossSurface?.map(finding=>({...finding,source:{...finding.source,surface:finding.source.surface==="labels"?"translations":finding.source.surface},target:{...finding.target,surface:finding.target.surface==="labels"?"translations":finding.target.surface}}))},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 p=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
274
274
 
275
- ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project2();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_esm();init_dist();import fs47 from"node:fs";import path51 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_config();init_sdk_transport();init_project_services();import{randomUUID}from"node:crypto";import{setTimeout as pause}from"node:timers/promises";var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{token:"agents:prompt",risk:"high",declarable:!1,enforcedBy:"api",description:"Send messages to project agents and chats, and start routines, as the signed-in person"},{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{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:"i18n:locales:add",risk:"medium",declarable:!0,enforcedBy:"api",description:"Add a supported locale to the project; never remove one or change the default"},{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:"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:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z141}from"zod";var SurfaceGuardPolicySchema=z141.enum(["block","warn","allow"]),ClassificationSchema=z141.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z141.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z141.object({enabled:z141.boolean(),allowed_skills:z141.array(z141.string().min(1)).default([]),allowed_classifications:z141.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z141.enum(["off","daily","weekly"]),NotificationFormatSchema=z141.object({markdown:z141.boolean().default(!0),html:z141.boolean().default(!1)}),NotificationsPolicySchema=z141.object({email_recipients:z141.array(z141.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z141.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z141.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
275
+ ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project2();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_esm();init_dist();import fs47 from"node:fs";import path51 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_config();init_sdk_transport();init_project_services();import{randomUUID}from"node:crypto";import{setTimeout as pause}from"node:timers/promises";var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{token:"agents:prompt",risk:"high",declarable:!1,enforcedBy:"api",description:"Send messages to project agents and chats, and start routines, as the signed-in person"},{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{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:"i18n:locales:add",risk:"medium",declarable:!0,enforcedBy:"api",description:"Add a supported locale to the project; never remove one or change the default"},{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:"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:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z142}from"zod";var SurfaceGuardPolicySchema=z142.enum(["block","warn","allow"]),ClassificationSchema=z142.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z142.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z142.object({enabled:z142.boolean(),allowed_skills:z142.array(z142.string().min(1)).default([]),allowed_classifications:z142.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z142.enum(["off","daily","weekly"]),NotificationFormatSchema=z142.object({markdown:z142.boolean().default(!0),html:z142.boolean().default(!1)}),NotificationsPolicySchema=z142.object({email_recipients:z142.array(z142.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z142.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z142.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
276
276
  // Every fact is fine, broken, or unknown (could not tell); only broken leads to a finding.
277
277
  import { spawn, spawnSync } from 'node:child_process';
278
278
  import crypto from 'node:crypto';
@@ -2364,7 +2364,7 @@ else if (cmd === 'text') pageText();
2364
2364
  else if (cmd === 'links') links();
2365
2365
  else if (cmd === 'ledger') pageLedger();
2366
2366
  else console.log('node site.mjs crawl [origin] [--max 300] [--max-links 300] [--deadline 900] [--parallel 1] [--seed previous.txt] [--preview-host host] [--hosted url] [--quality] [--phone-max 20] [--compliance] [--consent-max 6] [--fresh] [--pages file] [--http [--browser-max 100]] [--session name] | wait | check [--topic t1,t2] [--retired "Old=New;..."] [--today YYYY-MM-DD] | text [/path ...] | links (after crawl --pages) | diff previous.txt (writes snapshot.txt) | ledger [previous.tsv] [--values "v1;v2"] [--today YYYY-MM-DD] (writes pages.tsv)');
2367
- `;import{z as z142}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=z142.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z142.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"],PERSON_ONLY_OPERATION_CAPABILITIES=["agents:prompt"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");function isPersonOnlyOperationCapability(capability){return PERSON_ONLY_OPERATION_CAPABILITIES.includes(capability)}__name(isPersonOnlyOperationCapability,"isPersonOnlyOperationCapability");var OPERATION_CAP={"agents.list":"agents:read","agents.routines":"agents:read","agents.routine_runs":"agents:read","agents.read":"agents:read","agents.search":"agents:read","agents.send":"agents:prompt","agents.run":"agents:prompt","knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","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","i18n.locales.add":"i18n:locales:add","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.site.check":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","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");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 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_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(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"person-only":return"Only a person runs this with their own fimo CLI. Ask the person to run it.";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 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.branch})}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.branch}),{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);if(isPersonOnlyOperationCapability(cap)){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:"person-only",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:"person-only",sessionId})}return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor3,config){let value=Number(cursor3??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page2=await input.fetchPage(input.cursor);if(!input.allPages||page2.nextCursor===null)return page2;let items=[...page2.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page2.nextCursor!==null;){if(seen.has(page2.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page2.nextCursor),page2=await input.fetchPage(page2.nextCursor),items.push(...page2.items)}return{...page2,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");init_project_context();init_project2();init_project2();import fs7 from"node:fs";import path8 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=path8.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs7.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");var AgentsCommandError=class extends Error{static{__name(this,"AgentsCommandError")}code;hint;constructor(code2,message,hint){super(message),this.name="AgentsCommandError",this.code=code2,this.hint=hint}};async function projectContext(options,command,operation){let projectId2=options.project??resolveProjectSettings(resolveProjectCwd(options.cwd))?.projectId;if(!projectId2)throw new NotInProjectError;let branch=branchOverrideFromCommand(command)??(process.env.FIMO_ENV?.trim()||DEFAULT_BRANCH);await requireOperation(operation,{projectId:projectId2});let cfg=loadConfig();return{projectId:projectId2,branch,cfg,fimo:createCliFimoClient(cfg)}}__name(projectContext,"projectContext");function pick(items,ref,nameOf,kind){let byId=items.find(item=>item.id===ref),found=byId?[byId]:items.filter(item=>nameOf(item)===ref);if(!found.length)throw new Error(`${kind} not found: ${ref}`);if(found.length>1)throw new Error(`Multiple ${kind.toLowerCase()}s named "${ref}". Use an ID from fimo agents.`);return found[0]}__name(pick,"pick");var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,POLL_MS=2e3,SETTLE_MS=3e4,AROUND_PAGES=10,PAGE_LIMIT=200,LIST_HINT="List them with `fimo agents list --all`.";async function resolveChat(scope2,ref){let{chats:chats2}=await scope2.fimo.execute("agents.chats",{projectId:scope2.projectId,branch:scope2.branch}),byId=chats2.find(chat=>chat.id===ref);if(byId)return byId;let named=chats2.filter(chat=>chat.title===ref);if(named.length>1)throw new AgentsCommandError("AMBIGUOUS_CHAT",`Several chats are named "${ref}".`,`Use its id. ${LIST_HINT}`);if(named[0])return named[0];if(UUID.test(ref))return{id:ref,title:null,kind:null};throw new AgentsCommandError("CHAT_NOT_FOUND",`No agent or chat is named "${ref}" or has that id.`,LIST_HINT)}__name(resolveChat,"resolveChat");function chatNotFound(chat){return new AgentsCommandError("CHAT_NOT_FOUND",`No agent or chat has the id ${chat.id} in this project.`,LIST_HINT)}__name(chatNotFound,"chatNotFound");function next(scope2,options,args){return`fimo agents ${args}${options.project?` --project ${scope2.projectId}`:""}`}__name(next,"next");var TOOL_PART=/^tool-(.+)$/;function messageView(message,chat,full){let parts=message.role==="assistant"&&!full?partsAfterReplyStart(message.parts):message.parts,lines=[],tools=[];for(let part of parts){part?.type==="text"&&typeof part.text=="string"&&part.text.trim()&&lines.push(part.text.trim());let tool=part?.type==="dynamic-tool"&&typeof part.toolName=="string"?part.toolName:typeof part?.type=="string"&&part.type!==START_REPLY_PART_TYPE?TOOL_PART.exec(part.type)?.[1]:void 0;tool&&(tools.push(tool),lines.push(`\xB7 ${tool}`))}let metadata=message.metadata??{},credits=typeof metadata.credits=="number"?metadata.credits:null;return{id:message.id,createdAt:message.createdAt,role:message.role,author:{kind:message.role==="assistant"?"agent":message.author.kind,name:authorName(message,chat)},text:lines.filter(line=>!line.startsWith("\xB7 ")).join(`
2367
+ `;import{z as z143}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=z143.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z143.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"],PERSON_ONLY_OPERATION_CAPABILITIES=["agents:prompt"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");function isPersonOnlyOperationCapability(capability){return PERSON_ONLY_OPERATION_CAPABILITIES.includes(capability)}__name(isPersonOnlyOperationCapability,"isPersonOnlyOperationCapability");var OPERATION_CAP={"agents.list":"agents:read","agents.routines":"agents:read","agents.routine_runs":"agents:read","agents.read":"agents:read","agents.search":"agents:read","agents.send":"agents:prompt","agents.run":"agents:prompt","knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","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","i18n.locales.add":"i18n:locales:add","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.site.check":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","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");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 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_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(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"person-only":return"Only a person runs this with their own fimo CLI. Ask the person to run it.";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 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.branch})}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.branch}),{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);if(isPersonOnlyOperationCapability(cap)){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:"person-only",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:"person-only",sessionId})}return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor3,config){let value=Number(cursor3??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page2=await input.fetchPage(input.cursor);if(!input.allPages||page2.nextCursor===null)return page2;let items=[...page2.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page2.nextCursor!==null;){if(seen.has(page2.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page2.nextCursor),page2=await input.fetchPage(page2.nextCursor),items.push(...page2.items)}return{...page2,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");init_project_context();init_project2();init_project2();import fs7 from"node:fs";import path8 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=path8.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs7.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");var AgentsCommandError=class extends Error{static{__name(this,"AgentsCommandError")}code;hint;constructor(code2,message,hint){super(message),this.name="AgentsCommandError",this.code=code2,this.hint=hint}};async function projectContext(options,command,operation){let projectId2=options.project??resolveProjectSettings(resolveProjectCwd(options.cwd))?.projectId;if(!projectId2)throw new NotInProjectError;let branch=branchOverrideFromCommand(command)??(process.env.FIMO_ENV?.trim()||DEFAULT_BRANCH);await requireOperation(operation,{projectId:projectId2});let cfg=loadConfig();return{projectId:projectId2,branch,cfg,fimo:createCliFimoClient(cfg)}}__name(projectContext,"projectContext");function pick(items,ref,nameOf,kind){let byId=items.find(item=>item.id===ref),found=byId?[byId]:items.filter(item=>nameOf(item)===ref);if(!found.length)throw new Error(`${kind} not found: ${ref}`);if(found.length>1)throw new Error(`Multiple ${kind.toLowerCase()}s named "${ref}". Use an ID from fimo agents.`);return found[0]}__name(pick,"pick");var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,POLL_MS=2e3,SETTLE_MS=3e4,AROUND_PAGES=10,PAGE_LIMIT=200,LIST_HINT="List them with `fimo agents list --all`.";async function resolveChat(scope2,ref){let{chats:chats2}=await scope2.fimo.execute("agents.chats",{projectId:scope2.projectId,branch:scope2.branch}),byId=chats2.find(chat=>chat.id===ref);if(byId)return byId;let named=chats2.filter(chat=>chat.title===ref);if(named.length>1)throw new AgentsCommandError("AMBIGUOUS_CHAT",`Several chats are named "${ref}".`,`Use its id. ${LIST_HINT}`);if(named[0])return named[0];if(UUID.test(ref))return{id:ref,title:null,kind:null};throw new AgentsCommandError("CHAT_NOT_FOUND",`No agent or chat is named "${ref}" or has that id.`,LIST_HINT)}__name(resolveChat,"resolveChat");function chatNotFound(chat){return new AgentsCommandError("CHAT_NOT_FOUND",`No agent or chat has the id ${chat.id} in this project.`,LIST_HINT)}__name(chatNotFound,"chatNotFound");function next(scope2,options,args){return`fimo agents ${args}${options.project?` --project ${scope2.projectId}`:""}`}__name(next,"next");var TOOL_PART=/^tool-(.+)$/;function messageView(message,chat,full){let parts=message.role==="assistant"&&!full?partsAfterReplyStart(message.parts):message.parts,lines=[],tools=[];for(let part of parts){part?.type==="text"&&typeof part.text=="string"&&part.text.trim()&&lines.push(part.text.trim());let tool=part?.type==="dynamic-tool"&&typeof part.toolName=="string"?part.toolName:typeof part?.type=="string"&&part.type!==START_REPLY_PART_TYPE?TOOL_PART.exec(part.type)?.[1]:void 0;tool&&(tools.push(tool),lines.push(`\xB7 ${tool}`))}let metadata=message.metadata??{},credits=typeof metadata.credits=="number"?metadata.credits:null;return{id:message.id,createdAt:message.createdAt,role:message.role,author:{kind:message.role==="assistant"?"agent":message.author.kind,name:authorName(message,chat)},text:lines.filter(line=>!line.startsWith("\xB7 ")).join(`
2368
2368
 
2369
2369
  `),tools,lines,...message.role==="assistant"?{credits,status:typeof metadata.status=="string"?metadata.status:null}:{}}}__name(messageView,"messageView");function authorName(message,chat){if(message.role==="assistant")return chat.kind==="agent"&&chat.title?chat.title:"Fimo";if(message.author.kind==="person"){let user=message.metadata?.user??null;return typeof user?.name=="string"&&user.name?user.name:"A person"}return message.author.kind==="routine"?"Routine":message.author.kind==="agent"?"An agent":"Fimo"}__name(authorName,"authorName");function openQuestions(chronological2){return getBlockStates(chronological2).filter(state=>state.status==="waiting").map(state=>{let block2=state.versions.at(-1).block;return{messageId:state.messageId,title:waitingBlockTitle(block2),questions:block2.type==="form"?block2.steps.map(step=>step.question):[]}})}__name(openQuestions,"openQuestions");function renderMessage(view){let credits=view.role==="assistant"&&view.credits!==null?` \xB7 ${view.credits} credits`:"",status=view.role==="assistant"&&view.status&&view.status!=="completed"?` \xB7 ${view.status}`:"",body=view.lines.length?view.lines.map(line=>` ${line.replace(/\n/g,`
2370
2370
  `)}`).join(`
@@ -2454,8 +2454,8 @@ ${c2}${n3}
2454
2454
  `}case"submit":{let n3=s?`${r2?" ":""}${styleText2("dim",s)}`:"",i2=r2?styleText2("gray",S_BAR):"";return`${l}${i2}${n3}`}case"cancel":{let n3=s?` ${styleText2(["strikethrough","dim"],s)}`:"",i2=r2?styleText2("gray",S_BAR):"";return`${l}${i2}${n3}${s.trim()?`
2455
2455
  ${i2}`:""}`}default:{let n3=r2?`${styleText2("cyan",S_BAR)} `:"",i2=r2?styleText2("cyan",S_BAR_END):"";return`${l}${n3}${o}
2456
2456
  ${i2}
2457
- `}}}}).prompt(),"text");init_esm();init_dist();init_config();init_sdk_transport();import{z as z143}from"zod";init_esm();init_config();init_sdk_transport();function createContentTransferService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch),tenantPath2=__name((projectId2,route)=>`/api/tenant/${projectId2}/branches/${encodeBranchPathSegment(branch)}${route}`,"tenantPath");return{async listEntries(projectId2,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return transport.request(tenantPath2(projectId2,`/entries/${typeName}${query}`))},async uploadAsset(projectId2,formData){return(await(await transport.response(tenantPath2(projectId2,"/assets/upload"),{method:"POST",body:formData})).json()).data},async admitAssetUploads(projectId2,sizes){return(await transport.request(tenantPath2(projectId2,"/assets/upload-admissions"),{method:"POST",body:JSON.stringify({files:sizes.map(sizeBytes=>({sizeBytes}))})})).data.admissionId},async completeAssetUploads(projectId2,admissionId){await transport.request(tenantPath2(projectId2,`/assets/upload-admissions/${admissionId}/complete`),{method:"POST"})},async getAssetReferenceImpact(projectId2,request){return(await(await transport.response(tenantPath2(projectId2,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
2458
- `).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId2,data){return(await transport.request(tenantPath2(projectId2,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId2,id,data){return(await transport.request(tenantPath2(projectId2,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");init_project_context();init_project2();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z143.object({sourceId:z143.string().min(1),path:z143.string().min(1),name:z143.string().min(1).optional(),parentId:z143.string().min(1).optional(),folderPath:z143.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z143.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item,admissionId){let filePath=path9.resolve(cwd,item.path);if(!fs8.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs8.readFileSync(filePath),fileName=path9.basename(filePath),formData=new FormData,mimeType=path9.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),admissionId&&formData.append("admissionId",admissionId),formData}__name(buildAssetFormData,"buildAssetFormData");function admissibleFileSize(cwd,item){try{let{size}=fs8.statSync(path9.resolve(cwd,item.path));return size>0&&size<=MAX_UPLOAD_FILE_SIZE_BYTES?size:null}catch{return null}}__name(admissibleFileSize,"admissibleFileSize");function isRejectedAdmission(error){return error instanceof ApiRequestError&&error.code==="media_upload_admission_invalid"}__name(isRejectedAdmission,"isRejectedAdmission");function readBulkUploadManifest(cwd,manifest){let manifestPath=path9.resolve(cwd,manifest);if(!fs8.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs8.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(issue2=>`${issue2.path.join(".")||"manifest"}: ${issue2.message}`);throw new Error(`Invalid asset manifest:
2457
+ `}}}}).prompt(),"text");init_esm();init_dist();init_config();init_sdk_transport();import{z as z144}from"zod";init_esm();init_config();init_sdk_transport();function createContentTransferService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch),tenantPath2=__name((projectId2,route)=>`/api/tenant/${projectId2}/branches/${encodeBranchPathSegment(branch)}${route}`,"tenantPath");return{async listEntries(projectId2,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return transport.request(tenantPath2(projectId2,`/entries/${typeName}${query}`))},async uploadAsset(projectId2,formData){return(await(await transport.response(tenantPath2(projectId2,"/assets/upload"),{method:"POST",body:formData})).json()).data},async admitAssetUploads(projectId2,sizes){return(await transport.request(tenantPath2(projectId2,"/assets/upload-admissions"),{method:"POST",body:JSON.stringify({files:sizes.map(sizeBytes=>({sizeBytes}))})})).data.admissionId},async completeAssetUploads(projectId2,admissionId){await transport.request(tenantPath2(projectId2,`/assets/upload-admissions/${admissionId}/complete`),{method:"POST"})},async getAssetReferenceImpact(projectId2,request){return(await(await transport.response(tenantPath2(projectId2,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
2458
+ `).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId2,data){return(await transport.request(tenantPath2(projectId2,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId2,id,data){return(await transport.request(tenantPath2(projectId2,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");init_project_context();init_project2();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z144.object({sourceId:z144.string().min(1),path:z144.string().min(1),name:z144.string().min(1).optional(),parentId:z144.string().min(1).optional(),folderPath:z144.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z144.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item,admissionId){let filePath=path9.resolve(cwd,item.path);if(!fs8.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs8.readFileSync(filePath),fileName=path9.basename(filePath),formData=new FormData,mimeType=path9.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),admissionId&&formData.append("admissionId",admissionId),formData}__name(buildAssetFormData,"buildAssetFormData");function admissibleFileSize(cwd,item){try{let{size}=fs8.statSync(path9.resolve(cwd,item.path));return size>0&&size<=MAX_UPLOAD_FILE_SIZE_BYTES?size:null}catch{return null}}__name(admissibleFileSize,"admissibleFileSize");function isRejectedAdmission(error){return error instanceof ApiRequestError&&error.code==="media_upload_admission_invalid"}__name(isRejectedAdmission,"isRejectedAdmission");function readBulkUploadManifest(cwd,manifest){let manifestPath=path9.resolve(cwd,manifest);if(!fs8.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs8.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(issue2=>`${issue2.path.join(".")||"manifest"}: ${issue2.message}`);throw new Error(`Invalid asset manifest:
2459
2459
  ${issues.join(`
2460
2460
  `)}`)}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 index=nextIndex;nextIndex+=1,results[index]=await run(items[index])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page2=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor3=>{let offset=parseCursorNumber(cursor3,{defaultValue:0,minimum:0}),response=await fimo.execute("assets.list",{projectId:ctx.projectId,branch:ctx.branch,parentId:options.parentId||void 0,search:options.search||void 0,type:options.type||void 0,mimePrefix:mimePrefix||void 0,sortBy:options.sortBy||void 0,limit:pagination.limit,offset}),hasMore=response.nextCursor!==null;return{...response,nextCursor:hasMore?String(offset+pagination.limit):null,meta:{limit:pagination.limit,offset,total:response.total,hasMore}}},"fetchPage")}),result={data:page2.items,items:page2.items,nextCursor:page2.nextCursor,total:page2.total,meta:{...page2.meta,offset:initialOffset,hasMore:page2.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page2.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page2.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result;try{result=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}))}catch(error){if(error instanceof ApiRequestError&&error.code==="unclaimed_media_limit"){ui.error({command:"assets upload",code:"UNCLAIMED_MEDIA_LIMIT",message:error.detail,details:{limits:error.body.limits}});return}throw error}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}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let admissions=new Set,finished=new Set,admit=__name(async pending=>{let sizes=pending.map(item=>admissibleFileSize(cwd,item)).filter(size=>size!==null);if(sizes.length===0)return;let id=await content2.admitAssetUploads(ctx.projectId,sizes);return admissions.add(id),id},"admit"),admissionId;try{admissionId=await admit(items)}catch(error){if(error instanceof ApiRequestError&&error.code==="media_storage_limit_exceeded"){let body=error.body;ui.error({command:"assets bulk-upload",code:"MEDIA_STORAGE_LIMIT_EXCEEDED",message:"The files do not fit the media storage allowance. Nothing was uploaded.",details:{used_bytes:body.usedBytes,limit_bytes:body.limitBytes,incoming_bytes:body.incomingBytes}});return}throw error}let renewal,renewAdmission=__name(rejectedId=>admissionId!==rejectedId?Promise.resolve(admissionId):(renewal??=admit(items.filter(item=>!finished.has(item))).then(id=>(admissionId=id,id)).finally(()=>{renewal=void 0}),renewal),"renewAdmission"),upload=__name(async item=>{let id=admissionId;try{return await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item,id))}catch(error){if(!id||!isRejectedAdmission(error))throw error;return content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item,await renewAdmission(id)))}},"upload"),uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await upload(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)}}finally{finished.add(item)}});for(let id of admissions)try{await content2.completeAssetUploads(ctx.projectId,id)}catch(error){isRejectedAdmission(error)||ui.warn({command:"assets bulk-upload",message:`Uploads finished, but the upload batch could not be closed: ${error instanceof Error?error.message:String(error)}`})}let 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,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.read",{projectId:ctx.projectId,branch:ctx.branch,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,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.createFolder",{projectId:ctx.projectId,branch:ctx.branch,name,parentId: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,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.move",{projectId:ctx.projectId,branch:ctx.branch,id,parentId:options.parentId});ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.",scopeCount=__name(scope2=>scope2.referenceCount??scope2.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope2=>[scope2.scope,scopeCount(scope2)])),referenceCount=scopes.reduce((total,scope2)=>total+scopeCount(scope2),0),codeReferenceCount=scopes.reduce((total,scope2)=>total+(scope2.codeReferenceCount??0),0);return{status:scopes.some(scope2=>scope2.coverage!=="complete"||scope2.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope2=>[scope2.scope,scope2.coverage])),counts,referenceCount,codeReferenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(content2,projectId2,id){let events=await content2.getAssetReferenceImpact(projectId2,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(content2,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("assets.replaceReferences",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.with}),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await confirm({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the site? This cannot be undone.`:`Permanently destroy asset ${id} across the site? This cannot be undone.`,initialValue:!1});if(isCancel(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement=await fimo.execute("assets.replaceAndDestroy",{projectId:ctx.projectId,branch:ctx.branch,id,replacementAssetId:options.replaceWith}),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await fimo.execute("assets.destroy",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let outcome=await fimo.execute("assets.replaceAndRemove",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.replaceWith}),receipt2={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!1,removal:{operationId:outcome.id,expiresAt:outcome.expiresAt,undoable:outcome.undoable},replacement:{assetId:options.replaceWith,code:outcome.codeReplacement}};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError;if(!options.withoutChecking)try{usage=await loadAssetImpact(content2,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await fimo.execute("assets.delete",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_local_runtime_env();init_config();init_sdk_transport();init_sdk_transport();init_project_services();init_esm();init_auth();init_sdk_transport();init_color();var REQUIRES_ACCOUNT_HINT=`Run \`fimo login\`, then run this command outside the unclaimed site, or delete \`${PROJECT_TOKEN_FILE}\` once the site is claimed.`,PROJECT_TOKEN_REJECTED_HINT=`Sites that are not claimed within ${UNCLAIMED_PLAN.ttlHours} hours are deleted, which also revokes their token, and a site's token stops working ${UNCLAIMED_PLAN.tokenTtlAfterClaimHours} hours after it is claimed. Delete \`${PROJECT_TOKEN_FILE}\` to use your Fimo account here, or create a new site.`;function unclaimedProjectHint(claimUrl){return claimUrl?`Give the claim link to the person who should own this site: ${claimUrl}`:"Open the claim link printed by `fimo init` to claim this site."}__name(unclaimedProjectHint,"unclaimedProjectHint");function isCliAuthError(err){return err instanceof NotAuthenticatedError||err instanceof UnauthorizedError||err instanceof PermissionDeniedError}__name(isCliAuthError,"isCliAuthError");function rethrowCliAuthError(err,beforeThrow){if(isCliAuthError(err))throw beforeThrow?.(err),err}__name(rethrowCliAuthError,"rethrowCliAuthError");function retryCommand(args=process.argv.slice(2)){return["fimo",...args].map(formatShellArg).join(" ")}__name(retryCommand,"retryCommand");function formatCliAuthError(err,opts={}){let p=opts.palette??palette,command=retryCommand(opts.args);if(err instanceof ProjectUnclaimedError)return[`${p.red("\u2717")} ${err.message}`,"",` ${unclaimedProjectHint(err.claimUrl)}`].join(`
2461
2461
  `);if(err instanceof PermissionDeniedError)return[`${p.red("\u2717")} You don't have permission to run this command.`,"",err.required.length?` Missing permission: ${p.bold(err.required.join(", "))}`:" Your role on this site does not allow this action."," Ask a site admin for access, or use an account with a higher role.","",p.dim(` Backend: ${err.apiUrl}`)].join(`
@@ -2522,7 +2522,7 @@ return __eta.res;
2522
2522
  `)}}return returnStr}__name(compileBody,"compileBody");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)}__name(trimWS,"trimWS");var escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function replaceChar(s){return escMap[s]}__name(replaceChar,"replaceChar");function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}__name(XMLEscape,"XMLEscape");var defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val=>String(val),"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;function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");function getLineNo(str,index){return str.slice(0,index).split(`
2523
2523
  `).length}__name(getLineNo,"getLineNo");function parse3(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i2=0;i2<config.plugins.length;i2++){let plugin=config.plugins[i2];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
2524
2524
  `).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 i2=0;i2<config.plugins.length;i2++){let plugin=config.plugins[i2];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}__name(parse3,"parse");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+"'")}}__name(handleCache,"handleCache");function render(template,data,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,data,options)}__name(render,"render");function renderAsync(template,data,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,data,options);return Promise.resolve(res)}__name(renderAsync,"renderAsync");function renderString(template,data){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data)}__name(renderString,"renderString");function renderStringAsync(template,data){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data)}__name(renderStringAsync,"renderStringAsync");var 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=parse3,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)}}};function readFile2(path52){let res="";try{res=fs20.readFileSync(path52,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path52}`):err}return res}__name(readFile2,"readFile");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+=path18.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=path18.join(views,formattedPath)}else resolvedFilePath=path18.join(path18.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path18.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`)}__name(resolvePath2,"resolvePath");function dirIsChild(parent,dir){let relative3=path18.relative(parent,dir);return relative3&&!relative3.startsWith("..")&&!path18.isAbsolute(relative3)}__name(dirIsChild,"dirIsChild");var 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 fileURLToPath5}from"node:url";var HERE=dirname3(fileURLToPath5(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}__name(assetPath,"assetPath");var FORMS_REL="src/forms";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}__name(getFormFiles,"getFormFiles");function readForm(path52){try{return JSON.parse(readFileSync4(path52,"utf-8"))}catch{return null}}__name(readForm,"readForm");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(`
2525
- `)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");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}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");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.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");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"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log2=__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)},files2=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files2){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++,log2(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log2(`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"),log2(`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++,log2(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log2(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__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 z144}from"zod";var 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=z144.object({uid:z144.string().min(1),name:z144.string().min(1).optional(),isSingleton:z144.boolean().optional(),i18n:z144.object({enabled:z144.boolean().optional()}).optional(),description:z144.string().optional(),groups:z144.array(z144.object({id:z144.string().min(1),label:z144.string().min(1),default:z144.boolean().optional()}).strict()).optional(),fields:z144.record(z144.string(),z144.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"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");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}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");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))}__name(packageExportsSubpath,"packageExportsSubpath");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}}__name(readProjectPackage,"readProjectPackage");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"),"."),providesLegacyNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-next":"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"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");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)}__name(templatePath,"templatePath");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.providesLegacyNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-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"||runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:`${runtimeImport}/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}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path52 of schemaFiles){let fileUid=basename(path52,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path52)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path52,"utf-8"))}catch(error){errors.push(`${basename(path52)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path52)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path52)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path52)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue2=>`${issue2.path.join(".")||"schema"}: ${issue2.message}`).join("; ");errors.push(`${basename(path52)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path52)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
2525
+ `)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");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}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");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.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");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"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log2=__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)},files2=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files2){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++,log2(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log2(`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"),log2(`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++,log2(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log2(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__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 z145}from"zod";var 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=z145.object({uid:z145.string().min(1),name:z145.string().min(1).optional(),isSingleton:z145.boolean().optional(),i18n:z145.object({enabled:z145.boolean().optional()}).optional(),description:z145.string().optional(),groups:z145.array(z145.object({id:z145.string().min(1),label:z145.string().min(1),default:z145.boolean().optional()}).strict()).optional(),fields:z145.record(z145.string(),z145.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"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");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}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");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))}__name(packageExportsSubpath,"packageExportsSubpath");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}}__name(readProjectPackage,"readProjectPackage");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"),"."),providesLegacyNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-next":"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"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");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)}__name(templatePath,"templatePath");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.providesLegacyNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-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"||runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:`${runtimeImport}/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}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path52 of schemaFiles){let fileUid=basename(path52,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path52)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path52,"utf-8"))}catch(error){errors.push(`${basename(path52)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path52)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path52)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path52)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue2=>`${issue2.path.join(".")||"schema"}: ${issue2.message}`).join("; ");errors.push(`${basename(path52)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path52)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
2526
2526
  - ${errors.join(`
2527
2527
  - `)}
2528
2528
  No generated files were changed.`);return schemas3}__name(loadSchemas,"loadSchemas");function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`