fimo 2.11.0-staging.5 → 2.11.0-staging.6

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
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __fimoCreateRequire } from 'node:module';
3
3
  const require = __fimoCreateRequire(import.meta.url);
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_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_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,"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,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","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_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),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z11.enum(AUDIT_ACTOR_KINDS)}});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"],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 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=z15.iso.datetime({offset:!0}).pipe(z15.coerce.date()),OpsRecentChatInputSchema=z15.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z15.string().trim().min(1).max(255).optional(),limit:z15.coerce.number().int().min(1).max(200).default(100),cursor:z15.string().trim().min(1).max(2e3).optional(),slim:z15.boolean().default(!0),reason:z15.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=z15.object({id:z15.string(),threadId:z15.string(),threadKind:z15.string(),providerMessageId:z15.string().nullable(),invocationId:z15.string().nullable(),env:z15.string().nullable(),role:z15.string(),parts:z15.array(z15.record(z15.string(),z15.unknown())),metadata:z15.object({status:z15.string().optional(),traceUrl:z15.string().optional(),externalFileChanges:z15.array(z15.unknown()).optional()}),stats:z15.object({toolCount:z15.number().int().nonnegative(),failedToolCount:z15.number().int().nonnegative()}),createdAt:z15.iso.datetime({offset:!0}),project:z15.object({id:z15.string(),name:z15.string(),displayName:z15.string().nullable(),organizationId:z15.string().nullable()})}),OpsRecentChatResponseSchema=z15.object({target:z15.object({backendProfile:OpsBackendProfileSchema,projectEnv:z15.string().nullable()}),window:z15.object({from:z15.iso.datetime({offset:!0}),to:z15.iso.datetime({offset:!0})}),messages:z15.object({items:z15.array(OpsRecentChatMessageSchema),nextCursor:z15.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 z16}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_chat_dto();init_ops();init_create_dto();init_args();init_types();init_shared();invocation=z16.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z16.string().trim().min(1).max(255).describe("Braintrust span id"),OpsChatViewSchema=z16.enum(["tool-calls","app-calls","turns","slices"]),OpsChatViewsInputSchema=OpsRecentChatInputSchema.safeExtend({view:OpsChatViewSchema}),viewIds=z16.object({threadId:z16.string(),invocationId:z16.string().nullable(),projectId:z16.string(),messageId:z16.string()}),ending={terminal:z16.string(),terminalReason:z16.string().nullable()},toolCallRow=viewIds.extend({tool:z16.string(),subcommand:z16.string().nullable(),state:z16.string().nullable(),failed:z16.boolean(),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative(),recoveredNext:z16.boolean().nullable()}),appCallRow=viewIds.extend({routineId:z16.string().nullable(),via:z16.string(),integrationId:z16.string().nullable(),appTool:z16.string().nullable(),withApproval:z16.boolean(),outcome:z16.enum(["ok","failed","approval_required","blocked","pending"]),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative()}),turnRow=viewIds.extend({...ending,userMessageId:z16.string().nullable(),failureCategory:z16.enum(["expected_billing_stop","expected_model_refusal","expected_cancellation","workspace_failure","provider_model_failure","unknown_failure"]).nullable(),changes:z16.string().nullable(),mergeState:z16.string().nullable(),validation:z16.string().nullable(),publication:z16.string().nullable(),stepCount:z16.number().int().nonnegative(),toolCount:z16.number().int().nonnegative(),failedToolCount:z16.number().int().nonnegative(),hasTextReply:z16.boolean(),fimoAuthored:z16.boolean().nullable()}),turnSlice=viewIds.extend({...ending,previousUserAsk:z16.string().max(300),previousAgentWords:z16.string().max(500),userMessage:z16.string().max(1500),agentReply:z16.string().max(1305),failedToolCalls:z16.array(z16.object({tool:z16.string(),errorSignature:z16.string()})).max(6)}),viewEnvelope=z16.object({target:z16.object({backendProfile:OpsBackendProfileSchema,projectEnv:z16.string().nullable()}),window:z16.object({from:z16.iso.datetime({offset:!0}),to:z16.iso.datetime({offset:!0})})}),OpsChatViewsResponseDTO=createDTO(z16.discriminatedUnion("view",[viewEnvelope.extend({view:z16.literal("tool-calls"),messages:z16.object({items:z16.array(toolCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("app-calls"),messages:z16.object({items:z16.array(appCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("turns"),messages:z16.object({items:z16.array(turnRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("slices"),messages:z16.object({items:z16.array(turnSlice),nextCursor:z16.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:z16.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:z16.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:z16.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:z16.object({project:opsArgs.project,spec:z16.record(z16.string(),z16.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{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:z16.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z16.uuid().optional().describe("Chat thread id"),agent:z16.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z16.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z16.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:z16.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:z16.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:z16.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:z16.object({invocation,span,maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z16.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:z16.object({invocation,span,message:z16.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z16.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:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z16.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 z17}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:z17.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z17.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:z17.object({thread:z17.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z18}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=z18.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:z18.object({org:opsArgs.org})},{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z18.object({customer:z18.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:z18.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:z18.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:z18.object({org:opsArgs.org,kind:z18.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:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z18.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z18.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:z18.object({orgs:z18.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:z18.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:z18.object({org:opsArgs.org,deadline:z18.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:z18.object({org:opsArgs.org,coupon:z18.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:z18.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:z18.object({batchSize:z18.coerce.number().int().min(1).max(100).default(50),concurrency:z18.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:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.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:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.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:z18.object({state:z18.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:z18.object({dispatches:z18.array(z18.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:z18.object({dispatch:z18.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:z18.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:z18.object({source:z18.string().trim().min(1).max(100),meter:z18.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:z18.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:z18.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 z19}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:z19.object({query:opsArgs.query,kind:z19.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:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z19.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z19.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 z20}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:z20.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:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z20.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z20.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:z20.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:z20.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:z20.object({...window2,model:z20.string().trim().min(1).max(200).optional(),provider:z20.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z20.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:z20.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z20.coerce.number().int().min(1).max(100).default(25),sampleChars:z20.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:z20.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:z20.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z20.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:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z20.coerce.number().int().min(1).max(25).default(10),calibrate:z20.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:z20.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:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z20.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:z20.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:z20.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z20.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:z20.object({project:opsArgs.project,checkProvider:z20.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:z20.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:z20.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z20.uuid().optional().describe("Schedule id"),run:z20.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:z20.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:z20.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 z21}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:z21.object({project:opsArgs.project.optional(),stuck:z21.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z21.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:z21.object({merge:z21.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:z21.object({merge:z21.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:z21.object({merge:z21.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 z22}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=z22.enum(OPS_SIGNAL_CASE_STATES),OpsSignatureHashSchema=z22.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=z22.enum(OPS_WATCH_STATES),OpsWatchCadenceSchema=z22.enum(OPS_WATCH_CADENCES),OpsWatchResultSchema=z22.enum(OPS_WATCH_RESULTS),OpsWatchModelSchema=z22.enum(OPS_WATCH_MODELS),OpsWatchEffortSchema=z22.enum(OPS_WATCH_EFFORTS),OpsWatchSlugSchema=z22.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Expected a kebab-case slug").max(80),day2=z22.iso.date(),watchText=__name(max=>z22.string().trim().min(1).max(max),"watchText"),watchRef=z22.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:z22.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:z22.object({check:z22.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:z22.object({state:OpsSignalCaseStateSchema.optional().describe("Only cases in this state"),check:z22.string().trim().min(1).max(160).optional().describe("Only cases from this check id, or from every check under a prefix ending in /"),minSeverity:z22.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:z22.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:z22.object({case:z22.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:z22.object({case:z22.uuid().describe("Case id"),state:OpsSignalCaseStateSchema.optional(),decisionReason:z22.string().trim().min(1).max(2e3).optional().describe("Why this decision; required to accept, snooze or dismiss. Shown on the finding"),ceiling:z22.number().nonnegative().optional().describe("For accepted: reopen above this metric"),snoozedUntil:z22.iso.datetime().optional().describe("For snoozed: reopen after this time"),linearIssue:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional(),prUrl:z22.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:z22.object({state:z22.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:z22.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:z22.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:z22.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:z22.array(watchText(1e3)).min(1).max(20).optional().describe("The calls to judge, asked both ways (repeatable). Required to create"),reads:z22.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:z22.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:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional().describe("The issue that owns the watch"),prUrls:z22.array(z22.url()).max(20).optional().describe("The PRs it watches (repeatable)"),state:z22.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:z22.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:z22.object({watch:watchRef,result:OpsWatchResultSchema,summary:watchText(4e3).describe("What the run found, with counts and their denominator. No customer text"),judged:z22.number().int().nonnegative().optional().describe("Cases judged"),right:z22.number().int().nonnegative().optional(),wrong:z22.number().int().nonnegative().optional(),unclear:z22.number().int().nonnegative().optional(),caseIds:z22.array(z22.uuid()).max(50).optional().describe("Alerts the run opened or linked (repeatable)"),links:z22.array(z22.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:z22.number().nonnegative().optional().describe("What the run cost at list price"),close:z22.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 z23}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=z23.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z23.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:z23.object({channel,message:z23.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z23.email().optional().describe("email: override the recipient"),subject:z23.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z23.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z23.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z23.array(z23.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z23.array(z23.email()).max(50).optional(),bccEmails:z23.array(z23.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:z23.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:z23.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z23.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 z24}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=z24.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z24.array(z24.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z24.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:z24.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:z24.object({...logFilters,at:z24.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z24.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:z24.object({trace:z24.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:z24.object({project:opsArgs.project.optional(),search:z24.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z24.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z24.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:z24.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:z24.object({event:z24.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:z24.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:z24.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:z24.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 z25}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:z25.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:z25.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:z25.object({org:opsArgs.org,feature:z25.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z25.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:z25.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.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:z25.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:z25.object({org:opsArgs.org,credits:z25.coerce.number().int().positive().describe("Number of credits"),type:z25.enum(["free","purchase"]).default("free"),amountCents:z25.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z25.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z25.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:z25.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z26}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:z26.object({dashboard:z26.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:z26.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:z26.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:z26.object({pooled:z26.array(z26.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:z26.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:z26.object({message:z26.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:z26.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:z26.object({message:z26.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:z26.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:z26.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({event:z26.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:z26.object({status:z26.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:z26.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:z26.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:z26.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:z26.object({query:z26.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 z27}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:z27.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:z27.object({query:opsArgs.query.optional().describe("Project name, display name, id or organization name"),databaseQuota:z27.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:z27.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:z27.object({project:opsArgs.project,thread:z27.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:z27.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:z27.object({project:opsArgs.project,env:envMain,path:z27.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:z27.object({project:opsArgs.project,env:envMain,pattern:z27.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:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(200).describe("Regular expression"),include:z27.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z27.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:z27.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:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z27.string().max(256*1024).describe("The exact desired file contents"),overwrite:z27.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:z27.object({project:opsArgs.project,env:envMain,version:z27.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:z27.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:z27.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:z27.object({project:opsArgs.project,domain:z27.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:z27.object({project:opsArgs.project,env:envMain,migration:z27.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:z27.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project,type:z27.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:z27.object({project:opsArgs.project,env:envMain,version:z27.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:z27.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:z27.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:z27.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:z27.object({project:opsArgs.project})}]}});import{z as z28}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=z28.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:z28.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),status:z28.enum(OPS_SANDBOX_STATUSES).optional().describe("Only sandboxes in this provider status"),owner:z28.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:z28.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:z28.object({sandbox:sandboxArg,process:z28.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:z28.object({sandbox:sandboxArg,command:z28.string().trim().min(1).max(4e3).describe("Shell command, run with `sh -c` in the project directory"),timeout:z28.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:z28.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:z28.object({sandbox:sandboxArg,discardUnsaved:z28.boolean().default(!1).describe("Delete even though the plan shows unsaved work or a running agent on it")})}]}});import{z as z29}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=z29.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z29.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z29.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z29.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z29.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z29.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z29.enum(["user","agent","system"]),SupportReportTagSchema=z29.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z29.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z29.object({organization:z29.object({id:z29.string().trim().min(1).max(255),name:z29.string().trim().max(240).optional()}),project:z29.object({id:z29.uuid(),name:z29.string().trim().max(240).optional(),createdAt:z29.coerce.date().optional()}).optional(),environment:z29.string().trim().max(255).optional(),clientVersion:z29.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z29.object({message:z29.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z29.string().trim().max(200).optional(),limit:z29.coerce.number().int().min(1).max(100).default(50),offset:z29.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z29.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z29.uuid().nullable().optional(),note:z29.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=z29.object({message:z29.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z29.object({kind:SupportReportLinkKindSchema,label:z29.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z29.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z29.object({kind:SupportReportActorKindSchema,id:z29.string().nullable(),name:z29.string().nullable()}),SupportReportLinkDTOSchema=z29.object({id:z29.uuid(),kind:SupportReportLinkKindSchema,label:z29.string(),url:SupportReportHttpUrlSchema,externalId:z29.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z29.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z29.object({id:z29.uuid(),kind:SupportReportEventKindSchema,body:z29.string().nullable(),metadata:z29.record(z29.string(),z29.unknown()),actor:SupportReportActorDTOSchema,createdAt:z29.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z29.object({id:z29.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z29.array(z29.string()),source:SupportReportSourceSchema,message:z29.string(),reporter:z29.object({id:z29.string().nullable(),name:z29.string().nullable(),email:z29.string().nullable()}),organization:z29.object({id:z29.string().nullable(),name:z29.string()}),project:z29.object({id:z29.uuid().nullable(),name:z29.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z29.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z29.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z29.string().nullable(),deliveredAt:z29.coerce.date().nullable()}).nullable(),duplicateOfReportId:z29.uuid().nullable(),resolvedAt:z29.coerce.date().nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z29.string().nullable(),clientVersion:z29.string().nullable(),links:z29.array(SupportReportLinkDTOSchema),events:z29.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z29.object({reports:z29.array(SupportReportSummaryDTOSchema),total:z29.number().int().nonnegative(),statusCounts:z29.object({new:z29.number().int().nonnegative(),in_progress:z29.number().int().nonnegative(),waiting:z29.number().int().nonnegative(),resolved:z29.number().int().nonnegative(),duplicate:z29.number().int().nonnegative(),irrelevant:z29.number().int().nonnegative(),ignored:z29.number().int().nonnegative()}),limit:z29.number().int().positive(),offset:z29.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z29.object({id:z29.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z29.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z30}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=z30.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:z30.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z30.string().trim().min(1).max(50).optional(),search:z30.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z30.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:z30.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:z30.object({report,note:z30.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:z30.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z30.array(z30.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z30.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z30.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:z30.object({report,message:z30.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:z30.object({report,kind:SupportReportLinkKindSchema,label:z30.string().trim().min(1).max(240),url:z30.url({protocol:/^https?$/}).max(2e3),externalId:z30.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:z30.object({report,link:z30.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:z30.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:z30.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z30.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:z30.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:z30.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:z30.object({issue:pylonIssue,message:z30.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z31}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:z31.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:z31.object({user:opsArgs.user.optional(),active:z31.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:z31.object({session:z31.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z32}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=z32.array(z32.record(z32.string(),z32.unknown())).max(100),versions=z32.array(z32.string().trim().min(1).max(120)).max(100),detectionQueries=z32.array(z32.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:z32.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:z32.object({project:opsArgs.project,importance:z32.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z32.string().trim().max(120).optional(),packageManager:z32.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z32.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z32.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z32.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:z32.object({project:opsArgs.project,change:z32.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z32.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:z32.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:z32.object({project:opsArgs.project,title:z32.string().trim().min(1).max(240),userReport:z32.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:z32.object({investigation:z32.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z32.string().trim().max(1e4).optional(),outcome:z32.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:z32.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:z32.object({fingerprint:z32.string().trim().min(1).max(240),title:z32.string().trim().min(1).max(240),description:z32.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z32.string().trim().min(1).max(64).optional(),workaround:z32.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:z32.object({knownIssue:z32.uuid().describe("Known issue id"),title:z32.string().trim().min(1).max(240).optional(),description:z32.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z32.string().trim().min(1).max(64).optional(),workaround:z32.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)}});import{z as z33}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,SitePagePathSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,AgentBlockSchema,PreviewBlockSchema,SearchImageUrlSchema,SearchPreviewBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,FormChoicesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,CHAT_FORM_INTERNAL_NOTE_MAX,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z33.object({kind:z33.literal("say"),label:z33.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z33.string().min(1).max(240).optional(),message:z33.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z33.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z33.discriminatedUnion("command",[z33.object({kind:z33.literal("app"),command:z33.literal("publish")}).strict(),z33.object({kind:z33.literal("app"),command:z33.literal("connect"),integrationKey:z33.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z33.object({fallback:z33.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z33.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z33.literal("choices"),text:z33.string().max(500).optional(),actions:z33.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),SitePagePathSchema=z33.string().trim().max(200).regex(/^\/(?!\/)/,"A page starts with one /."),TableRowTargetSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("entry"),collection:z33.string().min(1).max(80),entryId:z33.string().min(1).max(120)}),z33.object({kind:z33.literal("asset"),assetId:z33.string().min(1).max(120)}),z33.object({kind:z33.literal("url"),url:z33.url({protocol:/^https$/}).max(2e3)}),z33.object({kind:z33.literal("routine"),routineId:z33.string().min(1).max(120)})]),TableBlockSchema=BlockBaseSchema.extend({type:z33.literal("table"),columns:z33.array(z33.object({label:z33.string().min(1).max(24)})).min(2).max(4),rows:z33.array(z33.object({cells:z33.array(z33.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:z33.literal("cards"),layout:z33.enum(["rail","stack"]).optional(),items:z33.array(z33.object({title:z33.string().min(1).max(60),subtitle:z33.string().min(1).max(120).optional(),imageUrl:z33.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z33.literal("entry"),label:z33.string().min(1).max(80),collection:z33.string().min(1).max(80),entryId:z33.string().min(1).max(120),path:z33.string().min(1).max(120).optional()}),DraftsBlockSchema=BlockBaseSchema.extend({type:z33.literal("drafts"),items:z33.array(z33.object({label:z33.string().trim().min(1).max(80),collection:z33.string().min(1).max(80),entryId:z33.string().min(1).max(120).optional(),reviewId:z33.uuid().optional(),routineId:z33.string().min(1).max(120).optional()}).refine(item=>!!item.entryId==!!item.reviewId,{message:"A draft that exists names both its entryId and the reviewId from request_review."})).min(1).max(20)}),AssetsBlockSchema=BlockBaseSchema.extend({type:z33.literal("assets"),items:z33.array(z33.object({url:z33.url({protocol:/^https$/}).max(2e3),alt:z33.string().min(1).max(120),label:z33.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z33.literal("callout"),title:z33.string().min(1).max(80),text:z33.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z33.literal("stat"),items:z33.array(z33.object({label:z33.string().min(1).max(24),value:z33.string().min(1).max(16),delta:z33.string().min(1).max(12).optional(),tone:z33.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z33.literal("chart"),unit:z33.string().min(1).max(12).optional(),kind:z33.enum(["bars","columns"]).optional(),max:z33.number().finite().positive().max(1e9).optional(),highlight:z33.string().min(1).max(12).optional(),points:z33.array(z33.object({label:z33.string().min(1).max(12),value:z33.number().finite().min(0).max(1e9),note:z33.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:z33.literal("before_after"),title:z33.string().min(1).max(80),meta:z33.string().min(1).max(80).optional(),rows:z33.array(z33.object({label:z33.string().min(1).max(24),before:z33.string().max(600),after:z33.string().max(600),showLength:z33.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:z33.literal("agent"),agentId:z33.string().uuid(),view:z33.enum(["compact","full"]).optional()}),PreviewBlockSchema=BlockBaseSchema.extend({type:z33.literal("preview"),path:SitePagePathSchema.optional(),detail:z33.string().trim().min(1).max(80).optional()}),SearchImageUrlSchema=z33.url({protocol:/^https$/}).max(2e3),SearchPreviewBlockSchema=BlockBaseSchema.extend({type:z33.literal("search_preview"),url:z33.string().trim().min(1).max(200),pageTitle:z33.string().trim().min(1).max(200),description:z33.string().trim().min(1).max(500),siteName:z33.string().trim().min(1).max(60).optional(),faviconUrl:SearchImageUrlSchema.optional(),breadcrumbs:z33.array(z33.string().trim().min(1).max(40)).min(1).max(4).optional(),date:z33.string().trim().min(1).max(24).optional(),imageUrl:SearchImageUrlSchema.optional(),video:z33.object({duration:z33.string().trim().min(1).max(8),moments:z33.number().int().min(1).max(20).optional()}).optional(),rating:z33.object({value:z33.number().min(0).max(5),count:z33.string().trim().min(1).max(16).optional()}).optional(),attributes:z33.array(z33.string().trim().min(1).max(40)).min(1).max(4).optional(),prosCons:z33.array(z33.string().trim().min(1).max(48)).min(1).max(4).optional(),readMore:z33.boolean().optional(),sitelinks:z33.array(z33.object({title:z33.string().trim().min(1).max(60),description:z33.string().trim().min(1).max(120).optional(),path:SitePagePathSchema.optional()})).min(1).max(6).optional(),sitelinksLayout:z33.enum(["rows","chips"]).optional(),query:z33.string().trim().min(1).max(80).optional()}),ChatDisplayBlockSchema=z33.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z33.literal("text"),placeholder:z33.string().min(1).max(120).optional(),multiline:z33.boolean().optional()}).strict(),ChatFormStepIdSchema=z33.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z33.object({id:ChatFormStepIdSchema,token:z33.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z33.string().trim().min(1).max(60),reason:z33.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z33.literal("capabilities"),items:z33.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:z33.array(BlockActionSchema).min(2,"A choices step needs 2 to 8 options.").max(8,"A choices step needs 2 to 8 options.")}),ChatFormBodySchema=z33.discriminatedUnion("type",[FormChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z33.object({id:ChatFormStepIdSchema.optional(),question:z33.string().min(1).max(500),header:z33.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z33.boolean().optional(),recommended:z33.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:z33.literal("form"),steps:z33.array(ChatFormStepSchema).min(1).max(4),internalNote:z33.string().trim().min(1).max(CHAT_FORM_INTERNAL_NOTE_MAX).optional()}),ChatBlockSchema=z33.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema,AgentBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z33.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z33.object({stepId:ChatFormStepIdSchema.optional(),header:z33.string().min(1).max(25),question:z33.string().min(1).max(500),answer:z33.string().min(1),selectedLabels:z33.array(z33.string().min(1).max(120)).max(8),freeText:z33.string(),skipped:z33.boolean()}),ChatFormAnswerMetadataSchema=z33.object({toolCallId:z33.string().max(255).optional(),shortTitle:z33.string().max(80).optional(),questions:z33.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z33.object({version:z33.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z33.object({version:z33.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z33.string().min(1).max(255),partial:z33.boolean().optional()})}});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(`
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_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"],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 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=z15.iso.datetime({offset:!0}).pipe(z15.coerce.date()),OpsRecentChatInputSchema=z15.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z15.string().trim().min(1).max(255).optional(),limit:z15.coerce.number().int().min(1).max(200).default(100),cursor:z15.string().trim().min(1).max(2e3).optional(),slim:z15.boolean().default(!0),reason:z15.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=z15.object({id:z15.string(),threadId:z15.string(),threadKind:z15.string(),providerMessageId:z15.string().nullable(),invocationId:z15.string().nullable(),env:z15.string().nullable(),role:z15.string(),parts:z15.array(z15.record(z15.string(),z15.unknown())),metadata:z15.object({status:z15.string().optional(),traceUrl:z15.string().optional(),externalFileChanges:z15.array(z15.unknown()).optional(),userView:z15.object({view:z15.object({at:z15.string(),tab:z15.string().optional(),title:z15.string().optional(),locale:z15.string().optional(),range:z15.string().optional(),unsaved:z15.boolean().optional()}).optional(),tabs:z15.array(z15.object({id:z15.string(),at:z15.string()})).optional()}).optional()}),stats:z15.object({toolCount:z15.number().int().nonnegative(),failedToolCount:z15.number().int().nonnegative()}),createdAt:z15.iso.datetime({offset:!0}),project:z15.object({id:z15.string(),name:z15.string(),displayName:z15.string().nullable(),organizationId:z15.string().nullable()})}),OpsRecentChatResponseSchema=z15.object({target:z15.object({backendProfile:OpsBackendProfileSchema,projectEnv:z15.string().nullable()}),window:z15.object({from:z15.iso.datetime({offset:!0}),to:z15.iso.datetime({offset:!0})}),messages:z15.object({items:z15.array(OpsRecentChatMessageSchema),nextCursor:z15.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 z16}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_chat_dto();init_ops();init_create_dto();init_args();init_types();init_shared();invocation=z16.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z16.string().trim().min(1).max(255).describe("Braintrust span id"),OpsChatViewSchema=z16.enum(["tool-calls","app-calls","turns","slices"]),OpsChatViewsInputSchema=OpsRecentChatInputSchema.safeExtend({view:OpsChatViewSchema}),viewIds=z16.object({threadId:z16.string(),invocationId:z16.string().nullable(),projectId:z16.string(),messageId:z16.string()}),ending={terminal:z16.string(),terminalReason:z16.string().nullable()},toolCallRow=viewIds.extend({tool:z16.string(),subcommand:z16.string().nullable(),state:z16.string().nullable(),failed:z16.boolean(),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative(),recoveredNext:z16.boolean().nullable()}),appCallRow=viewIds.extend({routineId:z16.string().nullable(),via:z16.string(),integrationId:z16.string().nullable(),appTool:z16.string().nullable(),withApproval:z16.boolean(),outcome:z16.enum(["ok","failed","approval_required","blocked","pending"]),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative()}),turnRow=viewIds.extend({...ending,userMessageId:z16.string().nullable(),failureCategory:z16.enum(["expected_billing_stop","expected_model_refusal","expected_cancellation","workspace_failure","provider_model_failure","unknown_failure"]).nullable(),changes:z16.string().nullable(),mergeState:z16.string().nullable(),validation:z16.string().nullable(),publication:z16.string().nullable(),stepCount:z16.number().int().nonnegative(),toolCount:z16.number().int().nonnegative(),failedToolCount:z16.number().int().nonnegative(),hasTextReply:z16.boolean(),fimoAuthored:z16.boolean().nullable()}),turnSlice=viewIds.extend({...ending,previousUserAsk:z16.string().max(300),previousAgentWords:z16.string().max(500),userMessage:z16.string().max(1500),agentReply:z16.string().max(1305),failedToolCalls:z16.array(z16.object({tool:z16.string(),errorSignature:z16.string()})).max(6)}),viewEnvelope=z16.object({target:z16.object({backendProfile:OpsBackendProfileSchema,projectEnv:z16.string().nullable()}),window:z16.object({from:z16.iso.datetime({offset:!0}),to:z16.iso.datetime({offset:!0})})}),OpsChatViewsResponseDTO=createDTO(z16.discriminatedUnion("view",[viewEnvelope.extend({view:z16.literal("tool-calls"),messages:z16.object({items:z16.array(toolCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("app-calls"),messages:z16.object({items:z16.array(appCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("turns"),messages:z16.object({items:z16.array(turnRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("slices"),messages:z16.object({items:z16.array(turnSlice),nextCursor:z16.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:z16.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:z16.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:z16.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:z16.object({project:opsArgs.project,spec:z16.record(z16.string(),z16.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{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:z16.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z16.uuid().optional().describe("Chat thread id"),agent:z16.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z16.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z16.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:z16.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:z16.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:z16.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:z16.object({invocation,span,maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z16.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:z16.object({invocation,span,message:z16.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z16.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:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z16.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 z17}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:z17.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z17.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:z17.object({thread:z17.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z18}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=z18.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:z18.object({org:opsArgs.org})},{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z18.object({customer:z18.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:z18.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:z18.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:z18.object({org:opsArgs.org,kind:z18.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:z18.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:z18.boolean().optional().describe("Only referrals with an owed, unpaid credit"),side:z18.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:z18.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z18.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:z18.object({orgs:z18.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:z18.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:z18.object({org:opsArgs.org,deadline:z18.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:z18.object({org:opsArgs.org,coupon:z18.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:z18.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:z18.object({batchSize:z18.coerce.number().int().min(1).max(100).default(50),concurrency:z18.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:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.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:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.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:z18.object({state:z18.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:z18.object({dispatches:z18.array(z18.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:z18.object({dispatch:z18.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:z18.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:z18.object({source:z18.string().trim().min(1).max(100),meter:z18.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:z18.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:z18.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 z19}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:z19.object({query:opsArgs.query,kind:z19.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:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z19.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z19.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 z20}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:z20.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:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z20.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z20.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:z20.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:z20.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:z20.object({...window2,model:z20.string().trim().min(1).max(200).optional(),provider:z20.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z20.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:z20.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z20.coerce.number().int().min(1).max(100).default(25),sampleChars:z20.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:z20.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:z20.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z20.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:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z20.coerce.number().int().min(1).max(25).default(10),calibrate:z20.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:z20.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:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z20.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:z20.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:z20.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z20.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:z20.object({project:opsArgs.project,checkProvider:z20.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:z20.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:z20.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z20.uuid().optional().describe("Schedule id"),run:z20.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:z20.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:z20.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 z21}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:z21.object({project:opsArgs.project.optional(),stuck:z21.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z21.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:z21.object({merge:z21.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:z21.object({merge:z21.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:z21.object({merge:z21.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 z22}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=z22.enum(OPS_SIGNAL_CASE_STATES),OpsSignatureHashSchema=z22.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=z22.enum(OPS_WATCH_STATES),OpsWatchCadenceSchema=z22.enum(OPS_WATCH_CADENCES),OpsWatchResultSchema=z22.enum(OPS_WATCH_RESULTS),OpsWatchModelSchema=z22.enum(OPS_WATCH_MODELS),OpsWatchEffortSchema=z22.enum(OPS_WATCH_EFFORTS),OpsWatchSlugSchema=z22.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Expected a kebab-case slug").max(80),day2=z22.iso.date(),watchText=__name(max=>z22.string().trim().min(1).max(max),"watchText"),watchRef=z22.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:z22.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:z22.object({check:z22.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:z22.object({state:OpsSignalCaseStateSchema.optional().describe("Only cases in this state"),check:z22.string().trim().min(1).max(160).optional().describe("Only cases from this check id, or from every check under a prefix ending in /"),minSeverity:z22.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:z22.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:z22.object({case:z22.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:z22.object({case:z22.uuid().describe("Case id"),state:OpsSignalCaseStateSchema.optional(),decisionReason:z22.string().trim().min(1).max(2e3).optional().describe("Why this decision; required to accept, snooze or dismiss. Shown on the finding"),ceiling:z22.number().nonnegative().optional().describe("For accepted: reopen above this metric"),snoozedUntil:z22.iso.datetime().optional().describe("For snoozed: reopen after this time"),linearIssue:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional(),prUrl:z22.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:z22.object({state:z22.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:z22.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:z22.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:z22.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:z22.array(watchText(1e3)).min(1).max(20).optional().describe("The calls to judge, asked both ways (repeatable). Required to create"),reads:z22.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:z22.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:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional().describe("The issue that owns the watch"),prUrls:z22.array(z22.url()).max(20).optional().describe("The PRs it watches (repeatable)"),state:z22.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:z22.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:z22.object({watch:watchRef,result:OpsWatchResultSchema,summary:watchText(4e3).describe("What the run found, with counts and their denominator. No customer text"),judged:z22.number().int().nonnegative().optional().describe("Cases judged"),right:z22.number().int().nonnegative().optional(),wrong:z22.number().int().nonnegative().optional(),unclear:z22.number().int().nonnegative().optional(),caseIds:z22.array(z22.uuid()).max(50).optional().describe("Alerts the run opened or linked (repeatable)"),links:z22.array(z22.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:z22.number().nonnegative().optional().describe("What the run cost at list price"),close:z22.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 z23}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=z23.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z23.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:z23.object({channel,message:z23.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z23.email().optional().describe("email: override the recipient"),subject:z23.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z23.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z23.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z23.array(z23.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z23.array(z23.email()).max(50).optional(),bccEmails:z23.array(z23.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:z23.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:z23.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z23.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 z24}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=z24.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z24.array(z24.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z24.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:z24.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:z24.object({...logFilters,at:z24.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z24.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:z24.object({trace:z24.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:z24.object({project:opsArgs.project.optional(),search:z24.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z24.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z24.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:z24.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:z24.object({event:z24.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:z24.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:z24.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:z24.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 z25}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:z25.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:z25.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:z25.object({org:opsArgs.org,feature:z25.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z25.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:z25.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.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:z25.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:z25.object({org:opsArgs.org,credits:z25.coerce.number().int().positive().describe("Number of credits"),type:z25.enum(["free","purchase"]).default("free"),amountCents:z25.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z25.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z25.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:z25.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z26}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:z26.object({dashboard:z26.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:z26.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:z26.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:z26.object({pooled:z26.array(z26.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:z26.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:z26.object({message:z26.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:z26.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:z26.object({message:z26.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:z26.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:z26.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({event:z26.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:z26.object({status:z26.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:z26.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:z26.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:z26.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:z26.object({query:z26.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 z27}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:z27.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:z27.object({query:opsArgs.query.optional().describe("Project name, display name, id or organization name"),databaseQuota:z27.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:z27.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:z27.object({project:opsArgs.project,thread:z27.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:z27.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:z27.object({project:opsArgs.project,env:envMain,path:z27.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:z27.object({project:opsArgs.project,env:envMain,pattern:z27.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:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(200).describe("Regular expression"),include:z27.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z27.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:z27.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:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z27.string().max(256*1024).describe("The exact desired file contents"),overwrite:z27.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:z27.object({project:opsArgs.project,env:envMain,version:z27.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:z27.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:z27.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:z27.object({project:opsArgs.project,domain:z27.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:z27.object({project:opsArgs.project,env:envMain,migration:z27.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:z27.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project,type:z27.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:z27.object({project:opsArgs.project,env:envMain,version:z27.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:z27.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:z27.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:z27.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:z27.object({project:opsArgs.project})}]}});import{z as z28}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=z28.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:z28.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),status:z28.enum(OPS_SANDBOX_STATUSES).optional().describe("Only sandboxes in this provider status"),owner:z28.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:z28.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:z28.object({sandbox:sandboxArg,process:z28.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:z28.object({sandbox:sandboxArg,command:z28.string().trim().min(1).max(4e3).describe("Shell command, run with `sh -c` in the project directory"),timeout:z28.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:z28.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:z28.object({sandbox:sandboxArg,discardUnsaved:z28.boolean().default(!1).describe("Delete even though the plan shows unsaved work or a running agent on it")})}]}});import{z as z29}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=z29.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z29.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z29.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z29.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z29.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z29.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z29.enum(["user","agent","system"]),SupportReportTagSchema=z29.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z29.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z29.object({organization:z29.object({id:z29.string().trim().min(1).max(255),name:z29.string().trim().max(240).optional()}),project:z29.object({id:z29.uuid(),name:z29.string().trim().max(240).optional(),createdAt:z29.coerce.date().optional()}).optional(),environment:z29.string().trim().max(255).optional(),clientVersion:z29.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z29.object({message:z29.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z29.string().trim().max(200).optional(),limit:z29.coerce.number().int().min(1).max(100).default(50),offset:z29.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z29.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z29.uuid().nullable().optional(),note:z29.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=z29.object({message:z29.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z29.object({kind:SupportReportLinkKindSchema,label:z29.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z29.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z29.object({kind:SupportReportActorKindSchema,id:z29.string().nullable(),name:z29.string().nullable()}),SupportReportLinkDTOSchema=z29.object({id:z29.uuid(),kind:SupportReportLinkKindSchema,label:z29.string(),url:SupportReportHttpUrlSchema,externalId:z29.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z29.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z29.object({id:z29.uuid(),kind:SupportReportEventKindSchema,body:z29.string().nullable(),metadata:z29.record(z29.string(),z29.unknown()),actor:SupportReportActorDTOSchema,createdAt:z29.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z29.object({id:z29.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z29.array(z29.string()),source:SupportReportSourceSchema,message:z29.string(),reporter:z29.object({id:z29.string().nullable(),name:z29.string().nullable(),email:z29.string().nullable()}),organization:z29.object({id:z29.string().nullable(),name:z29.string()}),project:z29.object({id:z29.uuid().nullable(),name:z29.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z29.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z29.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z29.string().nullable(),deliveredAt:z29.coerce.date().nullable()}).nullable(),duplicateOfReportId:z29.uuid().nullable(),resolvedAt:z29.coerce.date().nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z29.string().nullable(),clientVersion:z29.string().nullable(),links:z29.array(SupportReportLinkDTOSchema),events:z29.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z29.object({reports:z29.array(SupportReportSummaryDTOSchema),total:z29.number().int().nonnegative(),statusCounts:z29.object({new:z29.number().int().nonnegative(),in_progress:z29.number().int().nonnegative(),waiting:z29.number().int().nonnegative(),resolved:z29.number().int().nonnegative(),duplicate:z29.number().int().nonnegative(),irrelevant:z29.number().int().nonnegative(),ignored:z29.number().int().nonnegative()}),limit:z29.number().int().positive(),offset:z29.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z29.object({id:z29.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z29.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z30}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=z30.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:z30.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z30.string().trim().min(1).max(50).optional(),search:z30.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z30.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:z30.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:z30.object({report,note:z30.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:z30.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z30.array(z30.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z30.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z30.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:z30.object({report,message:z30.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:z30.object({report,kind:SupportReportLinkKindSchema,label:z30.string().trim().min(1).max(240),url:z30.url({protocol:/^https?$/}).max(2e3),externalId:z30.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:z30.object({report,link:z30.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:z30.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:z30.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z30.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:z30.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:z30.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:z30.object({issue:pylonIssue,message:z30.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z31}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:z31.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:z31.object({user:opsArgs.user.optional(),active:z31.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:z31.object({session:z31.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z32}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=z32.array(z32.record(z32.string(),z32.unknown())).max(100),versions=z32.array(z32.string().trim().min(1).max(120)).max(100),detectionQueries=z32.array(z32.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:z32.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:z32.object({project:opsArgs.project,importance:z32.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z32.string().trim().max(120).optional(),packageManager:z32.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z32.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z32.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z32.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:z32.object({project:opsArgs.project,change:z32.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z32.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:z32.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:z32.object({project:opsArgs.project,title:z32.string().trim().min(1).max(240),userReport:z32.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:z32.object({investigation:z32.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z32.string().trim().max(1e4).optional(),outcome:z32.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:z32.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:z32.object({fingerprint:z32.string().trim().min(1).max(240),title:z32.string().trim().min(1).max(240),description:z32.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z32.string().trim().min(1).max(64).optional(),workaround:z32.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:z32.object({knownIssue:z32.uuid().describe("Known issue id"),title:z32.string().trim().min(1).max(240).optional(),description:z32.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z32.string().trim().min(1).max(64).optional(),workaround:z32.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 init_chat_reply=__esm({"../../packages/api-contracts/dist/esm/types/chat-reply.js"(){"use strict"}});import{z as z33}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,SitePagePathSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,AgentBlockSchema,PreviewBlockSchema,SearchImageUrlSchema,SearchPreviewBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,FormChoicesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,CHAT_FORM_INTERNAL_NOTE_MAX,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";init_chat_reply();BlockSayActionSchema=z33.object({kind:z33.literal("say"),label:z33.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z33.string().min(1).max(240).optional(),message:z33.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z33.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z33.discriminatedUnion("command",[z33.object({kind:z33.literal("app"),command:z33.literal("publish")}).strict(),z33.object({kind:z33.literal("app"),command:z33.literal("connect"),integrationKey:z33.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z33.object({fallback:z33.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z33.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z33.literal("choices"),text:z33.string().max(500).optional(),actions:z33.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),SitePagePathSchema=z33.string().trim().max(200).regex(/^\/(?!\/)/,"A page starts with one /."),TableRowTargetSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("entry"),collection:z33.string().min(1).max(80),entryId:z33.string().min(1).max(120)}),z33.object({kind:z33.literal("asset"),assetId:z33.string().min(1).max(120)}),z33.object({kind:z33.literal("url"),url:z33.url({protocol:/^https$/}).max(2e3)}),z33.object({kind:z33.literal("routine"),routineId:z33.string().min(1).max(120)})]),TableBlockSchema=BlockBaseSchema.extend({type:z33.literal("table"),columns:z33.array(z33.object({label:z33.string().min(1).max(24)})).min(2).max(4),rows:z33.array(z33.object({cells:z33.array(z33.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:z33.literal("cards"),layout:z33.enum(["rail","stack"]).optional(),items:z33.array(z33.object({title:z33.string().min(1).max(60),subtitle:z33.string().min(1).max(120).optional(),imageUrl:z33.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z33.literal("entry"),label:z33.string().min(1).max(80),collection:z33.string().min(1).max(80),entryId:z33.string().min(1).max(120),path:z33.string().min(1).max(120).optional()}),DraftsBlockSchema=BlockBaseSchema.extend({type:z33.literal("drafts"),items:z33.array(z33.object({label:z33.string().trim().min(1).max(80),collection:z33.string().min(1).max(80).optional(),entryId:z33.string().min(1).max(120).optional(),reviewId:z33.uuid().optional(),routineId:z33.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:z33.literal("assets"),items:z33.array(z33.object({url:z33.url({protocol:/^https$/}).max(2e3),alt:z33.string().min(1).max(120),label:z33.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z33.literal("callout"),title:z33.string().min(1).max(80),text:z33.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z33.literal("stat"),items:z33.array(z33.object({label:z33.string().min(1).max(24),value:z33.string().min(1).max(16),delta:z33.string().min(1).max(12).optional(),tone:z33.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z33.literal("chart"),unit:z33.string().min(1).max(12).optional(),kind:z33.enum(["bars","columns"]).optional(),max:z33.number().finite().positive().max(1e9).optional(),highlight:z33.string().min(1).max(12).optional(),points:z33.array(z33.object({label:z33.string().min(1).max(12),value:z33.number().finite().min(0).max(1e9),note:z33.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:z33.literal("before_after"),title:z33.string().min(1).max(80),meta:z33.string().min(1).max(80).optional(),rows:z33.array(z33.object({label:z33.string().min(1).max(24),before:z33.string().max(600),after:z33.string().max(600),showLength:z33.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:z33.literal("agent"),agentId:z33.string().uuid(),view:z33.enum(["compact","full"]).optional()}),PreviewBlockSchema=BlockBaseSchema.extend({type:z33.literal("preview"),path:SitePagePathSchema.optional(),detail:z33.string().trim().min(1).max(80).optional()}),SearchImageUrlSchema=z33.url({protocol:/^https$/}).max(2e3),SearchPreviewBlockSchema=BlockBaseSchema.extend({type:z33.literal("search_preview"),url:z33.string().trim().min(1).max(200),pageTitle:z33.string().trim().min(1).max(200),description:z33.string().trim().min(1).max(500),siteName:z33.string().trim().min(1).max(60).optional(),faviconUrl:SearchImageUrlSchema.optional(),breadcrumbs:z33.array(z33.string().trim().min(1).max(40)).min(1).max(4).optional(),date:z33.string().trim().min(1).max(24).optional(),imageUrl:SearchImageUrlSchema.optional(),video:z33.object({duration:z33.string().trim().min(1).max(8),moments:z33.number().int().min(1).max(20).optional()}).optional(),rating:z33.object({value:z33.number().min(0).max(5),count:z33.string().trim().min(1).max(16).optional()}).optional(),attributes:z33.array(z33.string().trim().min(1).max(40)).min(1).max(4).optional(),prosCons:z33.array(z33.string().trim().min(1).max(48)).min(1).max(4).optional(),readMore:z33.boolean().optional(),sitelinks:z33.array(z33.object({title:z33.string().trim().min(1).max(60),description:z33.string().trim().min(1).max(120).optional(),path:SitePagePathSchema.optional()})).min(1).max(6).optional(),sitelinksLayout:z33.enum(["rows","chips"]).optional(),query:z33.string().trim().min(1).max(80).optional()}),ChatDisplayBlockSchema=z33.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z33.literal("text"),placeholder:z33.string().min(1).max(120).optional(),multiline:z33.boolean().optional()}).strict(),ChatFormStepIdSchema=z33.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z33.object({id:ChatFormStepIdSchema,token:z33.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z33.string().trim().min(1).max(60),reason:z33.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z33.literal("capabilities"),items:z33.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:z33.array(BlockActionSchema).min(2,"A choices step needs 2 to 8 options.").max(8,"A choices step needs 2 to 8 options.")}),ChatFormBodySchema=z33.discriminatedUnion("type",[FormChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z33.object({id:ChatFormStepIdSchema.optional(),question:z33.string().min(1).max(500),header:z33.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z33.boolean().optional(),recommended:z33.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:z33.literal("form"),steps:z33.array(ChatFormStepSchema).min(1).max(4),internalNote:z33.string().trim().min(1).max(CHAT_FORM_INTERNAL_NOTE_MAX).optional()}),ChatBlockSchema=z33.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,DraftsBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,BeforeAfterBlockSchema,PreviewBlockSchema,SearchPreviewBlockSchema,AgentBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z33.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z33.object({stepId:ChatFormStepIdSchema.optional(),header:z33.string().min(1).max(25),question:z33.string().min(1).max(500),answer:z33.string().min(1),selectedLabels:z33.array(z33.string().min(1).max(120)).max(8),freeText:z33.string(),skipped:z33.boolean()}),ChatFormAnswerMetadataSchema=z33.object({toolCallId:z33.string().max(255).optional(),shortTitle:z33.string().max(80).optional(),questions:z33.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z33.object({version:z33.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z33.object({version:z33.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z33.string().min(1).max(255),partial:z33.boolean().optional()})}});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 z34}from"zod";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"],BlockUpdateResultSchema=z34.object({rendered:z34.literal(!0),id:z34.string().min(1),block:ChatBlockSchema,reason:z34.string().optional()}),BlockCloseResultSchema=z34.object({closed:z34.literal(!0),ids:z34.array(z34.string().min(1)).min(1),outcome:z34.enum(BLOCK_CLOSE_OUTCOMES),reason:z34.string(),messageId:z34.string().optional(),stepIds:z34.array(ChatFormStepIdSchema).min(1).optional()})}});import{z as z35}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=z35.union([z35.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z35.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z35.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z35.object({label:z35.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z35.object({label:z35.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z35.discriminatedUnion("kind",[BlockSayActionSchema,z35.object({kind:z35.literal("open"),label:z35.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z35.object({kind:z35.literal("op"),label:z35.string().trim().min(1).max(32),operation:z35.string().min(1).max(80),input:z35.record(z35.string(),z35.unknown())}).strict(),z35.object({kind:z35.literal("impersonate"),label:z35.string().trim().min(1).max(32),userId:z35.string().min(1).max(120)}).strict(),z35.object({kind:z35.literal("studio"),label:z35.string().trim().min(1).max(32),projectId:z35.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z35.object({fallback:z35.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z35.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z35.literal("record"),kind:z35.string().trim().min(1).max(24),name:z35.string().trim().min(1).max(80),id:z35.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z35.array(z35.object({label:z35.string().trim().min(1).max(24),value:z35.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z35.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z35.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z35.literal("cards"),items:z35.array(z35.object({name:z35.string().trim().min(1).max(60),subtitle:z35.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z35.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z35.literal("table"),columns:z35.array(z35.object({label:z35.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z35.array(z35.object({cells:z35.array(z35.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:z35.literal("timeline"),events:z35.array(z35.object({at:z35.string().trim().min(1).max(16),label:z35.string().trim().min(1).max(80),detail:z35.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z35.literal("stats"),items:z35.array(z35.object({label:z35.string().min(1).max(24),value:z35.string().min(1).max(16),delta:z35.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z35.literal("excerpt"),source:z35.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z35.discriminatedUnion("kind",[z35.object({kind:z35.literal("lines"),lines:z35.array(z35.object({text:z35.string().max(200),highlight:z35.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z35.object({kind:z35.literal("message"),author:z35.string().trim().min(1).max(60),at:z35.string().max(24).optional(),text:z35.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z35.literal("media"),items:z35.array(z35.object({url:z35.url({protocol:/^https$/}).max(2e3),alt:z35.string().min(1).max(120),label:z35.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z35.literal("actions"),actions:z35.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z35.literal("handoff"),prompt:z35.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z35.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z35.object({block:AdminChatBlockSchema})}});import{z as z36}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=z36.object({shape:z36.enum(CHAT_PORTRAIT_SHAPES),eyes:z36.enum(CHAT_PORTRAIT_EYES),mouth:z36.enum(CHAT_PORTRAIT_MOUTHS),color:z36.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z37}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=z37.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z37.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z37.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z37.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z37.string().trim().min(1).max(2e4),ChatRoutineDescriptionSchema=z37.string().trim().min(1).max(500),ChatRoutineModelSchema=z37.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z37.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z37.object({text:z37.string(),title:z37.string(),explanation:z37.string(),watches:z37.array(z37.object({url:z37.string(),health:z37.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z37.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z37.object({text:z37.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z37.object({manual:z37.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z37.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z37.object({message:z37.string().trim().min(1).max(2e4),decision:z37.boolean().optional(),incomplete:z37.boolean().optional(),remaining:z37.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=z37.object({id:z37.string().uuid(),threadId:z37.string().uuid(),runThreadId:z37.string().uuid(),name:z37.string(),description:z37.string().nullable(),instructions:z37.string(),template:z37.object({key:z37.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z37.string(),modelIsDefault:z37.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z37.boolean(),nextRunAt:z37.string().nullable(),lastRunAt:z37.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z37.string().nullable(),createdAt:z37.string(),updatedAt:z37.string()}),ChatRoutineListDTOSchema=z37.object({routines:z37.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z37.object({usedMs:z37.number().int().min(0),includedMs:z37.number().int().min(0),periodStart:z37.string(),periodEnd:z37.string(),stopsAtIncluded:z37.boolean(),canStart:z37.boolean(),canPayOverage:z37.boolean(),overageRateMicrosPerHour:z37.number().int().nullable(),billedMs:z37.number().int().min(0),billedMicros:z37.number().int().min(0)}),ChatRoutineCreateSchema=z37.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=z37.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z37.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z37.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=z37.object({message:z37.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z37.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z37.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z37.object({kind:z37.enum(["person","agent"]),name:z37.string().nullable()}),ChatRoutineRunDTOSchema=z37.object({messageId:z37.string().uuid(),invocationId:z37.string().uuid().nullable(),startedAt:z37.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z37.string().nullable(),events:z37.number().int().min(1),durationMs:z37.number().int().min(0).nullable(),credits:z37.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z37.object({runs:z37.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z37.object({message:z37.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z37.object({kind:z37.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z37.string().uuid().nullable()})}});import{z as z38}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=z38.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z38.string(),displayName:z38.string().nullable(),subdomain:z38.string().nullable().optional(),subdomainUpdatedAt:z38.date().nullable().optional(),organizationId:z38.string().nullable(),createdBy:z38.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z38.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z38.string(),thumbnailUrl:z38.string().nullable(),publishedThumbnailUrl:z38.string().nullable(),category:z38.string().nullable(),snapshotUrl:z38.string().startsWith("/").optional(),appUrl:z38.string().nullable(),lastPublishedAt:z38.coerce.date(),databaseQuotaIncidentId:z38.uuid().nullable().optional(),databaseQuotaLastObservedAt:z38.coerce.date().nullable().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z38.object({name:z38.string().optional(),enabledChatModels:z38.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z38.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z38.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z38.object({id:z38.uuid(),name:z38.string(),displayName:z38.string().nullable(),thumbnailUrl:z38.string().nullable(),category:z38.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z38.object({id:z38.string(),name:z38.string(),avatar:z38.string().nullable(),color:z38.object({bg:z38.string(),text:z38.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z38.object({path:z38.string(),content:z38.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z38.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z38.object({id:z38.string(),messageId:z38.string(),versionId:z38.string().nullable(),role:ProjectChatMessageRole,parts:z38.array(z38.any()),createdAt:z38.coerce.date()}),MessageUserMetadataSchema=z38.object({id:z38.string(),name:z38.string().nullable().optional(),image:z38.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z38.number(),metadata:z38.object({user:MessageUserMetadataSchema,changeManifest:z38.array(z38.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z38.object({versionId:z38.uuid(),commitHash:z38.string(),name:z38.string(),description:z38.string().nullable(),kind:z38.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z38.object({versionCount:z38.number().int().nonnegative(),snapshotBytes:z38.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z38.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z38.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z38.object({content:z38.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z38.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),message:z38.string().optional(),warning:z38.string().optional(),durationMs:z38.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z38.object({code:z38.literal("PUBLISH_UPGRADE_REQUIRED"),message:z38.string(),currentVersion:z38.number().int().positive(),targetVersion:z38.literal(4)}),ProjectLatestPublicationAttemptSchema=z38.object({publicationId:z38.uuid(),status:z38.enum(["queued","building","published","failed","canceled"]),failureCode:z38.string().nullable(),sourceBranch:z38.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z38.object({isPublished:z38.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z38.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z38.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z38.object({label:z38.string().trim().min(1).max(120).optional(),notes:z38.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z38.object({success:z38.boolean(),message:z38.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z38.boolean(),publicationId:z38.string().optional(),url:z38.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z39}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,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=z39.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z39.object({items:z39.array(ProjectMessagePublicDTOSchema),nextCursor:z39.string().nullable()}),ChatLiveTurnDTOSchema=z39.object({invocationId:z39.string(),step:z39.enum(["preparing","working","compacting","merging"]),startedAt:z39.string(),continuesInvocationId:z39.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z39.object({threadId:z39.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z39.object({kind:z39.enum(["person","agent","routine","system"]),id:z39.string().nullable()}),ChatThreadMessageDTOSchema=z39.object({id:z39.string(),role:z39.enum(["user","assistant"]),parts:z39.array(z39.unknown()),metadata:z39.record(z39.string(),z39.unknown()).nullable(),versionId:z39.string().nullable().optional(),createdAt:z39.date().transform(value=>value.toISOString()),providerMessageId:z39.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z39.string().nullable().optional(),invocationStatus:z39.string().nullable().optional(),invocationTerminalReason:z39.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z39.object({id:z39.string(),parts:z39.array(z39.unknown()),metadata:z39.record(z39.string(),z39.unknown()).nullable(),providerMessageId:z39.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z39.boolean(),queuedAt:z39.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z39.object({type:z39.literal("merge_conflict"),merge:z39.object({mergeId:z39.string().uuid(),projectId:z39.string(),fromBranch:z39.string(),toBranch:z39.string()}),publishAfterMerge:z39.boolean()}),ChatThreadMessagesPageDTOSchema=z39.object({threadId:z39.string().nullable(),title:z39.string().nullable(),messages:z39.array(ChatThreadMessageDTOSchema),nextCursor:z39.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z39.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z39.boolean().optional(),queueWaitUntil:z39.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z39.object({kind:z39.literal("replay"),threadId:z39.string(),userMessageId:z39.string()}),ChatQueuedOutcomeDTOSchema=z39.object({kind:z39.literal("queued"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),ChatBusyOutcomeDTOSchema=z39.object({kind:z39.literal("busy"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),ChatRefusedOutcomeDTOSchema=z39.object({kind:z39.literal("refused"),threadId:z39.string(),userMessageId:z39.string(),refusedInvocationId:z39.string(),terminalReason:z39.string()}),ChatNonStreamingOutcomeDTOSchema=z39.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z39.enum(["chat","agent","routine","task","draft"]),ProjectChatCreatableKindSchema=z39.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z39.object({quietRuns:z39.number().int().nonnegative(),since:z39.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z39.string().nullable(),nextRunAt:z39.string().nullable(),wakesOnChanges:z39.boolean()}),ProjectChatDescriptionSchema=z39.string().trim().max(2e3),ProjectChatInstructionsSchema=z39.string().trim().max(8e3),ProjectChatDTOSchema=z39.object({id:z39.string().uuid(),kind:ProjectChatKindSchema,title:z39.string().nullable(),description:z39.string().nullable(),instructions:z39.string().nullable(),liveAt:z39.string().nullable(),template:z39.string().nullable(),parentThreadId:z39.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z39.string(),lastMessageAt:z39.string().nullable(),preview:z39.string().nullable(),running:z39.boolean(),awaitingAnswer:z39.boolean(),unread:z39.boolean(),pinned:z39.boolean(),archived:z39.boolean(),muted:z39.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z39.object({chats:z39.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z39.object({id:z39.string().uuid()}),ProjectChatTitleSchema=z39.string().trim().min(1).max(120),ProjectChatCreateSchema=z39.object({id:z39.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z39.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema,setup:z39.literal(!0),locale:z39.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=z39.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=z39.object({cron:z39.string()}),ChatTemplateRoutineDTOSchema=z39.object({name:z39.string(),description:z39.string(),instructions:z39.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z39.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z39.object({id:z39.string(),name:z39.string(),summary:z39.string(),description:z39.string(),greeting:z39.string(),starters:z39.array(z39.string()),portrait:ChatPortraitSchema,plans:z39.array(AgentPlanSchema),routines:z39.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z39.object({templates:z39.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z39.object({read:z39.boolean(),pinned:z39.boolean(),archived:z39.boolean(),muted:z39.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 z40}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:z40.array(ChatFormAnswerItemSchema.extend({answer:z40.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z40.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z40.object({id:z40.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z40.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z40.object({threadId:z40.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=z40.discriminatedUnion("kind",[z40.object({kind:z40.literal("replay"),threadId:z40.string(),userMessageId:z40.string()}),z40.object({kind:z40.literal("queued"),threadId:z40.string(),userMessageId:z40.string(),blockingRootId:z40.string().optional()}),z40.object({kind:z40.literal("busy"),threadId:z40.string(),userMessageId:z40.string(),blockingRootId:z40.string().optional()}),z40.object({kind:z40.literal("refused"),threadId:z40.string(),userMessageId:z40.string(),refusedInvocationId:z40.string(),terminalReason:z40.string()})]),AdminAssistantStreamHeadSchema=z40.object({kind:z40.literal("turn"),threadId:z40.string(),userMessageId:z40.string(),invocationId:z40.string()}),AdminAssistantThreadSummarySchema=z40.object({id:z40.string().uuid(),title:z40.string().nullable(),lastMessageAt:z40.string().nullable(),createdAt:z40.string()}),AdminAssistantThreadListQuerySchema=z40.object({q:z40.string().trim().max(200).optional(),cursor:z40.string().max(500).optional(),limit:z40.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z40.object({threads:z40.array(AdminAssistantThreadSummarySchema),nextCursor:z40.string().nullable()}),AdminAssistantThreadResponseSchema=z40.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z40.string().nullable()}),messages:z40.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z40.object({threadId:z40.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z40.object({aborted:z40.boolean()}),AdminAssistantThreadUpdateSchema=z40.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z40.object({deleted:z40.literal(!0)})}});import{z as z41}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=z41.enum(REPORT_TONES),blockCommon={title:z41.string().trim().min(1).max(120).optional(),fallback:z41.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z41.object({type:z41.literal("text"),...blockCommon,text:z41.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=z41.object({type:z41.literal("metric"),...blockCommon,items:z41.array(z41.object({value:z41.string().trim().min(1).max(24),unit:z41.string().trim().min(1).max(12).optional(),label:z41.string().trim().min(1).max(160),note:z41.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z41.array(z41.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=z41.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z41.object({type:z41.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z41.string().trim().min(1).max(12).optional(),points:z41.array(z41.object({label:z41.string().trim().min(1).max(24),value:z41.number().finite(),highlight:z41.boolean().optional()}).strict()).min(2).max(24),caption:z41.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=z41.object({type:z41.literal("list"),...blockCommon,items:z41.array(z41.object({tone:ReportToneSchema.optional(),label:z41.string().trim().min(1).max(24).optional(),heading:z41.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z41.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z41.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=z41.object({type:z41.literal("table"),...blockCommon,columns:z41.array(z41.object({label:z41.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z41.array(z41.object({cells:z41.array(z41.object({text:z41.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z41.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=z41.object({type:z41.literal("media"),...blockCommon,assetId:z41.uuid(),alt:z41.string().trim().min(1).max(300),caption:z41.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=z41.object({type:z41.literal("links"),...blockCommon,items:z41.array(z41.object({label:z41.string().trim().min(1).max(120),url:z41.url({protocol:/^https$/}).max(2e3),description:z41.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z41.object({type:z41.literal("code"),...blockCommon,language:z41.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z41.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z41.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z41.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z41.object({title:z41.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z41.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z41.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=z41.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=z41.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z41.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z42}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=z42.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z42.object({dev:z42.string().trim().min(1).optional(),build:z42.string().trim().min(1).optional(),install:z42.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z42.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z42.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z42.object({type:z42.enum(["header","cookie","query","host"]),key:z42.string().min(1).optional(),value:z42.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:z42.array(FimoHostingConditionSchema).min(1).optional(),missing:z42.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z42.object({source:z42.string().min(1),destination:z42.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z42.object({source:z42.string().min(1),destination:z42.string().min(1),permanent:z42.boolean().optional(),statusCode:z42.union([z42.literal(301),z42.literal(302),z42.literal(307),z42.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z42.object({source:z42.string().min(1),headers:z42.array(z42.object({key:z42.string().min(1),value:z42.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z42.object({rewrites:z42.array(FimoHostingRewriteSchema).optional(),redirects:z42.array(FimoHostingRedirectSchema).optional(),headers:z42.array(FimoHostingHeaderSchema).optional(),cleanUrls:z42.boolean().optional(),trailingSlash:z42.boolean().optional()}).strict(),FimoAppConfigSchema=z42.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 z43}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=z43.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z43.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z43.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z43.string().nullable(),deletedAt:z43.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z43.object({id:z43.union([z43.literal(PREVIEW_ENVIRONMENT_KEY),z43.uuid()]),name:z43.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z43.object({sessionId:z43.uuid(),name:z43.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z43.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=z43.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z43.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z43.object({surface:z43.enum(["code","schemas","content","translations","assets","forms"]),status:z43.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z43.number().int().nonnegative(),conflictCount:z43.number().int().nonnegative()}),BranchDiffResultSchema=z43.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z43.coerce.date(),surfaces:z43.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z44}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=z44.object({projectId:z44.uuid(),name:z44.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z44.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z44.literal("production"),sourceBranch:BranchSchema,isPublished:z44.boolean(),url:z44.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z44.literal(PREVIEW_ENVIRONMENT_KEY),kind:z44.literal("preview"),matchedBranchCount:z44.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z44.literal("custom"),matchedBranchCount:z44.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z44.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z44.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z44.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z44.object({deletedId:z44.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z45}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=z45.object({kind:z45.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z45.object({kind:z45.enum(["variable","secret"]),value:z45.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z45.string().min(1).max(255),exposure:z45.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z45.object({kind:z45.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z45.object({id:z45.uuid(),projectId:z45.uuid(),key:z45.string(),kind:z45.literal("secret"),exposure:z45.literal("private"),environment:EnvironmentKeySchema,maskedValue:z45.string().optional(),createdAt:z45.date().transform(value=>value.toISOString()),updatedAt:z45.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z45.object({id:z45.uuid(),projectId:z45.uuid(),key:z45.string(),kind:z45.literal("variable"),environment:EnvironmentKeySchema,managed:z45.boolean(),createdAt:z45.date().transform(value=>value.toISOString()),updatedAt:z45.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z45.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z45.literal("public"),value:z45.string()}),ProjectVariableBaseSchema.extend({exposure:z45.literal("private"),maskedValue:z45.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z45.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z46}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=z46.object({success:z46.literal(!0),downloadUrl:z46.string(),expiresAt:z46.string(),fileSize:z46.number(),duration:z46.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z46.object({success:z46.literal(!0),projectId:z46.string(),projectName:z46.string(),displayName:z46.string(),projectUrl:z46.string(),duration:z46.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z46.object({contentTypes:z46.number(),entries:z46.number(),assets:z46.number(),translations:z46.number(),forms:z46.number(),codeFiles:z46.number(),assetFiles:z46.number()}),ImportPreviewSurfaceDTOSchema=z46.object({name:z46.string(),included:z46.boolean(),count:z46.number().optional(),note:z46.string().optional()}),ImportPreviewDTOSchema=z46.object({projectName:z46.string(),displayName:z46.string().nullable(),category:z46.string().nullable(),exportedAt:z46.string(),version:z46.string(),envScope:z46.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z46.array(ImportPreviewSurfaceDTOSchema),fileSize:z46.number(),fileName:z46.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z46.object({success:z46.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z47}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=z47.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z47.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z47.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z47.object({verb:SurfaceDeltaVerbSchema,key:z47.string(),detail:z47.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z47.record(z47.string(),z47.unknown()).optional()}),PerSurfaceDeltaSchema=z47.object({surface:SurfaceNameSchema,status:z47.enum(["ok","timed_out","failed","unchanged"]),durationMs:z47.number().int().nonnegative().optional(),changedCount:z47.number().int().nonnegative(),conflictCount:z47.number().int().nonnegative(),items:z47.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z47.boolean().optional(),error:z47.string().optional()}),CrossSurfaceFindingSchema=z47.object({id:z47.string(),kind:z47.string(),description:z47.string(),severity:z47.enum(["warning","error"]),source:z47.object({surface:SurfaceNameSchema,key:z47.string()}),target:z47.object({surface:SurfaceNameSchema,key:z47.string()}),actions:z47.array(z47.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z47.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z47.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z47.coerce.date(),surfaces:z47.array(PerSurfaceDeltaSchema),agents:z47.array(z47.object({id:z47.string(),name:z47.string(),status:z47.enum(["active","paused","failed"]),lastRunAt:z47.coerce.date().nullable()})).optional(),crossSurface:z47.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z47.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z47.coerce.date(),surfaces:z47.array(PerSurfaceDeltaSchema),crossSurface:z47.array(CrossSurfaceFindingSchema).optional(),fingerprint:z47.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z47.object({path:z47.string(),state:z47.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z47.string(),additions:z47.number().int().nonnegative(),deletions:z47.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z47.object({oid:z47.string().optional(),content:z47.string().optional(),truncated:z47.boolean(),binary:z47.boolean()}),CodeConflictDetailSchema=z47.object({path:z47.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z47.string(),targetTipSha:z47.string(),mergeBaseSha:z47.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z47.object({id:z47.string(),slug:z47.string(),contentType:z47.string(),data:z47.record(z47.string(),z47.unknown()),updatedAt:z47.coerce.date()}),ContentRowDiffSchema=z47.object({collection:z47.string(),rowId:z47.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z47.object({name:z47.string(),label:z47.string(),isSingleton:z47.boolean(),description:z47.string().nullable().default(null),fields:z47.record(z47.string(),z47.unknown())}),SchemaTypeDiffSchema=z47.object({typeName:z47.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z47.object({id:z47.string(),name:z47.string(),type:z47.enum(["file","folder"]),mimeType:z47.string().nullable(),storageKey:z47.string().nullable(),url:z47.string().nullable(),fileSize:z47.number().nullable(),width:z47.number().nullable(),height:z47.number().nullable(),altText:z47.string().nullable(),caption:z47.string().nullable(),createdAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),AssetDiffSchema=z47.object({assetId:z47.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z47.object({locale:z47.string(),key:z47.string(),parent:z47.string().nullable(),child:z47.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z47.object({formName:z47.string(),label:z47.string().nullable(),schemaFingerprint:z47.string(),fields:z47.record(z47.string(),z47.unknown()),settings:z47.record(z47.string(),z47.unknown()).optional()}),FormSchemaDiffSchema=z47.object({formName:z47.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=z47.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z47.object({sha:z47.string(),subject:z47.string(),body:z47.string().optional(),author:z47.string(),date:z47.string()}),ConflictSchema=z47.object({surface:SurfaceNameSchema,key:z47.string(),kind:ConflictKindSchema.optional(),description:z47.string(),parentValue:z47.unknown().optional(),childValue:z47.unknown().optional(),conflictingFields:z47.array(z47.string()).optional(),code:z47.object({path:z47.string(),unresolvable:z47.boolean().optional(),reason:z47.string().optional(),targetCommits:z47.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z47.object({field:z47.string(),choice:z47.enum(["parent","child","pick","ai-pick"]),pickedValue:z47.unknown().optional(),aiSessionId:z47.string().optional()}),ConflictResolutionSchema=z47.object({surface:SurfaceNameSchema,key:z47.string(),choice:z47.enum(["parent","child","pick"]),pickedValue:z47.unknown().optional(),fieldPicks:z47.array(FieldPickSchema).optional()}),MergeResultSchema=z47.object({ok:z47.boolean(),mergeId:z47.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z47.array(z47.object({surface:SurfaceNameSchema,count:z47.number().int().nonnegative()})),conflicts:z47.array(ConflictSchema).optional(),summary:z47.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z47.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z47.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z47.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z47.boolean().optional()}),ResolvedStrategySchema=z47.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z47.boolean()}),MergeRequestSchema=z47.object({from:BranchSchema,allowDirectMerge:z47.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z47.object({mergeId:z47.string().uuid(),streamUrl:z47.string(),strategy:ResolvedStrategySchema,acceptedAt:z47.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z47.object({mergeId:z47.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z47.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z47.array(ConflictSchema),draftResolutions:z47.array(ConflictResolutionSchema),lastEditedBy:z47.string().nullable(),lastEditedAt:z47.coerce.date().nullable(),initiator:z47.object({userId:z47.string().nullable(),role:z47.string().nullable(),agentName:z47.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z47.object({resolutions:z47.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z47.object({mergeId:z47.string().uuid(),draftResolutions:z47.array(ConflictResolutionSchema),lastEditedAt:z47.coerce.date(),lastEditedBy:z47.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z47.object({mergeId:z47.string().uuid(),resolutions:z47.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z47.object({mergeId:z47.string().uuid()}),PublishReleaseRequestSchema=z47.object({version:z47.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z47.string().max(2e4).optional()}),PublishReleaseResultSchema=z47.object({releaseTag:z47.string(),sha:z47.string(),publishedAt:z47.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z48}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=z48.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z48.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z48.object({capturedAt:z48.coerce.date(),fingerprint:z48.string().min(1).max(256),counts:z48.object({code:z48.number().int().nonnegative(),content:z48.number().int().nonnegative(),schemas:z48.number().int().nonnegative(),labels:z48.number().int().nonnegative(),assets:z48.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z48.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z48.object({diff:DiffReportSchema,code:z48.array(CodeFileDiffSchema.extend({raw:z48.string().max(24576)})).max(200),schemas:z48.array(SchemaTypeDiffSchema).max(200),content:z48.array(z48.object({key:z48.string().min(1).max(512),collection:z48.string().min(1).max(256),slug:z48.string().max(512).optional(),verb:z48.enum(["added","modified","deleted"]),fields:z48.array(z48.object({name:z48.string().min(1).max(256),before:z48.unknown().optional(),after:z48.unknown().optional()})).max(20)})).max(200),labels:z48.array(z48.object({key:z48.string().min(1).max(512),locale:z48.string().min(1).max(64).optional(),before:z48.unknown().nullable(),after:z48.unknown().nullable()})).max(200),assets:z48.array(z48.object({key:z48.string().min(1).max(512),name:z48.string().min(1).max(512),verb:z48.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z48.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z49}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentBranchClassificationSchema=z49.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z49.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z49.object({sessionId:z49.uuid(),branch:z49.string().min(1),targetBranch:z49.string().min(1),revision:z49.string().min(1),fingerprint:z49.string().min(1),source:z49.enum(["studio","slack","mcp"]),threadId:z49.uuid().nullable(),invocationId:z49.uuid().nullable(),conversationBranch:z49.string().nullable(),capturedAt:z49.string(),surfaces:z49.array(PerSurfaceDeltaSchema).optional(),counts:z49.record(z49.string(),z49.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z49.strictObject({sessionId:z49.uuid(),summary:z49.string().trim().min(1).max(240),targetBranch:z49.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z49.object({requested:z49.literal(!0),alreadyRequested:z49.boolean(),reviewId:z49.uuid(),reviewUrl:z49.url(),status:z49.literal("pending"),sessionId:z49.uuid(),branch:z49.string(),targetBranch:z49.string(),revision:z49.string(),savedRevision:z49.string(),fingerprint:z49.string(),visibility:z49.literal("user-visible"),retention:z49.literal("durable"),expiresAt:z49.null(),merged:z49.literal(!1),published:z49.literal(!1),links:z49.object({preview:z49.url(),changes:z49.url(),conversation:z49.url().nullable()})}),AgentBranchProposalDTOSchema=z49.object({id:z49.uuid(),envId:z49.uuid(),sessionId:z49.uuid().nullable(),skillName:z49.string().min(1),classification:AgentBranchClassificationSchema,rationale:z49.string().nullable(),summary:z49.string().nullable(),surfaceDeltas:z49.record(z49.string(),z49.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z49.coerce.date(),decidedAt:z49.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z49.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z49.object({path:z49.enum(["review-merged","review-discarded"]),acceptCurrent:z49.boolean().optional()}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z49.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z49.object({code:z49.literal("merge_conflict"),message:z49.string(),conflicts:z49.record(z49.string(),z49.number().int().nonnegative())})}});import{z as z50}from"zod";var AskDraftChangeRequestSchema,RewriteDraftWordsRequestSchema,DraftChangeStateQuerySchema,DraftChangeStateSchema,init_draft_change_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/draft-change.dto.js"(){"use strict";AskDraftChangeRequestSchema=z50.object({projectId:z50.uuid(),reviewId:z50.uuid(),entryId:z50.string().min(1).max(120),contentTypeName:z50.string().min(1).max(120),field:z50.string().min(1).max(120),quote:z50.string().min(1).max(2e4).optional(),locale:z50.string().min(1).max(35).optional(),message:z50.string().trim().min(1).max(4e3),providerMessageId:z50.string().min(1).max(200)}),RewriteDraftWordsRequestSchema=AskDraftChangeRequestSchema.extend({format:z50.enum(["rich","plain"]),words:z50.string().min(1).max(4e4),surroundingText:z50.string().max(2e4).optional()}),DraftChangeStateQuerySchema=z50.object({projectId:z50.uuid(),reviewId:z50.uuid()}),DraftChangeStateSchema=z50.object({busy:z50.boolean(),reply:z50.string().nullable()})}});import{z as z51}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=z51.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z51.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=z51.object({description:z51.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z51.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z51.array(z51.uuid()).optional()}),AgentQuestionSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),threadId:z51.uuid(),invocationId:z51.uuid(),agentKey:z51.string().min(1).max(120),anchorEnv:z51.string().min(1).max(64),retainedEnv:z51.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z51.string().min(1).nullable(),continuationInvocationId:z51.uuid().nullable(),askedAt:z51.coerce.date(),expiresAt:z51.coerce.date(),closedAt:z51.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z51.object({questionId:z51.uuid(),invocationId:z51.uuid(),askedAt:z51.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z51.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z51.object({question:AgentQuestionSchema,continuationInvocationId:z51.uuid(),deduped:z51.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z52}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=z52.object({projectId:z52.uuid(),agentId:z52.uuid(),recipientEmail:z52.email().max(320)}).strict(),AgentQuestionFollowUpSchema=z52.object({projectId:z52.uuid(),agentId:z52.uuid(),eligible:z52.boolean(),reason:z52.enum(["ready","no_pending_questions","incomplete_coverage","unavailable"]),agentPendingQuestions:z52.number().int().nonnegative().nullable(),projectPendingQuestions:z52.number().int().nonnegative().nullable(),agentLegacyPendingForms:z52.number().int().nonnegative().nullable(),projectLegacyPendingForms:z52.number().int().nonnegative().nullable(),agentPendingCoverage:z52.enum(["complete","partial","unknown"]),projectPendingCoverage:z52.enum(["complete","partial","unknown"]),snapshotAt:z52.iso.datetime().nullable()}),AgentQuestionFollowUpDTO=createDTO(AgentQuestionFollowUpSchema)}});import{z as z53}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=z53.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z53.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z53.enum(["secret_text"]),IntegrationCredentialUsageSchema=z53.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z53.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z53.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z53.object({mode:IntegrationAuthModeSchema,label:z53.string().min(1),description:z53.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z53.object({id:z53.string().min(1),label:z53.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z53.boolean()}),IntegrationToolDefinitionDTOSchema=z53.object({key:z53.string().min(1),name:z53.string().min(1),description:z53.string().min(1),effect:IntegrationToolEffectSchema,input:z53.record(z53.string(),z53.unknown()).optional()}),IntegrationRecipeDTOSchema=z53.object({title:z53.string().min(1),description:z53.string().min(1),command:z53.string().min(1).optional()}),IntegrationInfoDTOSchema=z53.object({key:z53.string().min(1),name:z53.string().min(1),summary:z53.string().min(1),type:z53.enum(["native","mcp"]).optional(),url:z53.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z53.array(IntegrationAuthModeDTOSchema),credentials:z53.array(IntegrationCredentialDefinitionDTOSchema),tools:z53.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z53.enum(["available","unavailable"]).optional(),connectionCapabilities:z53.object({customIdentityCreation:z53.boolean()}).optional(),recipes:z53.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z53.object({projectId:z53.uuid(),integrationKey:z53.string().min(1),name:z53.string().min(1),summary:z53.string().min(1),installed:z53.boolean(),enabled:z53.boolean(),setupState:z53.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z53.string().nullable(),connectionId:z53.uuid().nullable().optional(),connectionAlias:z53.string().min(1).nullable().optional(),connectionStatus:z53.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z53.array(z53.string()),installedAt:z53.coerce.date().nullable(),updatedAt:z53.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),integrationKey:z53.string().min(1),enabled:z53.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z53.string(),connectionId:z53.uuid().nullable().optional(),connectionAlias:z53.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z53.array(z53.string()),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z53.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z53.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z53.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z53.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z53.object({id:z53.uuid(),organizationId:z53.string().min(1),integrationKey:z53.string().min(1),registrationId:z53.uuid().nullable(),alias:z53.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z53.string().min(1),externalAccountName:z53.string().nullable(),externalBotUserId:z53.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z53.array(z53.string()),connectedAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z53.boolean(),isDefault:z53.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z53.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z53.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z53.record(McpHeaderNameSchema,z53.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z53.object({alias:z53.string().min(1).max(120).optional(),token:z53.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z53.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=z53.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z53.object({displayName:z53.string().trim().min(1).max(35),backgroundColor:z53.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z53.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z53.discriminatedUnion("mode",[z53.object({mode:z53.literal("personal"),alias:z53.string().min(1).max(120),token:z53.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z53.boolean().optional()}),z53.object({mode:z53.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z53.boolean().optional(),registrationId:z53.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=z53.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z53.union([z53.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z53.object({type:z53.literal("mcp"),name:z53.string().trim().min(1).max(120),url:z53.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z53.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z53.string().min(1).optional(),integrationId:z53.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=z53.object({integrationKey:z53.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z53.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z53.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z53.literal("oauth"),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()})]),ReusableMcpServerAuthKindSchema=z53.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z53.object({id:z53.uuid(),name:z53.string().min(1),host:z53.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z53.string().min(1),availability:z53.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z53.object({query:z53.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z53.object({serverId:z53.uuid()}),LinearOAuthApplicationDistributionSchema=z53.enum(["private","public"]),OrganizationLinearAppDTOSchema=z53.object({id:z53.uuid(),displayName:z53.string().min(1),description:z53.string().nullable(),iconUrl:z53.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z53.enum(["active","revoked","disconnected"]),connectionIds:z53.array(z53.uuid()),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z53.object({appName:z53.string().trim().min(2).max(80),description:z53.string().trim().max(1e3).optional(),iconUrl:z53.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z53.object({projectId:z53.uuid(),registrationId:z53.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z53.object({integrationKey:z53.string().min(1),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z53.discriminatedUnion("mode",[z53.object({mode:z53.literal("personal"),integrationKey:z53.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z53.object({mode:z53.literal("oauth"),integrationKey:z53.string().min(1),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()})]),BindProjectChannelRequestSchema=z53.object({ref:z53.string().min(1),connectionAlias:z53.string().min(1).optional(),agentName:z53.string().min(1).max(160).nullable().optional(),force:z53.boolean().optional()}),ListProjectChannelsQuerySchema=z53.object({integrationKey:z53.string().min(1)}),SearchProjectChannelsQuerySchema=z53.object({integrationKey:z53.string().min(1),connectionAlias:z53.string().min(1),query:z53.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),integrationKey:z53.string().min(1),connectionId:z53.uuid(),externalWorkspaceId:z53.string().min(1),externalChannelId:z53.string().min(1),externalChannelName:z53.string().nullable(),agentName:z53.string().nullable(),enabled:z53.boolean(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z53.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z53.object({id:z53.string().min(1),name:z53.string().min(1),visibility:z53.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z53.string().min(1).nullable(),canMove:z53.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z53.object({markdown:z53.boolean().optional(),summary:z53.boolean().optional(),links:z53.boolean().optional(),branding:z53.boolean().optional(),images:z53.boolean().optional(),html:z53.union([z53.literal("cleaned"),z53.literal("raw"),z53.boolean()]).optional(),json:z53.union([z53.boolean(),z53.object({prompt:z53.string().min(1).max(1e4),schema:z53.record(z53.string(),z53.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z53.object({url:z53.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional(),waitForMs:z53.number().int().min(0).max(3e4).optional(),maxAgeMs:z53.number().int().min(0).optional(),minAgeMs:z53.number().int().min(0).optional(),storeInCache:z53.boolean().optional(),proxy:z53.enum(["basic","enhanced","auto"]).optional(),mobile:z53.boolean().optional(),location:z53.object({country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z53.array(z53.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z53.object({query:z53.string().min(1),maxResults:z53.number().int().positive().max(20).optional(),sources:z53.array(z53.enum(["web","news","images"])).min(1).max(3).optional(),categories:z53.array(z53.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z53.enum(["hour","day","week","month","year"]).optional(),location:z53.string().min(1).max(160).optional(),country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z53.object({query:z53.string().min(1).max(500),maxResults:z53.number().int().min(1).max(100).optional(),types:z53.array(z53.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z53.array(z53.string().min(1).max(512)).min(1).max(20).optional(),sources:z53.array(z53.string().min(1).max(512)).min(1).max(20).optional(),passages:z53.number().int().min(1).max(5).optional(),skills:z53.literal("only").optional(),language:z53.string().min(1).optional(),topic:z53.string().min(1).optional(),license:z53.string().min(1).optional(),minStars:z53.number().int().min(0).optional(),maxStars:z53.number().int().min(0).optional(),archived:z53.boolean().optional(),fork:z53.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z53.object({query:z53.string().min(1).max(500),maxResults:z53.number().int().min(1).max(500).optional(),authors:z53.array(z53.string().min(1)).min(1).optional(),categories:z53.array(z53.string().min(1)).min(1).optional(),from:z53.iso.date().optional(),to:z53.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z53.object({paperId:z53.string().min(1).max(512),query:z53.string().min(1).max(500).optional(),maxPassages:z53.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z53.object({paperId:z53.string().min(1).max(512),intent:z53.string().min(1).max(500),mode:z53.enum(["similar","citers","references"]).optional(),maxResults:z53.number().int().min(1).max(500).optional(),rerank:z53.boolean().optional(),anchors:z53.array(z53.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z53.object({url:z53.string().url(),search:z53.string().min(1).optional(),limit:z53.number().int().positive().max(200).optional(),includeSubdomains:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z53.object({url:z53.string().url(),limit:z53.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z53.object({text:z53.string().min(1).max(200).optional(),cron:z53.string().min(1).max(120).optional(),timezone:z53.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z53.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional(),waitForMs:z53.number().int().min(0).max(3e4).optional(),maxAgeMs:z53.number().int().min(0).optional(),minAgeMs:z53.number().int().min(0).optional(),storeInCache:z53.boolean().optional(),proxy:z53.enum(["basic","enhanced","auto"]).optional(),mobile:z53.boolean().optional(),location:z53.object({country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z53.array(z53.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z53.union([z53.object({type:z53.enum(["scrape","crawl"]).default("scrape"),urls:z53.array(z53.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z53.object({type:z53.literal("search"),queries:z53.array(z53.string().min(1).max(256)).min(1).max(12),searchWindow:z53.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z53.number().int().min(1).max(50).optional(),includeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z53.object({name:z53.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z53.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z53.string().min(1).max(2e3).optional(),judgeEnabled:z53.boolean().optional(),retentionDays:z53.number().int().min(1).max(365).optional(),notification:z53.object({email:z53.object({enabled:z53.boolean().default(!0),recipients:z53.array(z53.string().email()).min(1).max(20),includeDiffs:z53.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=z53.object({monitorId:z53.string().uuid(),name:z53.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z53.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z53.string().min(1).max(2e3).optional(),judgeEnabled:z53.boolean().optional(),retentionDays:z53.number().int().min(1).max(365).optional(),status:z53.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z53.object({monitorId:z53.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z53.string().uuid()}),RunProjectIntegrationToolRequestSchema=z53.object({tool:z53.string().min(1),input:z53.record(z53.string(),z53.unknown()),connectionAlias:z53.string().min(1).optional(),approval:z53.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z53.object({provider:z53.string().min(1),providerCredits:z53.number().nonnegative().optional(),providerCostUsd:z53.number().nonnegative().optional(),requests:z53.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z53.object({credits:z53.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),title:z53.string().optional(),statusCode:z53.number().optional(),markdown:z53.string().optional(),summary:z53.string().optional(),links:z53.array(z53.string()).optional(),images:z53.array(z53.string()).optional(),html:z53.string().optional(),json:z53.unknown().optional(),branding:z53.record(z53.string(),z53.unknown()).optional(),warning:z53.string().optional()}),FirecrawlSearchToolOutputSchema=z53.object({query:z53.string(),provider:z53.literal("firecrawl"),warning:z53.string().optional(),results:z53.array(z53.object({title:z53.string(),url:z53.string(),snippet:z53.string().optional(),content:z53.string().optional(),score:z53.number().optional(),publishedAt:z53.string().optional()}))}),FirecrawlResearchPaperSchema=z53.object({paperId:z53.string(),primaryId:z53.string().optional(),ids:z53.record(z53.string(),z53.array(z53.string())).optional(),title:z53.string().optional(),abstract:z53.string().optional(),score:z53.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z53.object({text:z53.string(),score:z53.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(z53.object({id:z53.string(),type:z53.string().min(1).optional(),url:z53.string(),title:z53.string().optional(),passages:z53.array(z53.object({text:z53.string()}).passthrough())}).passthrough()),coverage:z53.record(z53.string(),z53.string()).optional(),reranked:z53.boolean().optional(),repos:z53.array(z53.record(z53.string(),z53.unknown())).optional(),sources:z53.array(z53.record(z53.string(),z53.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),paper:z53.record(z53.string(),z53.unknown()),paperId:z53.string().optional(),query:z53.string().optional(),passages:z53.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(FirecrawlResearchPaperSchema),poolSize:z53.number().int().nonnegative(),truncated:z53.boolean(),note:z53.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),count:z53.number(),links:z53.array(z53.object({url:z53.string(),title:z53.string().optional(),description:z53.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),total:z53.number(),pages:z53.array(z53.object({url:z53.string(),title:z53.string().optional(),statusCode:z53.number().optional(),markdown:z53.string().optional(),summary:z53.string().optional(),links:z53.array(z53.string()).optional(),images:z53.array(z53.string()).optional(),html:z53.string().optional(),warning:z53.string().optional()})),warning:z53.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z53.object({cron:z53.string().optional(),text:z53.string().optional(),timezone:z53.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z53.object({id:z53.string().optional(),type:z53.enum(["scrape","crawl","search"]).optional(),urls:z53.array(z53.string()).optional(),queries:z53.array(z53.string()).optional(),searchWindow:z53.string().optional(),maxResults:z53.number().optional(),includeDomains:z53.array(z53.string()).optional(),excludeDomains:z53.array(z53.string()).optional(),scrapeOptions:z53.record(z53.string(),z53.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z53.object({id:z53.string(),name:z53.string(),status:z53.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z53.string().nullable().optional(),lastRunAt:z53.string().nullable().optional(),currentCheckId:z53.string().nullable().optional(),targets:z53.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z53.string().nullable().optional(),judgeEnabled:z53.boolean().optional(),estimatedCreditsPerMonth:z53.number().optional(),createdAt:z53.string().optional(),updatedAt:z53.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z53.object({id:z53.string(),monitorId:z53.string(),scheduledFor:z53.string().nullable().optional(),startedAt:z53.string().nullable().optional(),finishedAt:z53.string().nullable().optional(),estimatedCredits:z53.number().nullable().optional(),reservedCredits:z53.number().nullable().optional(),actualCredits:z53.number().nullable().optional(),billingStatus:z53.string().nullable().optional(),summary:z53.object({totalPages:z53.number().optional(),same:z53.number().optional(),changed:z53.number().optional(),new:z53.number().optional(),removed:z53.number().optional(),error:z53.number().optional()}).passthrough().optional(),error:z53.string().nullable().optional(),createdAt:z53.string().optional(),updatedAt:z53.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitors:z53.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),deleted:z53.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),checks:z53.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),check:FirecrawlMonitorCheckOutputSchema,next:z53.string().optional()}),FirecrawlToolKeySchema=z53.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=z53.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z53.object({projectId:z53.uuid(),integrationKey:z53.string().min(1),tool:z53.string().min(1),connectionAlias:z53.string().min(1).nullable().optional(),output:z53.record(z53.string(),z53.unknown()),executedAt:z53.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z53.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z53.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z53.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z53.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z53.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z53.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z53.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z53.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z53.array(ProjectChannelCandidateDTOSchema))}});import{z as z54}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=z54.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z54.strictObject({scope:z54.string().min(1),reason:z54.string().min(1).max(200)}),IntegrationOAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("oauth"),actor:z54.literal("user").default("user"),authorizationUrl:z54.url(),tokenUrl:z54.url(),revocationUrl:z54.url().optional(),userInfoUrl:z54.url().optional(),client:z54.strictObject({idEnv:z54.string().min(1),secretEnv:z54.string().min(1)}),authorizeParams:z54.record(z54.string(),z54.string()).default({}),scopes:z54.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("apiKey"),keyLabel:z54.string().min(1).max(80),placeholder:z54.string().min(1).max(40).optional(),helpUrl:z54.url()}),IntegrationProviderAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("provider")}),IntegrationMcpAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("mcp"),methods:z54.array(McpIntegrationSetupAuthSchema).min(1),scopes:z54.array(z54.string().min(1)).min(1).optional(),header:z54.object({name:z54.string().min(1).max(80),valuePrefix:z54.string().max(80)}).optional()}),IntegrationAuthSchema=z54.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z54.strictObject({title:z54.string().min(1).max(80),description:z54.string().min(1).max(300),command:z54.string().min(1).optional()}),IntegrationSettingSchema=z54.strictObject({type:z54.enum(["string","choice"]),label:z54.string().min(1).max(80),description:z54.string().min(1).max(300).optional(),required:z54.boolean().default(!1),optionsFrom:z54.strictObject({tool:z54.string().min(1)}).optional()}),IntegrationToolsSchema=z54.discriminatedUnion("source",[z54.strictObject({source:z54.literal("hosted")}),z54.strictObject({source:z54.literal("mcp"),url:z54.url()})]),IntegrationSkillSchema=z54.strictObject({name:z54.string().min(1).max(64),description:z54.string().min(1).max(300),content:z54.string().min(1)}),IntegrationManifestSchema=z54.strictObject({apiVersion:z54.literal(1),id:IntegrationIdSchema,version:z54.string().regex(/^\d+\.\d+\.\d+$/),listing:z54.strictObject({name:z54.string().min(1).max(60),description:z54.string().min(1).max(200),details:z54.string().min(1).max(1e3),icon:z54.string().min(1),category:z54.enum(["seo","ai-visibility","analytics","communication"]),publisher:z54.string().min(1).max(60),agentReads:z54.strictObject({label:z54.string().min(1).max(80),description:z54.string().min(1).max(200)}).optional()}),auth:z54.array(IntegrationAuthSchema).min(1),identity:z54.strictObject({label:z54.string().min(1)}).optional(),settings:z54.record(z54.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z54.array(IntegrationSkillSchema).default([]),recipes:z54.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z54.object({scope:z54.string(),reason:z54.string()}),IntegrationSettingDefinitionDTOSchema=z54.object({key:z54.string(),type:z54.enum(["string","choice"]),label:z54.string(),description:z54.string().nullable(),required:z54.boolean(),hasOptions:z54.boolean()}),IntegrationKindSchema=z54.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z54.object({id:z54.string(),kind:IntegrationKindSchema,integrationKey:z54.string(),host:z54.string().nullable(),apiKey:z54.object({label:z54.string(),placeholder:z54.string().nullable(),helpUrl:z54.string(),primary:z54.boolean()}).nullable(),mcp:z54.object({url:z54.string(),methods:z54.array(McpIntegrationSetupAuthSchema),header:z54.object({name:z54.string(),valuePrefix:z54.string()}).nullable()}).nullable(),name:z54.string(),description:z54.string(),details:z54.string(),icon:z54.string(),category:z54.string(),publisher:z54.string(),signInLabel:z54.string(),permissions:z54.array(IntegrationPermissionDTOSchema),readOnly:z54.boolean(),settings:z54.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z54.object({connectionId:z54.uuid(),alias:z54.string(),accountName:z54.string().nullable(),status:z54.enum(["active","revoked"]),authKind:z54.enum(["oauth","api_key"]),connectedAt:z54.coerce.date()}),IntegrationSiteDTOSchema=z54.object({projectId:z54.uuid(),projectName:z54.string(),enabled:z54.boolean(),granted:z54.boolean(),connectionId:z54.uuid().nullable(),settings:z54.record(z54.string(),z54.string()),missingSettings:z54.array(z54.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z54.boolean(),accounts:z54.array(IntegrationAccountDTOSchema),siteAccess:z54.enum(["all","selected"]),sites:z54.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z54.boolean(),enabled:z54.boolean(),granted:z54.boolean(),accountName:z54.string().nullable(),settingsValues:z54.record(z54.string(),z54.string()),missingSettings:z54.array(z54.string()),tools:z54.array(z54.object({key:z54.string(),name:z54.string(),description:z54.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z54.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z54.object({projectId:z54.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z54.object({connectUrl:z54.url().nullable(),expiresAt:z54.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z54.string()}),ConnectIntegrationKeyRequestSchema=z54.object({key:z54.string().trim().min(1).max(500),projectId:z54.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z54.object({token:z54.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z54.object({enabled:z54.boolean(),connectionId:z54.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z54.object({access:z54.enum(["all","selected"]).optional(),projectIds:z54.array(z54.uuid()).max(1e3),connectionId:z54.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z54.object({settings:z54.record(z54.string(),z54.string().max(500))}),IntegrationSettingOptionDTOSchema=z54.object({value:z54.string(),label:z54.string(),suggested:z54.boolean()}),IntegrationToolMatchDTOSchema=z54.object({integrationId:z54.string(),integrationName:z54.string(),key:z54.string(),name:z54.string(),description:z54.string(),effect:IntegrationToolEffectSchema,input:z54.record(z54.string(),z54.unknown())}),ProjectIntegrationGuideDTOSchema=z54.object({integrationId:z54.string(),name:z54.string(),description:z54.string(),content:z54.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z54.object({tool:z54.string().min(1).max(120),input:z54.record(z54.string(),z54.unknown()).default({}),approval:z54.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z54.boolean().optional()}),IntegrationApprovalCallShape={integration:z54.object({id:z54.string(),name:z54.string()}),tool:z54.object({key:z54.string(),name:z54.string(),effect:IntegrationToolEffectSchema}),input:z54.record(z54.string(),z54.unknown()),reason:z54.string(),canAlwaysAllow:z54.boolean()},IntegrationToolRunResultDTOSchema=z54.discriminatedUnion("status",[z54.object({status:z54.literal("ok"),output:z54.record(z54.string(),z54.unknown())}),z54.object({status:z54.literal("approval_required"),request:z54.string(),approveUrl:z54.string(),...IntegrationApprovalCallShape}),z54.object({status:z54.literal("blocked"),reason:z54.string()})]),IntegrationApprovalPreviewRequestSchema=z54.object({request:z54.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z54.object({...IntegrationApprovalCallShape,allowOnce:z54.boolean(),expiresAt:z54.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z54.string()}),IntegrationApprovalDecisionSchema=z54.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z54.object({request:z54.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z54.object({decision:IntegrationApprovalDecisionSchema,approval:z54.string().optional(),resumed:z54.boolean().optional()}),IntegrationAgentAccessDTOSchema=z54.object({reads:z54.object({label:z54.string(),description:z54.string()}).nullable(),tools:z54.array(z54.object({tool:z54.string(),label:z54.string(),description:z54.string(),allowed:z54.boolean()}))})}});import{z as z55}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=z55.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z55.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z55.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z55.object({userId:z55.string().min(1),name:z55.string(),email:z55.string().min(1),subscribed:z55.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z55.object({maxSubscribers:z55.number().int().positive(),subscriberCount:z55.number().int().nonnegative(),effectiveRecipientCount:z55.number().int().nonnegative(),currentUserSubscribed:z55.boolean(),candidates:z55.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z55.object({userIds:z55.array(z55.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z55.object({topic:UserManagedNotificationTopicSchema,enabled:z55.boolean(),source:z55.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z55.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z55.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z55.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z55.string().nullable(),maskedEmail:z55.string().min(1),applied:z55.boolean(),expiresAt:z55.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z55.object({scheduleId:z55.string().min(1),scheduleName:z55.string(),projectId:z55.string().min(1),projectName:z55.string(),env:z55.string().min(1)}),FollowedSchedulesSchema=z55.object({schedules:z55.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z56}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=z56.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=z56.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z56.uuid(),env:z56.string().min(1),name:z56.string().min(1),cron:z56.string().min(1),command:z56.string().min(1),secretKeys:z56.array(z56.string().min(1)),enabled:z56.boolean(),lastRunAt:z56.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z56.string().nullable(),suspendedAt:z56.coerce.date().nullable().optional(),suspensionReason:z56.string().nullable().optional(),overPolicyReasons:z56.array(z56.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z56.object({name:z56.string().min(1).max(120),cron:z56.string().min(1).max(120),command:z56.string().min(1).max(500),secretKeys:z56.array(ProjectSecretKeySchema).default([]),enabled:z56.boolean().optional()}),UpdateProjectScheduleRequestSchema=z56.object({name:z56.string().min(1).max(120).optional(),cron:z56.string().min(1).max(120).optional(),command:z56.string().min(1).max(500).optional(),secretKeys:z56.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z56.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z56.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z56.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z56.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z56.object({maxRuns:z56.number().int().positive(),retentionDays:z56.number().int().positive().nullable(),outputRetentionDays:z56.number().int().positive(),maxOutputBytes:z56.number().int().positive()}),SchedulePolicyStateSchema=z56.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z56.object({code:z56.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z56.enum(["cached_subscription","free_fallback"]),activeSchedules:z56.object({used:z56.number().int().nonnegative(),limit:z56.number().int().nonnegative()}),minCadenceMinutes:z56.number().int().positive(),maxRunMs:z56.number().int().positive(),concurrency:z56.object({used:z56.number().int().nonnegative(),limit:z56.number().int().positive()}),compute:z56.object({settledMs:z56.number().int().nonnegative(),activeMs:z56.number().int().nonnegative(),reservedMs:z56.number().int().nonnegative().optional(),includedMs:z56.number().int().nonnegative(),remainingMs:z56.number().int().nonnegative(),resetsAt:z56.coerce.date()}),upgrade:z56.object({code:z56.literal("Pro"),activeSchedulesLimit:z56.number().int().positive(),minCadenceMinutes:z56.number().int().positive(),maxRunMs:z56.number().int().positive(),maxConcurrentRuns:z56.number().int().positive(),computeIncludedMs:z56.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z56.array(z56.string())}),ProjectScheduleUsageSchema=z56.object({runCount:z56.number().int().nonnegative(),runsWithOutput:z56.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z56.object({id:z56.uuid(),scheduleId:z56.uuid(),projectId:z56.uuid(),env:z56.string().min(1),scheduleName:z56.string().min(1),command:z56.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z56.object({id:z56.string().min(1),name:z56.string().min(1)}).nullable(),queuedAt:z56.coerce.date(),startedAt:z56.coerce.date().nullable(),finishedAt:z56.coerce.date().nullable(),exitCode:z56.number().int().nullable(),errorCode:z56.string().nullable(),error:z56.string().nullable(),outputBytes:z56.number().int().nonnegative(),outputTruncated:z56.boolean(),outputExpiresAt:z56.coerce.date().nullable(),metadataExpiresAt:z56.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z56.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z56.coerce.date().nullable(),items:z56.array(z56.object({key:z56.string().min(1),updatedAt:z56.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z56.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z56.object({trigger:z56.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z56.object({limit:z56.coerce.number().int().min(1).max(100).default(25),cursor:z56.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z56.object({items:z56.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z56.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z56.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z56.object({items:z56.array(ProjectScheduleRunDTOSchema),nextCursor:z56.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z57}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=z57.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z57.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z57.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z57.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z57.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z57.discriminatedUnion("kind",[z57.object({kind:z57.literal("user"),userId:z57.string().min(1)}).strict(),z57.object({kind:z57.literal("agent"),agentKey:z57.string().min(1).max(120),agentId:z57.uuid().optional()}).strict(),z57.object({kind:z57.literal("system")}).strict()]),NotificationSummarySchema=z57.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z57.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z57.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z57.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z57.object({sessionId:z57.uuid(),branch:z57.string().min(1),targetBranch:z57.string().min(1),revision:z57.string().min(1),fingerprint:z57.string().min(1)}),NotificationPayloadSchema=z57.discriminatedUnion("topic",[z57.object({topic:z57.literal("database_quota_exceeded"),incidentId:z57.uuid(),observedAt:z57.iso.datetime()}).strict(),z57.object({topic:z57.literal("agent_run_outcome"),threadId:z57.uuid(),invocationId:z57.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("agent_retained_review"),threadId:z57.uuid().optional(),invocationId:z57.uuid().optional(),proposalId:z57.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("agent_conflict"),mergeId:z57.uuid(),threadId:z57.uuid().optional(),invocationId:z57.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("publication_failed"),publicationId:z57.uuid(),sourceBranch:z57.string().trim().min(1).max(120),failureCode:z57.string().trim().min(1).max(64),failedAt:z57.iso.datetime(),firstPublication:z57.boolean()}).strict()]),NotificationEnvelopeSchema=z57.object({id:z57.uuid(),projectId:z57.uuid(),sourceKey:z57.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z57.literal(1),payload:NotificationPayloadSchema,createdAt:z57.coerce.date()}),NotificationDeliveryStateSchema=z57.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z57.object({id:z57.uuid(),notificationRecipientId:z57.uuid(),projectId:z57.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z57.number().int().nonnegative(),nextAttemptAt:z57.coerce.date().nullable(),lastAttemptAt:z57.coerce.date().nullable(),sentAt:z57.coerce.date().nullable(),failureCode:z57.string().max(80).nullable(),createdAt:z57.coerce.date(),updatedAt:z57.coerce.date()}),NotificationPreferenceSchema=z57.object({topic:WorkNotificationTopicSchema,channel:z57.literal("email"),enabled:z57.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z57.enum(["default","explicit"])})}});import{z as z58}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=z58.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=z58.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z58.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z58.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z58.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z58.object({enabled:z58.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z58.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z58.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z58.discriminatedUnion("kind",[z58.object({kind:z58.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z58.enum(["work_review","publishing","schedule"]),enabled:z58.boolean(),source:PreferenceSourceSchema}).strict(),z58.object({kind:z58.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z58.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z58.object({kind:z58.literal("provider_subscription"),id:z58.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z58.literal("marketing"),name:z58.string(),description:z58.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z58.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z58.object({email:EmailNotificationPreferenceSchema,entries:z58.array(NotificationPreferenceEntrySchema),unavailableGroups:z58.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z58.object({enabled:z58.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z58.discriminatedUnion("kind",[z58.object({kind:z58.literal("toggle"),enabled:z58.boolean()}).strict(),z58.object({kind:z58.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z58.object({kind:z58.literal("provider_subscription"),enabled:z58.boolean()}).strict()])}});import{z as z59}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=z59.object({surface:SurfaceNameSchema,key:z59.string(),label:z59.string()}),InlineSchema=z59.object({text:z59.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z59.discriminatedUnion("type",[z59.object({type:z59.literal("paragraph"),content:z59.array(InlineSchema).max(24)}),z59.object({type:z59.literal("preview"),ref:DiffRefSchema,caption:z59.string().optional()}),z59.object({type:z59.literal("code"),code:z59.string(),lang:z59.string().optional(),caption:z59.string().optional()}),z59.object({type:z59.literal("risk"),level:z59.enum(["warning","error"]),content:z59.array(InlineSchema).max(24)}),z59.object({type:z59.literal("list"),items:z59.array(z59.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z59.object({headline:z59.string(),blocks:z59.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z59.object({summary:EnvDiffSummarySchema,fingerprint:z59.string(),generatedAt:z59.coerce.date(),cached:z59.boolean().optional(),credits:z59.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z60}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=z60.object({date:z60.string(),visitors:z60.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z60.object({key:z60.string(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z60.object({path:z60.string(),pageName:z60.string().nullable().optional(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z60.object({preset:z60.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z60.string(),requestedTo:z60.string(),effectiveFrom:z60.string(),effectiveTo:z60.string(),isRetentionLimited:z60.boolean(),groupBy:z60.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z60.object({date:z60.string(),content:z60.string(),updatedAt:z60.string(),updatedByUserId:z60.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z60.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z60.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative(),botPageviews:z60.number().int().nonnegative(),botVisitors:z60.number().int().nonnegative(),bounceRate:z60.number().min(0).max(100),viewsPerVisit:z60.number().nonnegative(),averageVisitDurationSeconds:z60.number().nonnegative(),visitorsSeries:z60.array(ProjectDailyVisitorsDTOSchema),topPages:z60.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z60.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z60.object({state:z60.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z60.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z61}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=z61.object({id:z61.string(),email:z61.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z61.coerce.date(),createdAt:z61.coerce.date(),inviterUserId:z61.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z61.object({id:z61.string(),token:z61.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z61.object({success:z61.boolean(),projectId:z61.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z62}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=z62.object({id:z62.string(),name:z62.string(),image:z62.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z62.object({count:z62.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z62.object({counts:z62.object({signed_up:z62.int(),activated:z62.int()}),credits:z62.object({total:z62.int(),earned:z62.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z62.email(),emailVerified:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z63}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=z63.object({id:z63.string(),principalType:ProjectPrincipalTypeSchema,principalId:z63.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z63.coerce.date(),expiresAt:z63.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z63.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:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z63.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z63.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z63.record(z63.string(),z63.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z63.object({access:z63.array(ProjectAccessItemDTOSchema),invites:z63.array(ProjectInviteDTOSchema),organization:z63.object({name:z63.string().nullable(),logo:z63.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z63.object({success:z63.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z63.object({success:z63.boolean(),projectId:z63.uuid()}))}});import{z as z64}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=z64.object({publicationStatus:PublicationStatusSchema,appUrl:z64.string().nullable(),lastPublishedAt:z64.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z65}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=z65.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z65.object({branch:BranchSchema,revision:z65.string().min(1).max(64).nullable(),generation:z65.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z65.url().nullable()})}});import{z as z66}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=z66.object({code:z66.literal("PREVIEW_UPGRADE_REQUIRED"),message:z66.string(),currentVersion:z66.number().int().positive(),targetVersion:z66.literal(4)}),PreviewBridgePackageSchema=z66.object({name:z66.string().min(1),version:z66.string().min(1)}),PreviewBridgeCapabilitySchema=z66.object({integrated:z66.boolean(),packages:z66.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z66.object({url:z66.url(),expiresAt:z66.iso.datetime().nullable(),source:z66.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z66.object({name:z66.string().min(1),locator:z66.string().min(1).optional(),source:z66.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z66.object({kind:z66.literal("dependency_build_scripts_blocked"),packageManager:z66.enum(["pnpm","yarn","bun"]),packages:z66.array(z66.string()),targets:z66.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z66.string(),approvalKey:z66.string(),command:z66.string().optional(),approval:z66.object({id:z66.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z66.object({code:z66.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z66.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z66.object({code:z66.literal("PREVIEW_START_FAILED"),message:z66.string(),logTail:z66.array(z66.string()).optional(),logTailTruncated:z66.boolean().optional()}),SandboxPullPhaseSchema=z66.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z66.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z66.object({message:z66.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z66.number().int().optional().catch(void 0),logTail:z66.array(z66.string()).optional().catch(void 0),logTailTruncated:z66.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z66.object({approvalId:z66.uuid()}),PreviewInstallPolicyApprovalEventSchema=z66.discriminatedUnion("type",[z66.object({type:z66.literal("progress"),step:z66.enum(["approval","install","restart","readiness"]),message:z66.string()}),z66.object({type:z66.literal("approved")}),z66.object({type:z66.literal("complete")}),z66.object({type:z66.literal("error"),code:z66.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z66.string()})])}});import{z as z67}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:z67.string(),slug:z67.string().nullable(),logo:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z67.object({id:z67.string(),name:z67.string(),email:z67.email(),image:z67.string().nullable()}),OrganizationMemberDTOSchema=z67.object({id:z67.string(),userId:z67.string(),organizationId:z67.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z67.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z67.object({canCreateProject:z67.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z68}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=z68.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z68.object({reason:CancellationReasonCodeSchema,details:z68.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z68.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z68.object({offerVersion:z68.string().trim().min(1),unusedPremiumCreditAmount:z68.number().int().nonnegative(),amountDueNow:z68.number().int().nonnegative(),renewsOn:z68.string()}),PlanMigrationPreviewDTOSchema=z68.object({currency:z68.string().trim().min(1),unusedPremiumCreditAmount:z68.number().int().nonnegative(),amountDueNow:z68.number().int().nonnegative(),startsAt:z68.string(),renewsAt:z68.string(),nextRenewalAmount:z68.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z68.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z68.object({id:z68.string(),organizationId:z68.string(),legacySubscriptionId:z68.string(),offeredPlanCode:z68.string(),offeredPlanName:z68.string(),offeredPriceAmount:z68.number(),offeredCurrency:z68.string(),offerVersion:z68.string(),state:PlanMigrationStateSchema,checkoutToken:z68.string().nullable(),deadlineAt:z68.string(),transitions:z68.array(z68.object({event:z68.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z68.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z68.object({included:z68.number().optional(),unitPrice:z68.number().optional(),dailyCap:z68.number().nullable().optional()}),EntitlementsDTOSchema=z68.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z68.object({retentionDays:z68.number().int().positive(),canUseExtendedDateRanges:z68.boolean()}).optional(),history:z68.object({retentionDays:z68.number().int().positive()}).optional(),members:z68.object({canInvite:z68.boolean(),maxMembers:z68.number().int().positive().nullable()}).optional(),projects:z68.object({maxProjects:z68.number().int().positive().nullable()}).optional(),domains:z68.object({canUseCustomDomains:z68.boolean(),maxDomains:z68.number().int().nonnegative().nullable()}).optional(),media_storage:z68.object({limitBytes:z68.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z68.object({usedBytes:z68.number().int().nonnegative().nullable(),limitBytes:z68.number().int().nonnegative().nullable(),state:z68.enum(["ready","unavailable"]),measuredAt:z68.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z68.object({toPlanCode:TemplateCodeSchema,effectiveAt:z68.string(),scheduledAt:z68.string().nullable()}),AutomaticSpendStopDTOSchema=z68.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z68.string(),spendStopped:z68.boolean(),settlementEndsAt:z68.string()}),HostingOverageStatusDTOSchema=z68.object({state:z68.enum(["ready","unavailable"]),planCode:z68.string(),overageAvailable:z68.boolean(),overageEnabled:z68.boolean(),monthlyCapUsd:z68.number().int().positive().nullable(),periodStart:z68.iso.datetime().nullable(),periodEnd:z68.iso.datetime().nullable(),usedBytes:z68.number().nonnegative().nullable(),includedBytes:z68.number().nonnegative().nullable(),overageBytes:z68.number().nonnegative(),currentOverageAmountMicros:z68.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z68.number().nonnegative().nullable(),currency:z68.string().nullable(),status:z68.enum(["ok","near_limit","paused"]),databaseCompute:z68.object({includedHoursPerSite:z68.number().nonnegative().nullable(),overageHours:z68.number().nonnegative(),fundedHours:z68.number().nonnegative(),sitesOverAllowance:z68.number().int().nonnegative(),rateMicrosPerHour:z68.number().nonnegative().nullable(),amountMicros:z68.number().nonnegative().nullable(),budgetSpent:z68.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z68.object({enabled:z68.boolean(),monthlyCapUsd:z68.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z68.object({id:z68.string(),external_id:z68.string(),customerId:z68.string(),planId:z68.string(),planCode:z68.union([TemplateCodeSchema,z68.literal("Unknown")]),currentPeriod:z68.object({start:z68.string(),end:z68.string().nullable()}),cancelAt:z68.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z68.string(),nextPaymentAt:z68.string().nullable(),baseAmount:z68.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z68.object({totalCap:z68.number(),dailyCap:z68.number(),usedTotal:z68.number()}),CreditBalanceDTOSchema=z68.object({total:z68.number(),base:z68.number(),dailyBase:z68.number(),purchases:z68.number(),awards:z68.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z68.object({total:z68.number(),nearLimit:z68.boolean(),canChat:z68.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z68.object({dailyFreeAvailable:z68.number(),monthlyAvailable:z68.number(),purchasedAvailable:z68.number(),awardedAvailable:z68.number()}),ProjectDailyCreditAllowanceDTOSchema=z68.object({periodCap:z68.number(),dailyGrant:z68.number(),usedThisPeriod:z68.number(),remainingThisPeriod:z68.number()}),ProjectCreditBalanceDTOSchema=z68.object({projectId:z68.uuid(),organizationId:z68.string(),balance:z68.object({totalAvailable:z68.number(),nearLimit:z68.boolean(),canUseAi:z68.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z68.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z68.discriminatedUnion("enabled",[z68.object({enabled:z68.literal(!0),thresholdUsd:z68.number().nonnegative(),refillAmountUsd:z68.number().nonnegative()}),z68.object({enabled:z68.literal(!1),thresholdUsd:z68.number().nonnegative().nullable(),refillAmountUsd:z68.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z68.discriminatedUnion("enabled",[z68.object({enabled:z68.literal(!0),thresholdUsd:z68.number().min(.01).multipleOf(.01),refillAmountUsd:z68.number().min(.01).multipleOf(.01),expectedRateToken:z68.string().trim().min(1).max(40)}).strict(),z68.object({enabled:z68.literal(!1),thresholdUsd:z68.number().min(.01).multipleOf(.01),expectedRateToken:z68.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z68.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z68.object({planCode:z68.union([TemplateCodeSchema,z68.literal("Unknown")]).nullable(),canPurchase:z68.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z68.number().int().positive(),minAmountUsd:z68.number().positive(),maxAmountUsd:z68.number().positive(),rateToken:z68.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z68.object({amountUsd:z68.number(),idempotencyKey:z68.string().trim().min(8).max(120),expectedRateToken:z68.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z68.object({invoiceId:z68.string(),newBalance:z68.int(),creditCount:z68.int(),amountUsd:z68.number(),creditsPerDollar:z68.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z68.object({url:z68.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z68.object({id:z68.string(),number:z68.string().nullable(),status:z68.string(),amountDue:z68.int(),currency:z68.string(),issuedAt:z68.string().nullable(),hostedInvoiceUrl:z68.string().nullable()}),PaymentRecoveryDTOSchema=z68.discriminatedUnion("status",[z68.object({status:z68.literal("eligible"),checkedAt:z68.string()}),z68.object({status:z68.literal("recovery_required"),checkedAt:z68.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z68.int().min(1)}),z68.object({status:z68.literal("unavailable"),checkedAt:z68.string(),reason:z68.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 z69}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=z69.object({brand:z69.string(),last4:z69.string(),exp:z69.string(),isDefault:z69.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z70}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=z70.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=z70.object({type:z70.literal("renameField"),contentType:z70.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z70.object({enabled:z70.boolean()}).strict(),ContentFieldGroupSchema=z70.object({id:z70.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z70.string().min(1).max(255),default:z70.boolean().optional()}).strict(),ContentTypeDTOSchema=z70.object({id:z70.string(),name:z70.string(),label:z70.string(),isSingleton:z70.boolean(),i18n:ContentTypeI18nSchema,description:z70.string().nullable().default(null),groups:z70.array(ContentFieldGroupSchema).default([]),fields:z70.record(z70.string(),FieldDefinitionSchema),createdAt:z70.string(),updatedAt:z70.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z70.object({contentTypes:z70.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z70.object({id:z70.string(),entryId:z70.string(),documentId:z70.string(),slug:z70.string(),locale:z70.string().optional(),createdAt:z70.string(),updatedAt:z70.string(),__fimo:z70.object({contentType:z70.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({limit:z70.number(),offset:z70.number(),total:z70.number(),hasMore:z70.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z70.object({contentType:z70.string(),count:z70.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z70.object({counts:z70.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z70.object({count:z70.number().int().nonnegative(),sourceLocale:z70.string(),targetLocale:z70.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z70.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z70.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z70.union([z70.string(),z70.number(),z70.boolean(),z70.null()]),entryWhereOperatorSchema=z70.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z70.array(entryWhereScalarSchema).optional(),$nin:z70.array(entryWhereScalarSchema).optional(),$contains:z70.string().optional(),$startsWith:z70.string().optional(),$null:z70.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z70.record(z70.string(),z70.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z70.record(z70.string(),z70.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z70.object({data:z70.record(z70.string(),z70.unknown()),locale:z70.string().min(1).optional(),documentId:z70.uuid().optional()}),entryIdsSchema=z70.array(z70.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z70.object({sql:z70.string().min(1)}),BulkCreateEntriesRequestSchema=z70.object({entries:z70.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z70.union([z70.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z70.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z70.object({updates:z70.array(z70.object({id:z70.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z70.union([z70.object({ids:entryIdsSchema,locale:z70.string().min(1).optional()}),z70.object({where:EntryWhereSchema,locale:z70.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z70.object({data:z70.array(z70.record(z70.string(),z70.unknown())),meta:z70.object({rowCount:z70.number().int().nonnegative(),truncated:z70.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({created:z70.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({updated:z70.number().int().nonnegative(),missing:z70.array(z70.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({deleted:z70.number().int().nonnegative(),missing:z70.array(z70.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z71}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z71.object({index:z71.number().int().nonnegative(),contentType:z71.string(),field:z71.string(),value:z71.string(),against:z71.enum(["stored","batch"]),ownerDocumentId:z71.uuid().optional(),ownerIndex:z71.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z71.object({code:z71.literal("unique_conflict"),message:z71.string(),conflicts:z71.array(UniqueConflictSchema),truncated:z71.boolean().optional()})}});import{z as z72}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=z72.object({kind:z72.literal("unique_conflict"),contentType:z72.string(),field:z72.string(),value:z72.string(),documentCount:z72.number().int().positive(),documentIds:z72.array(z72.uuid()),documentIdsTruncated:z72.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z72.object({code:z72.literal("schema_transition_rejected"),message:z72.string(),issues:z72.array(SchemaTransitionIssueSchema),truncated:z72.boolean().optional()})}});import{z as z73}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=z73.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z73.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z73.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z73.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z73.object({field:CmsFieldNameSchema,direction:z73.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z73.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z73.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z73.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z73.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z73.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z74}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=z74.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z75}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=z75.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z75.object({event:ClientTrackedEventSchema,properties:z75.record(z75.string(),z75.unknown()).default({})})}});import{z as z76}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=z76.object({id:z76.string(),name:z76.string()}),AssetDTOSchema=z76.object({id:z76.string(),name:z76.string(),type:AssetTypeSchema,originalFileName:z76.string().nullable(),parentId:z76.string().nullable(),mimeType:z76.string().nullable(),fileSize:z76.number().nullable(),url:z76.string().nullable(),storageKey:z76.string().nullable(),createdAt:z76.string(),updatedAt:z76.string(),altText:z76.string().nullable().optional(),caption:z76.string().nullable().optional(),aiCaption:z76.string().nullable().optional(),aiAltText:z76.string().nullable().optional(),aiTags:z76.array(z76.string()).nullable().optional(),aiPrimaryColor:z76.string().nullable().optional(),aiProcessingStatus:z76.string().nullable().optional(),width:z76.number().nullable().optional(),height:z76.number().nullable().optional(),path:z76.array(AssetPathItemSchema).optional(),hasChildren:z76.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z76.lazy(()=>z76.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z76.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z76.object({error:z76.string(),code:z76.literal("media_storage_limit_exceeded"),usedBytes:z76.number().int().nonnegative(),limitBytes:z76.number().int().positive(),incomingBytes:z76.number().int().nonnegative()}),AssetReferenceScopeSchema=z76.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z76.object({assetIds:z76.array(z76.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z76.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z76.object({totalFiles:z76.number().int().nonnegative(),checkedFiles:z76.number().int().nonnegative(),limit:z76.number().int().positive()}),AssetReferenceFindingDTOSchema=z76.object({assetId:z76.uuid(),entryId:z76.string(),documentId:z76.string(),contentType:z76.string(),locale:z76.string().nullable(),slug:z76.string(),fieldPath:z76.string()}),AssetReferenceScopeResultDTOSchema=z76.object({scope:AssetReferenceScopeSchema,label:z76.string(),state:z76.enum(["available","not-published","failed"]),coverage:z76.enum(["complete","partial","failed"]),referenceCount:z76.number().int().nonnegative().optional(),codeReferenceCount:z76.number().int().nonnegative().optional(),referencedAssetIds:z76.array(z76.uuid()).optional(),references:z76.array(AssetReferenceFindingDTOSchema),reason:z76.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z76.discriminatedUnion("type",[z76.object({type:z76.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z76.object({type:z76.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z76.object({type:z76.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z76.object({replacementAssetId:z76.uuid()}),AssetReferenceReplacementResultSchema=z76.object({referencesReplaced:z76.number().int().nonnegative(),entriesChanged:z76.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z76.object({referencesReplaced:z76.number().int().nonnegative(),filesChanged:z76.number().int().nonnegative(),commitSha:z76.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z76.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=z76.object({error:z76.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z76.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=z76.object({intent:AssetRemovalIntentSchema,assetIds:z76.array(z76.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z76.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=z76.object({id:z76.uuid(),intent:AssetRemovalIntentSchema,assetIds:z76.array(z76.uuid()),replacementAssetId:z76.uuid().nullable(),expiresAt:z76.iso.datetime(),undoable:z76.boolean(),requestedByMe:z76.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z76.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z76.object({error:z76.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z77}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z77.object({key:z77.string(),value:z77.string().optional(),defaultValue:z77.string(),locale:z77.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z78}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=z78.object({id:z78.string(),name:z78.string(),type:z78.enum(["file","folder"]),path:z78.string(),children:z78.lazy(()=>z78.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z78.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z78.object({path:z78.string(),exists:z78.boolean(),type:z78.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z79}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=z79.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z79.object({minLength:z79.number().optional(),maxLength:z79.number().optional(),min:z79.number().optional(),max:z79.number().optional(),pattern:z79.string().optional(),maxFileSize:z79.number().optional(),accept:z79.array(z79.string()).optional()}),FormFieldSchema=z79.object({type:FormFieldTypeSchema,label:z79.string(),placeholder:z79.string().optional(),required:z79.boolean().optional(),defaultValue:z79.string().optional(),options:z79.array(z79.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z79.record(z79.string(),FormFieldSchema),FormContentSchema=z79.object({name:z79.string().min(1).max(255),label:z79.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 z80}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z80.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z80.object({id:z80.string().uuid(),label:z80.string(),status:ChatTaskStatusSchema,startedAt:z80.string(),endedAt:z80.string().nullable(),result:z80.string().nullable()}),ChatTaskListDTOSchema=z80.object({tasks:z80.array(ChatTaskDTOSchema)})}});import{z as z81}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=z81.object({name:z81.string().trim().min(1).max(120).optional(),description:z81.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z81.string().min(1)).optional(),live:z81.literal(!0).optional()}),AgentToolInputSchema=AgentPatchSchema.extend({create:z81.literal(!0).optional()}),AgentToolRoutineSchema=z81.object({id:z81.string(),name:z81.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z81.string().nullable()}),AgentToolErrorCodeSchema=z81.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z81.discriminatedUnion("ok",[z81.object({ok:z81.literal(!0),agent:z81.object({id:z81.string(),name:z81.string(),live:z81.boolean(),routines:z81.array(AgentToolRoutineSchema)}),revisionId:z81.string().optional()}),z81.object({ok:z81.literal(!1),error:z81.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z81.object({kind:z81.enum(["person","agent"]),id:z81.string().nullable(),name:z81.string().nullable()}),AgentInstructionRevisionDTOSchema=z81.object({id:z81.string().uuid(),previous:z81.string().nullable(),instructions:z81.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z81.string()}),AgentInstructionRevisionListDTOSchema=z81.object({revisions:z81.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z81.object({revisionId:z81.string().uuid()})}});import{z as z82}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=z82.object({url:z82.string().url(),key:z82.string(),size:z82.number(),contentType:z82.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z83}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=z83.object({canAccess:z83.boolean(),permissions:z83.record(z83.string(),z83.boolean()),role:z83.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z84}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:z84.string().trim().default(""),sort:z84.enum(["recent","name","relevance"]).default("recent"),category:z84.string().optional()})}});import{z as z85}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=z85.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z85.enum(["fimo","external"]),PaymentStatusSchema=z85.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z85.object({id:z85.string().uuid(),domain:z85.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z85.boolean(),price:z85.number().int().nullable(),renewalPrice:z85.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z85.string().nullable(),failureReason:z85.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z85.object({domain:z85.string(),available:z85.boolean(),premium:z85.boolean(),price:z85.number().nullable(),renewalPrice:z85.number().nullable(),purchaseType:z85.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z85.object({domain:z85.string(),price:z85.number().nullable(),renewalPrice:z85.number().nullable(),premium:z85.boolean(),allowedYears:z85.array(z85.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z85.object({firstName:z85.string().max(100),lastName:z85.string().max(100),companyName:z85.string().max(100).optional(),address1:z85.string().max(255),address2:z85.string().max(255).optional(),city:z85.string().max(100),state:z85.string().max(100),zip:z85.string().max(20),country:z85.string().max(2),phone:z85.string().max(30),email:z85.union([z85.string().email().max(255),z85.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z85.object({firstName:z85.string().min(1).max(100),lastName:z85.string().min(1).max(100),companyName:z85.string().max(100).optional(),address1:z85.string().min(1).max(255),address2:z85.string().max(255).optional(),city:z85.string().min(1).max(100),state:z85.string().min(1).max(100),zip:z85.string().min(1).max(20),country:z85.string().min(1).max(2),phone:z85.string().min(1).max(30),email:z85.string().email().max(255)}),SearchDomainsRequestSchema=z85.object({keyword:z85.string().min(1).max(100),tldFilter:z85.array(z85.string()).optional()}),CheckAvailabilityRequestSchema=z85.object({domains:z85.array(z85.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=z85.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z85.object({domain:DomainNameSchema,years:z85.number().int().min(1).max(10).optional().default(3),autoRenew:z85.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z85.object({autoRenew:z85.boolean().optional()}),RenewDomainRequestSchema=z85.object({years:z85.number().int().min(1).max(10).optional().default(1),autoRenew:z85.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z85.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z85.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z85.object({verified:z85.boolean(),email:z85.string().nullable(),verifyBy:z85.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z86}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=z86.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=z86.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=z86.object({txtName:z86.string().nullable().optional(),txtValue:z86.string().nullable().optional(),httpUrl:z86.string().nullable().optional(),httpBody:z86.string().nullable().optional(),cname:z86.string().nullable().optional(),cnameTarget:z86.string().nullable().optional()}),SSLValidationErrorSchema=z86.object({message:z86.string()}),OwnershipVerificationSchema=z86.object({type:z86.string(),name:z86.string(),value:z86.string()}),ProjectDomainSSLDTOSchema=z86.object({status:z86.string(),method:z86.string().nullable(),type:z86.string().nullable(),validationRecords:z86.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z86.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z86.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z86.enum(["subdomain","apex"]),RedirectStatusSchema=z86.union([z86.literal(301),z86.literal(302),z86.literal(307),z86.literal(308)]),DomainRedirectSchema=z86.object({targetDomainId:z86.string(),targetHostname:z86.string(),status:RedirectStatusSchema}).nullable(),ProjectDomainDTOSchema=z86.object({id:z86.string(),hostname:z86.string(),status:z86.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z86.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z86.string(),scdCnameTarget:z86.string().optional(),apexTargets:z86.array(z86.string()),dnsAutoConfigured:z86.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirect:DomainRedirectSchema,migrationStatus:z86.string().nullable().optional(),primary:z86.boolean()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z86.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z86.object({hostname:z86.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:z86.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z86.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z86.object({available:z86.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z86.object({success:z86.boolean(),hostname:z86.string(),removed:z86.array(z86.object({id:z86.string(),hostname:z86.string()}))})),DEFAULT_REDIRECT_STATUS=307,SetProjectDomainRedirectRequestSchema=z86.object({targetDomainId:z86.uuid().toLowerCase(),status:RedirectStatusSchema.default(DEFAULT_REDIRECT_STATUS)})}});import{z as z87}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=z87.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z87.object({available:z87.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z87.object({slug:z87.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z87.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z87.object({subdomain:z87.string(),subdomainUpdatedAt:z87.coerce.date()})),SubdomainSuggestionsQuerySchema=z87.object({base:z87.string().max(100).optional(),max:z87.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z87.object({suggestions:z87.array(z87.string())}))}});import{z as z88}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","source_registered_domain"],ProjectTransferBlockerCodeSchema=z88.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z88.object({code:ProjectTransferBlockerCodeSchema,message:z88.string(),count:z88.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z88.object({targetOrganizationId:z88.string().min(1)}),ProjectTransferResultDTO=createDTO(z88.object({projectId:z88.string(),sourceOrganizationId:z88.string(),targetOrganizationId:z88.string(),movedThreads:z88.number().int().nonnegative(),revokedInvites:z88.number().int().nonnegative(),revokedGrants:z88.number().int().nonnegative(),preservedGrants:z88.number().int().nonnegative(),warnings:z88.array(z88.string())}))}});import{z as z89}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=z89.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z89.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=z89.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z89.object({displayName:z89.string().trim().min(1).max(80),machineId:z89.string().trim().min(1).max(128).optional(),cliVersion:z89.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z89.object({ttlHours:z89.number().int().positive(),lockedFeatures:z89.array(UnclaimedLockedFeatureSchema),media:z89.object({totalBytes:z89.number().int().nonnegative(),fileBytes:z89.number().int().positive(),maxFiles:z89.number().int().nonnegative(),mimeTypes:z89.array(z89.string())}),database:z89.object({storageBytes:z89.number().int().positive(),computeSeconds:z89.number().int().positive(),maxComputeUnits:z89.number().positive()})}),UnclaimedProjectClaimSchema=z89.object({url:z89.string().url(),expiresAt:z89.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z89.object({project:ProjectDTOSchema,token:z89.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z89.object({state:UnclaimedClaimStateSchema,displayName:z89.string().nullable(),expiresAt:z89.coerce.date().nullable(),projectId:z89.string().nullable()})),UnclaimedClaimSecretSchema=z89.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z89.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z89.object({secrets:z89.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z89.object({claims:z89.array(z89.object({state:UnclaimedClaimStateSchema,expiresAt:z89.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z89.object({secret:UnclaimedClaimSecretSchema,organizationId:z89.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z89.object({projectId:z89.string(),organizationId:z89.string()})),ProjectTokenSelfDTO=createDTO(z89.object({kind:z89.literal("project_token"),projectId:z89.string(),projectName:z89.string(),displayName:z89.string().nullable(),organizationId:z89.string().nullable(),organizationName:z89.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z89.coerce.date().nullable(),tokenExpiresAt:z89.coerce.date().nullable()}))}});import{z as z90}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=z90.object({translated:z90.number().int().nonnegative(),total:z90.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z90.object({locale:z90.string(),isDefault:z90.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z90.object({defaultLocale:z90.string(),locales:z90.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z90.object({locale:z90.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z90.object({locale:z90.string().min(1).max(40)}),ProjectLocaleMutationSchema=z90.object({locale:z90.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z90.object({locale:z90.string(),entriesDeleted:z90.number().int().nonnegative(),labelsDeleted:z90.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z91}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=z91.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z91.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=z91.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z91.number(),credits:z91.number().optional(),billingMode:z91.enum(["fimo-credits","provider-account"]).optional(),confidence:z91.enum(["exact","estimated","metered"]),basis:z91.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z92}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=z92.object({options:z92.record(z92.string(),z92.unknown()),name:z92.string().optional(),parentId:z92.string().nullable().optional(),altText:z92.string().optional(),caption:z92.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z92.string().min(1).optional(),model:z92.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=z92.object({jobId:z92.string(),status:z92.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z92.string().nullable().optional(),credits:z92.number().optional(),costUsd:z92.number().optional(),billingMode:z92.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z92.object({error:z92.string(),code:z92.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:z92.array(GenerationTaskIdSchema).optional(),availableModels:z92.array(z92.string()).optional(),issues:z92.array(z92.unknown()).optional()})}});import{z as z93}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=z93.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z93.object({name:z93.string(),key:z93.string(),description:z93.string(),type:FlagTypeSchema,required:z93.boolean(),defaultValue:z93.unknown().optional(),enumValues:z93.array(z93.string()).optional(),isArray:z93.boolean()}),AssetModelPriceSchema=z93.object({unitPrice:z93.number(),unit:z93.string(),confidence:z93.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z93.object({id:z93.string(),shortName:z93.string(),provider:z93.string(),source:z93.string(),modality:z93.enum(["image","video","audio"]),tags:z93.array(z93.string()),displayName:z93.string(),description:z93.string(),flags:z93.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z93.object({model:z93.string(),costUsd:z93.number(),credits:z93.number(),billingMode:z93.enum(["fimo-credits","provider-account"]),confidence:z93.enum(["exact","estimated","metered"]),basis:z93.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z94}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=z94.object({tourId:z94.string(),version:z94.string(),status:z94.string(),completedAt:z94.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z94.array(UserTourDTOSchema))}});import{z as z95}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=z95.object({backendProfile:OpsBackendProfileSchema,provider:z95.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z95.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z95.object({backendProfile:OpsBackendProfileSchema,provider:z95.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z95.literal(!1),reason:z95.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z96}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=z96.object({packageManager:z96.string().trim().min(1).max(200).nullable(),trackedLockfiles:z96.array(z96.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z96.string().trim().min(1)}),OpsProjectPackageManagerSchema=z96.object({target:z96.object({backendProfile:OpsBackendProfileSchema,projectId:z96.uuid(),projectEnv:z96.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z97}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:z97.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z97.union([z97.object({name:z97.string().trim().min(1).max(120),description:z97.string().trim().min(1).max(2e3)}).strict(),z97.object({template:z97.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z97.object({agent:OpsAgentChatAgentSpecSchema,routines:z97.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:z97.string().trim().min(1).max(1e3),dryRun:z97.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z97.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z97.object({id:z97.string().uuid().nullable(),name:z97.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z97.string().nullable(),paused:z97.boolean(),outcome:z97.enum(["created","would_create"]),source:z97.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z97.object({target:z97.object({backendProfile:OpsBackendProfileSchema,projectId:z97.string().uuid()}),dryRun:z97.boolean(),applied:z97.boolean(),createdBy:z97.object({userId:z97.string()}),agent:z97.object({id:z97.string().uuid().nullable(),title:z97.string(),template:z97.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z97.array(OpsAgentChatRoutineResultSchema),skipped:z97.array(z97.object({name:z97.string(),reason:z97.literal("routine_exists")})),refused:z97.array(z97.object({name:z97.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z98}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=z98.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z98.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z98.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z98.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z98.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z98.object({reason:WebhookEntryChangeReasonSchema,operationId:z98.string().optional(),batch:z98.object({index:z98.number().int().positive(),total:z98.number().int().positive()}).optional(),changes:z98.array(z98.object({action:WebhookEntryChangeActionSchema,contentType:z98.string(),id:z98.string(),documentId:z98.string(),locale:z98.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z98.object({form:z98.object({id:z98.string(),label:z98.string()}),submission:z98.object({id:z98.string(),data:z98.record(z98.string(),z98.unknown()),submittedAt:z98.string()})}),PublishStartedWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("publishing"),startedAt:z98.string()})}),PublishSucceededWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("published"),url:z98.string(),publishedAt:z98.string(),firstPublish:z98.boolean()})}),PublishFailedWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("failed"),reason:z98.string()})}),PublishUnpublishedWebhookEventDataSchema=z98.object({publication:z98.object({previousUrl:z98.string(),unpublishedAt:z98.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z98.object({report:z98.object({weekStart:z98.string(),weekEnd:z98.string(),pageviews:z98.number(),visitors:z98.number(),previousPageviews:z98.number(),previousVisitors:z98.number()})}),MediaAssetWebhookEventDataSchema=z98.object({id:z98.string().nullable(),name:z98.string().nullable(),type:z98.string(),mimeType:z98.string().nullable(),fileSize:z98.number().nullable()}),MediaUploadedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("updated")}),MediaDeletedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z98.object({domain:z98.object({id:z98.string(),hostname:z98.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z98.object({domain:z98.object({id:z98.string(),hostname:z98.string()})}),LabelChangedWebhookEventDataSchema=z98.object({changes:z98.array(z98.object({action:z98.enum(["created","updated","deleted"]),key:z98.string(),locale:z98.string(),value:z98.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),isDefault:z98.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),previousCode:z98.string()})}),LocaleDeletedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),entriesDeleted:z98.number().int().nonnegative(),labelsDeleted:z98.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z98.object({environment:z98.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z98.object({environment:z98.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z98.object({merge:z98.object({id:z98.string(),from:BranchSchema,to:BranchSchema,applied:z98.array(z98.object({surface:SurfaceNameSchema,count:z98.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z98.object({branch:z98.object({name:BranchSchema}),version:z98.object({versionId:z98.uuid(),name:z98.string()})}),WebhookEventFamilySchema=z98.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z98.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z98.discriminatedUnion("source",[z98.object({source:z98.literal("literal"),value:z98.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z98.object({source:z98.literal("secret"),key:z98.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z98.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z98.object({name:z98.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z98.object({name:z98.string(),source:z98.enum(["literal","secret"]),secretKey:z98.string().nullable(),secretPrefix:z98.string().nullable(),configured:z98.literal(!0)}),WebhookFilterSchema=z98.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z98.string().min(1).max(255).optional(),mediaType:z98.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z98.string().min(1).max(255).optional(),locale:z98.string().min(1).max(120).optional()}),JsonValueSchema=z98.lazy(()=>z98.union([z98.string(),z98.number(),z98.boolean(),z98.null(),z98.array(JsonValueSchema),z98.record(z98.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z98.object({name:z98.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z98.url(),enabled:z98.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z98.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z98.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z98.object({name:z98.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z98.url().optional(),enabled:z98.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z98.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z98.boolean().optional()}),TestProjectWebhookRequestSchema=z98.object({eventType:WebhookEventTypeSchema.optional(),data:z98.record(z98.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z98.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z98.uuid(),name:z98.string(),eventType:WebhookEventTypeSchema,enabled:z98.boolean(),destination:z98.object({host:z98.string(),maskedUrl:z98.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z98.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z98.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z98.coerce.date().nullable(),deliveryStats24h:z98.object({succeeded:z98.number().int().nonnegative(),failed:z98.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z98.uuid(),projectId:z98.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z98.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z98.number().int().positive(),test:z98.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z98.number().int().nonnegative(),responseStatus:z98.number().int().nullable(),lastErrorCode:z98.string().nullable(),lastErrorMessage:z98.string().nullable(),payloadAvailable:z98.boolean(),destination:z98.object({host:z98.string(),maskedUrl:z98.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z98.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z98.string().nullable(),qstashMessageId:z98.string().nullable(),deliveredAt:z98.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z98.object({items:z98.array(WebhookDeliveryDTOSchema),pagination:z98.object({page:z98.number().int().positive(),limit:z98.number().int().positive(),total:z98.number().int().nonnegative(),totalPages:z98.number().int().positive(),hasMore:z98.boolean()}),stats:z98.object({total:z98.number().int().nonnegative(),succeeded:z98.number().int().nonnegative(),failed:z98.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z98.object({id:z98.uuid(),deliveryId:z98.uuid(),attempt:z98.number().int().positive(),status:z98.enum(["delivering","succeeded","failed"]),responseStatus:z98.number().int().nullable(),durationMs:z98.number().int().nonnegative(),responseExcerpt:z98.string().nullable(),errorCode:z98.string().nullable(),errorMessage:z98.string().nullable(),createdAt:z98.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z98.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z98.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z99}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=z99.object({key:z99.literal("fimo-2"),enabled:z99.boolean(),dismissed:z99.boolean().default(!1),interacted:z99.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z100}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,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=z100.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z100.enum(["running","done","failed"]),SiteCloneStatusSchema=z100.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z100.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z100.object({code:SiteRefusalCodeSchema,suggestedUrl:z100.string().nullable()}),SiteCheckGroupSchema=z100.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z100.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=z100.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z100.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z100.record(z100.string(),z100.union([z100.string(),z100.number(),z100.boolean(),z100.array(z100.string())])),SiteCheckResultSchema=z100.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z100.object({id:SiteCheckGroupSchema,score:z100.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z100.object({answers:z100.number().int().min(0),domains:z100.record(z100.string(),z100.number().int().min(0))}),SiteMarketSchema=z100.object({domain:z100.string(),competitors:z100.array(z100.string()),rankings:z100.array(z100.object({domain:z100.string(),averagePosition:z100.number().min(1).nullable()})),keywords:z100.array(z100.object({keyword:z100.string(),positions:z100.record(z100.string(),z100.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z100.record(z100.string(),z100.string()).optional(),fetchedAt:z100.coerce.date()}),SitePageViewSchema=z100.object({url:z100.string(),title:z100.string().nullable(),description:z100.string().nullable(),h1:z100.string().nullable(),structuredData:z100.array(z100.string()),wordCount:z100.number().int().min(0),capturedAt:z100.coerce.date()}),SiteSectionStatusSchema=z100.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z100.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z100.coerce.date().optional(),afterQueuedAt:z100.coerce.date().optional()}),SiteReportSchema=z100.object({siteUrl:z100.string(),scannedAt:z100.coerce.date(),seoScore:z100.number().int().min(0).max(100).nullable(),geoScore:z100.number().int().min(0).max(100).nullable(),groups:z100.array(SiteReportGroupSchema),checks:z100.array(SiteCheckResultSchema),blockers:z100.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z100.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z100.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z100.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z100.object({name:z100.string(),summary:z100.string(),audience:z100.string(),positioning:z100.string(),homepage:z100.string()}),SiteSuggestionSchema=z100.object({label:z100.string(),url:z100.string().nullable()}),SiteInterviewSuggestionsSchema=z100.record(z100.string(),z100.record(z100.string(),z100.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z100.record(z100.string().max(50),z100.union([z100.string().trim().max(2e3),z100.array(z100.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z100.object({status:z100.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z100.record(z100.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z100.object({questionId:z100.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z100.object({fixes:z100.array(z100.object({checkId:SiteCheckIdSchema,status:z100.enum(["fixed","not_fixed","not_applicable"]),note:z100.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z100.object({fixes:SiteFixesReportSchema.nullable(),summary:z100.string().nullable()}),StartSiteOnboardingRequestSchema=z100.object({organizationId:z100.string().min(1),url:z100.string().trim().min(1).max(2048),locale:z100.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z100.object({projectId:z100.string()})),SiteOnboardingRefusedResponseSchema=z100.object({error:z100.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z100.object({projectId:z100.string(),siteUrl:z100.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z100.boolean(),budgetExhausted:z100.boolean(),sponsored:z100.boolean(),outOfCredits:z100.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z100.string().nullable(),welcomeThreadId:z100.string().nullable(),competitors:z100.array(z100.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z100.coerce.date(),openedAt:z100.coerce.date().nullable(),bannerDismissed:z100.boolean(),completed:z100.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z100.object({task:z100.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z100.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z100.object({search:z100.string().trim().max(200).optional(),organizationId:z100.string().trim().min(1).max(200).optional(),startDate:z100.coerce.date().optional(),endDate:z100.coerce.date().optional(),outcomes:z100.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z100.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z100.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z100.array(SiteTypeSchema).optional()),page:z100.coerce.number().int().min(1).default(1),pageSize:z100.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z100.object({projectId:z100.string(),projectName:z100.string(),organizationId:z100.string(),organizationName:z100.string().nullable(),ownerEmail:z100.string().nullable(),ownerName:z100.string().nullable(),siteUrl:z100.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z100.boolean(),cloneRetries:z100.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z100.number(),interviewQuestions:z100.number().nullable(),seoScore:z100.number().nullable(),geoScore:z100.number().nullable(),spentUsd:z100.number(),budgetCapUsd:z100.number(),capReached:z100.boolean(),cloneSeconds:z100.number().nullable(),createdAt:z100.coerce.date(),openedAt:z100.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z100.object({onboardings:z100.array(AdminSiteOnboardingDTOSchema),page:z100.number(),limit:z100.number(),total:z100.number(),totalPages:z100.number()})),AdminSiteOnboardingStatsSchema=z100.object({total:z100.number(),outcomes:z100.record(SiteOnboardingOutcomeSchema,z100.number()),funnel:z100.object({started:z100.number(),confirmed:z100.number(),finished:z100.number(),opened:z100.number()}),bySiteType:z100.array(z100.object({siteType:SiteTypeSchema,total:z100.number(),finished:z100.number(),opened:z100.number()})),granularity:z100.enum(["hour","day"]),series:z100.array(z100.object({at:z100.coerce.date(),outcomes:z100.record(SiteOnboardingOutcomeSchema,z100.number())})),spentUsd:z100.object({total:z100.number(),average:z100.number().nullable()}),sponsored:z100.number(),paidByOrganization:z100.object({usd:z100.number(),credits:z100.number()}),capReached:z100.number(),cloneSeconds:z100.object({median:z100.number().nullable(),average:z100.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z100.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z100.string(),cloneThreadId:z100.string().nullable(),paidByOrganizationUsd:z100.number()}),interview:SiteInterviewSchema.extend({invocationIds:z100.array(z100.string())}).nullable(),knowledgeWritten:z100.string().nullable(),knowledgeNow:z100.object({content:z100.string(),updatedAt:z100.coerce.date().nullable(),updatedBy:z100.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z101}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=z101.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z101.object({total:z101.number(),base:z101.number(),purchases:z101.number(),awards:z101.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z101.object({id:z101.string(),name:z101.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z101.object({type:z101.string(),brand:z101.string().nullable(),last4:z101.string().nullable(),expirationDate:z101.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z101.object({currency:z101.string(),nextPaymentAmount:z101.number().nullable(),nextPaymentAt:z101.string().nullable(),billingInterval:z101.string().nullable(),totalAmount:z101.number().nullable(),discountAmount:z101.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z101.object({id:z101.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z101.string().nullable(),currentPeriodEndsAt:z101.string().nullable(),renewsAt:z101.string().nullable(),cancelAt:z101.string().nullable(),renewAutomatically:z101.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z101.object({type:z101.enum(["low_balance","critical_balance","approaching_limit"]),message:z101.string(),estimatedPromptsRemaining:z101.number().nullable(),avgCostPerPrompt:z101.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z101.object({monthlyCredits:z101.number().nullable(),usedThisPeriod:z101.number(),remainingThisPeriod:z101.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z101.object({organizationId:z101.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z101.string().nullable(),tenureDays:z101.number().int().nonnegative(),capturedAt:z101.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z101.object({hasSubscription:z101.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z101.number().nullable(),alerts:z101.array(CreditAlertDTOSchema),portalUrl:z101.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z101.object({creditCount:z101.number().int().positive(),expiresAt:z101.string().datetime().nullable().optional(),message:z101.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z101.literal("free"),amountCents:z101.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z101.literal("purchase"),amountCents:z101.number().int().positive()}),CreditTopupRequestDTOSchema=z101.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z101.object({success:z101.boolean(),transactionId:z101.string().nullable(),newBalance:z101.number(),creditCount:z101.number(),type:z101.enum(["free","purchase"]),invoiceId:z101.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z102}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=z102.object({totalCredits:z102.number(),totalCostUsd:z102.number(),totalMessages:z102.number(),avgCostPerMessage:z102.number(),periodStart:z102.string().nullable(),periodEnd:z102.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z102.object({projectId:z102.string(),projectName:z102.string(),projectDisplayName:z102.string().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z102.object({userId:z102.string(),userName:z102.string().nullable(),userEmail:z102.string().email().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z102.object({date:z102.string(),credits:z102.number(),costUsd:z102.number(),messages:z102.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z102.object({userId:z102.string(),userName:z102.string().nullable(),userEmail:z102.string().email().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z102.object({projectId:z102.string(),projectName:z102.string(),projectDisplayName:z102.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z102.array(UsageByUserForProjectDTOSchema),timeline:z102.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z102.object({summary:UsageSummaryDTOSchema,byProject:z102.array(UsageByProjectDTOSchema),byUser:z102.array(UsageByUserDTOSchema),timeline:z102.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z103}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=z103.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z103.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z103.object({startDate:z103.string().optional(),endDate:z103.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z103.coerce.number().int().positive().default(1),limit:z103.coerce.number().int().positive().max(100).default(20),sortBy:z103.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z103.string().optional(),activeOnly:z103.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z103.object({totalCredits:z103.number(),totalCostUsd:z103.number(),totalMessages:z103.number(),automatedMessages:z103.number(),avgCostPerMessage:z103.number(),avgCreditsPerMessage:z103.number(),periodStart:z103.string(),periodEnd:z103.string(),creditsChange:z103.number().nullable(),costChange:z103.number().nullable(),messagesChange:z103.number().nullable(),unattributedCredits:z103.number(),unattributedCostUsd:z103.number(),unattributedMessages:z103.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z103.object({date:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z103.object({organizationId:z103.string(),organizationName:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),userCount:z103.number(),projectCount:z103.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z103.object({userId:z103.string(),userName:z103.string().nullable(),userEmail:z103.string().nullable(),userImage:z103.string().nullable(),organizationId:z103.string().nullable(),organizationName:z103.string().nullable(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),projectCount:z103.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z103.object({projectId:z103.string(),projectName:z103.string(),projectDisplayName:z103.string().nullable(),organizationId:z103.string(),organizationName:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),userCount:z103.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z103.object({id:z103.string(),name:z103.string(),value:z103.number(),percentage:z103.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z103.object({day:z103.number(),hour:z103.number(),value:z103.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z103.object({summary:UsageOverviewSummaryDTOSchema,timeline:z103.array(UsageTimelinePointDTOSchema),topOrganizations:z103.array(OrganizationUsageRowDTOSchema),topUsers:z103.array(UserUsageRowDTOSchema),topProjects:z103.array(ProjectUsageRowDTOSchema),creditDistribution:z103.array(UsageDistributionItemDTOSchema),userDistribution:z103.array(UsageDistributionItemDTOSchema),heatmap:z103.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z103.object({page:z103.number(),limit:z103.number(),totalItems:z103.number(),totalPages:z103.number(),hasMore:z103.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z103.object({organizations:z103.array(OrganizationUsageRowDTOSchema),top:z103.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z103.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z103.object({users:z103.array(ExtendedUserUsageRowDTOSchema),top:z103.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z103.string(),ownerName:z103.string().nullable(),ownerEmail:z103.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z103.object({projects:z103.array(ExtendedProjectUsageRowDTOSchema),top:z103.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z103.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z103.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z103.object({credits:z103.number(),costUsd:z103.number(),messages:z103.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z103.object({id:z103.string(),name:z103.string(),createdAt:z103.string(),memberCount:z103.number(),projectCount:z103.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z103.object({id:z103.string(),name:z103.string().nullable(),email:z103.string(),image:z103.string().nullable(),createdAt:z103.string(),organizationCount:z103.number(),projectCount:z103.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z103.object({id:z103.string(),name:z103.string(),displayName:z103.string().nullable(),createdAt:z103.string(),organizationId:z103.string(),organizationName:z103.string(),ownerId:z103.string(),ownerName:z103.string().nullable(),ownerEmail:z103.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z104}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=z104.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z104.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z104.object({command:z104.string().min(1).max(1e4),cwd:z104.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z104.record(z104.string(),z104.string()).optional(),name:z104.string().optional(),waitForCompletion:z104.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=z104.object({identifier:z104.string(),status:SandboxProcessStatusSchema,command:z104.string().optional(),startedAt:z104.string().optional(),exitCode:z104.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z104.object({processes:z104.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z104.object({processId:z104.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z104.object({success:z104.boolean(),message:z104.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z105}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=z105.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z105.object({search:z105.string().trim().max(200).optional(),startDate:z105.coerce.date().optional(),endDate:z105.coerce.date().optional(),states:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(AdminUnclaimedStateSchema).optional()),cliVersions:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(z105.string().max(64)).optional()),page:z105.coerce.number().int().min(1).default(1),pageSize:z105.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z105.object({projectId:z105.string(),displayName:z105.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z105.string().nullable(),createdAt:z105.coerce.date(),expiresAt:z105.coerce.date(),claimedAt:z105.coerce.date().nullable(),claimedOrganizationId:z105.string().nullable(),claimedOrganizationName:z105.string().nullable(),claimedByEmail:z105.string().nullable(),projectExists:z105.boolean(),previewUrl:z105.string().nullable(),hostingCostUsd:z105.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z105.object({projects:z105.array(AdminUnclaimedProjectDTOSchema),page:z105.number(),limit:z105.number(),total:z105.number(),totalPages:z105.number()})),ClaimOutcomesSchema=z105.object({total:z105.number(),claimed:z105.number(),archived:z105.number(),claimRate:z105.number().nullable(),medianTimeToClaimSeconds:z105.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z105.record(AdminUnclaimedStateSchema,z105.number()),averageTimeToClaimSeconds:z105.number().nullable(),byCliVersion:z105.array(ClaimOutcomesSchema.extend({cliVersion:z105.string().nullable()})),granularity:z105.enum(["hour","day"]),series:z105.array(z105.object({at:z105.coerce.date(),states:z105.record(AdminUnclaimedStateSchema,z105.number()),alive:z105.number(),hostingCostUsd:z105.number()})),hostingCostUsd:z105.number(),costPerProjectUsd:z105.number().nullable(),leftovers:z105.object({overdue:z105.number(),claiming:z105.number(),archivedNotDeleted:z105.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z106}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z106.enum(["internal","user-visible"]),SessionSetRetentionSchema=z106.object({additionalDays:z106.number().int().min(1).max(30)}).strict()}});import{z as z107}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=z107.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=z107.object({content:ProjectKnowledgeContentSchema,updatedAt:z107.string().nullable(),updatedBy:z107.string().nullable()}),ProjectKnowledgeUpdateSchema=z107.object({content:ProjectKnowledgeContentSchema,expectedUpdatedAt:z107.iso.datetime().nullable().optional()}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z107.object({id:z107.uuid(),status:z107.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z107.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z107.object({idempotencyKey:z107.uuid()})}});import{z as z108}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_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_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_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_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=z41.enum(REPORT_TONES),blockCommon={title:z41.string().trim().min(1).max(120).optional(),fallback:z41.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z41.object({type:z41.literal("text"),...blockCommon,text:z41.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=z41.object({type:z41.literal("metric"),...blockCommon,items:z41.array(z41.object({value:z41.string().trim().min(1).max(24),unit:z41.string().trim().min(1).max(12).optional(),label:z41.string().trim().min(1).max(160),note:z41.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z41.array(z41.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=z41.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z41.object({type:z41.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z41.string().trim().min(1).max(12).optional(),points:z41.array(z41.object({label:z41.string().trim().min(1).max(24),value:z41.number().finite(),highlight:z41.boolean().optional()}).strict()).min(2).max(24),caption:z41.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=z41.object({type:z41.literal("list"),...blockCommon,items:z41.array(z41.object({tone:ReportToneSchema.optional(),label:z41.string().trim().min(1).max(24).optional(),heading:z41.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z41.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z41.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=z41.object({type:z41.literal("table"),...blockCommon,columns:z41.array(z41.object({label:z41.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z41.array(z41.object({cells:z41.array(z41.object({text:z41.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z41.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=z41.object({type:z41.literal("media"),...blockCommon,assetId:z41.uuid(),alt:z41.string().trim().min(1).max(300),caption:z41.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=z41.object({type:z41.literal("links"),...blockCommon,items:z41.array(z41.object({label:z41.string().trim().min(1).max(120),url:z41.url({protocol:/^https$/}).max(2e3),description:z41.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z41.object({type:z41.literal("code"),...blockCommon,language:z41.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z41.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z41.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z41.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z41.object({title:z41.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z41.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z41.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=z41.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=z41.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z41.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z42}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=z42.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z42.object({dev:z42.string().trim().min(1).optional(),build:z42.string().trim().min(1).optional(),install:z42.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z42.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z42.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z42.object({type:z42.enum(["header","cookie","query","host"]),key:z42.string().min(1).optional(),value:z42.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:z42.array(FimoHostingConditionSchema).min(1).optional(),missing:z42.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z42.object({source:z42.string().min(1),destination:z42.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z42.object({source:z42.string().min(1),destination:z42.string().min(1),permanent:z42.boolean().optional(),statusCode:z42.union([z42.literal(301),z42.literal(302),z42.literal(307),z42.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z42.object({source:z42.string().min(1),headers:z42.array(z42.object({key:z42.string().min(1),value:z42.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z42.object({rewrites:z42.array(FimoHostingRewriteSchema).optional(),redirects:z42.array(FimoHostingRedirectSchema).optional(),headers:z42.array(FimoHostingHeaderSchema).optional(),cleanUrls:z42.boolean().optional(),trailingSlash:z42.boolean().optional()}).strict(),FimoAppConfigSchema=z42.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 z43}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=z43.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z43.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z43.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z43.string().nullable(),deletedAt:z43.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z43.object({id:z43.union([z43.literal(PREVIEW_ENVIRONMENT_KEY),z43.uuid()]),name:z43.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z43.object({sessionId:z43.uuid(),name:z43.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z43.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=z43.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z43.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z43.object({surface:z43.enum(["code","schemas","content","translations","assets","forms"]),status:z43.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z43.number().int().nonnegative(),conflictCount:z43.number().int().nonnegative()}),BranchDiffResultSchema=z43.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z43.coerce.date(),surfaces:z43.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z44}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=z44.object({projectId:z44.uuid(),name:z44.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z44.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z44.literal("production"),sourceBranch:BranchSchema,isPublished:z44.boolean(),url:z44.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z44.literal(PREVIEW_ENVIRONMENT_KEY),kind:z44.literal("preview"),matchedBranchCount:z44.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z44.literal("custom"),matchedBranchCount:z44.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z44.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z44.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z44.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z44.object({deletedId:z44.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z45}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=z45.object({kind:z45.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z45.object({kind:z45.enum(["variable","secret"]),value:z45.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z45.string().min(1).max(255),exposure:z45.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z45.object({kind:z45.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z45.object({id:z45.uuid(),projectId:z45.uuid(),key:z45.string(),kind:z45.literal("secret"),exposure:z45.literal("private"),environment:EnvironmentKeySchema,maskedValue:z45.string().optional(),createdAt:z45.date().transform(value=>value.toISOString()),updatedAt:z45.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z45.object({id:z45.uuid(),projectId:z45.uuid(),key:z45.string(),kind:z45.literal("variable"),environment:EnvironmentKeySchema,managed:z45.boolean(),createdAt:z45.date().transform(value=>value.toISOString()),updatedAt:z45.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z45.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z45.literal("public"),value:z45.string()}),ProjectVariableBaseSchema.extend({exposure:z45.literal("private"),maskedValue:z45.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z45.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z46}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=z46.object({success:z46.literal(!0),downloadUrl:z46.string(),expiresAt:z46.string(),fileSize:z46.number(),duration:z46.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z46.object({success:z46.literal(!0),projectId:z46.string(),projectName:z46.string(),displayName:z46.string(),projectUrl:z46.string(),duration:z46.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z46.object({contentTypes:z46.number(),entries:z46.number(),assets:z46.number(),translations:z46.number(),forms:z46.number(),codeFiles:z46.number(),assetFiles:z46.number()}),ImportPreviewSurfaceDTOSchema=z46.object({name:z46.string(),included:z46.boolean(),count:z46.number().optional(),note:z46.string().optional()}),ImportPreviewDTOSchema=z46.object({projectName:z46.string(),displayName:z46.string().nullable(),category:z46.string().nullable(),exportedAt:z46.string(),version:z46.string(),envScope:z46.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z46.array(ImportPreviewSurfaceDTOSchema),fileSize:z46.number(),fileName:z46.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z46.object({success:z46.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z47}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=z47.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z47.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z47.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z47.object({verb:SurfaceDeltaVerbSchema,key:z47.string(),detail:z47.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z47.record(z47.string(),z47.unknown()).optional()}),PerSurfaceDeltaSchema=z47.object({surface:SurfaceNameSchema,status:z47.enum(["ok","timed_out","failed","unchanged"]),durationMs:z47.number().int().nonnegative().optional(),changedCount:z47.number().int().nonnegative(),conflictCount:z47.number().int().nonnegative(),items:z47.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z47.boolean().optional(),error:z47.string().optional()}),CrossSurfaceFindingSchema=z47.object({id:z47.string(),kind:z47.string(),description:z47.string(),severity:z47.enum(["warning","error"]),source:z47.object({surface:SurfaceNameSchema,key:z47.string()}),target:z47.object({surface:SurfaceNameSchema,key:z47.string()}),actions:z47.array(z47.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z47.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z47.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z47.coerce.date(),surfaces:z47.array(PerSurfaceDeltaSchema),agents:z47.array(z47.object({id:z47.string(),name:z47.string(),status:z47.enum(["active","paused","failed"]),lastRunAt:z47.coerce.date().nullable()})).optional(),crossSurface:z47.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z47.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z47.coerce.date(),surfaces:z47.array(PerSurfaceDeltaSchema),crossSurface:z47.array(CrossSurfaceFindingSchema).optional(),fingerprint:z47.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z47.object({path:z47.string(),state:z47.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z47.string(),additions:z47.number().int().nonnegative(),deletions:z47.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z47.object({oid:z47.string().optional(),content:z47.string().optional(),truncated:z47.boolean(),binary:z47.boolean()}),CodeConflictDetailSchema=z47.object({path:z47.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z47.string(),targetTipSha:z47.string(),mergeBaseSha:z47.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z47.object({id:z47.string(),slug:z47.string(),contentType:z47.string(),data:z47.record(z47.string(),z47.unknown()),updatedAt:z47.coerce.date()}),ContentRowDiffSchema=z47.object({collection:z47.string(),rowId:z47.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z47.object({name:z47.string(),label:z47.string(),isSingleton:z47.boolean(),description:z47.string().nullable().default(null),fields:z47.record(z47.string(),z47.unknown())}),SchemaTypeDiffSchema=z47.object({typeName:z47.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z47.object({id:z47.string(),name:z47.string(),type:z47.enum(["file","folder"]),mimeType:z47.string().nullable(),storageKey:z47.string().nullable(),url:z47.string().nullable(),fileSize:z47.number().nullable(),width:z47.number().nullable(),height:z47.number().nullable(),altText:z47.string().nullable(),caption:z47.string().nullable(),createdAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),AssetDiffSchema=z47.object({assetId:z47.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z47.object({locale:z47.string(),key:z47.string(),parent:z47.string().nullable(),child:z47.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z47.object({formName:z47.string(),label:z47.string().nullable(),schemaFingerprint:z47.string(),fields:z47.record(z47.string(),z47.unknown()),settings:z47.record(z47.string(),z47.unknown()).optional()}),FormSchemaDiffSchema=z47.object({formName:z47.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=z47.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z47.object({sha:z47.string(),subject:z47.string(),body:z47.string().optional(),author:z47.string(),date:z47.string()}),ConflictSchema=z47.object({surface:SurfaceNameSchema,key:z47.string(),kind:ConflictKindSchema.optional(),description:z47.string(),parentValue:z47.unknown().optional(),childValue:z47.unknown().optional(),conflictingFields:z47.array(z47.string()).optional(),code:z47.object({path:z47.string(),unresolvable:z47.boolean().optional(),reason:z47.string().optional(),targetCommits:z47.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z47.object({field:z47.string(),choice:z47.enum(["parent","child","pick","ai-pick"]),pickedValue:z47.unknown().optional(),aiSessionId:z47.string().optional()}),ConflictResolutionSchema=z47.object({surface:SurfaceNameSchema,key:z47.string(),choice:z47.enum(["parent","child","pick"]),pickedValue:z47.unknown().optional(),fieldPicks:z47.array(FieldPickSchema).optional()}),MergeResultSchema=z47.object({ok:z47.boolean(),mergeId:z47.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z47.array(z47.object({surface:SurfaceNameSchema,count:z47.number().int().nonnegative()})),conflicts:z47.array(ConflictSchema).optional(),summary:z47.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z47.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z47.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z47.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z47.boolean().optional()}),ResolvedStrategySchema=z47.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z47.boolean()}),MergeRequestSchema=z47.object({from:BranchSchema,allowDirectMerge:z47.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z47.object({mergeId:z47.string().uuid(),streamUrl:z47.string(),strategy:ResolvedStrategySchema,acceptedAt:z47.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z47.object({mergeId:z47.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z47.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z47.array(ConflictSchema),draftResolutions:z47.array(ConflictResolutionSchema),lastEditedBy:z47.string().nullable(),lastEditedAt:z47.coerce.date().nullable(),initiator:z47.object({userId:z47.string().nullable(),role:z47.string().nullable(),agentName:z47.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z47.object({resolutions:z47.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z47.object({mergeId:z47.string().uuid(),draftResolutions:z47.array(ConflictResolutionSchema),lastEditedAt:z47.coerce.date(),lastEditedBy:z47.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z47.object({mergeId:z47.string().uuid(),resolutions:z47.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z47.object({mergeId:z47.string().uuid()}),PublishReleaseRequestSchema=z47.object({version:z47.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z47.string().max(2e4).optional()}),PublishReleaseResultSchema=z47.object({releaseTag:z47.string(),sha:z47.string(),publishedAt:z47.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z48}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=z48.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z48.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z48.object({capturedAt:z48.coerce.date(),fingerprint:z48.string().min(1).max(256),counts:z48.object({code:z48.number().int().nonnegative(),content:z48.number().int().nonnegative(),schemas:z48.number().int().nonnegative(),labels:z48.number().int().nonnegative(),assets:z48.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z48.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z48.object({diff:DiffReportSchema,code:z48.array(CodeFileDiffSchema.extend({raw:z48.string().max(24576)})).max(200),schemas:z48.array(SchemaTypeDiffSchema).max(200),content:z48.array(z48.object({key:z48.string().min(1).max(512),collection:z48.string().min(1).max(256),slug:z48.string().max(512).optional(),verb:z48.enum(["added","modified","deleted"]),fields:z48.array(z48.object({name:z48.string().min(1).max(256),before:z48.unknown().optional(),after:z48.unknown().optional()})).max(20)})).max(200),labels:z48.array(z48.object({key:z48.string().min(1).max(512),locale:z48.string().min(1).max(64).optional(),before:z48.unknown().nullable(),after:z48.unknown().nullable()})).max(200),assets:z48.array(z48.object({key:z48.string().min(1).max(512),name:z48.string().min(1).max(512),verb:z48.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z48.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z49}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=z49.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z49.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z49.object({sessionId:z49.uuid(),branch:z49.string().min(1),targetBranch:z49.string().min(1),revision:z49.string().min(1),fingerprint:z49.string().min(1),source:z49.enum(["studio","slack","mcp"]),threadId:z49.uuid().nullable(),invocationId:z49.uuid().nullable(),conversationBranch:z49.string().nullable(),capturedAt:z49.string(),surfaces:z49.array(PerSurfaceDeltaSchema).optional(),counts:z49.record(z49.string(),z49.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z49.strictObject({sessionId:z49.uuid(),summary:z49.string().trim().min(1).max(240),targetBranch:z49.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z49.object({requested:z49.literal(!0),alreadyRequested:z49.boolean(),reviewId:z49.uuid(),reviewUrl:z49.url(),status:z49.literal("pending"),sessionId:z49.uuid(),branch:z49.string(),targetBranch:z49.string(),revision:z49.string(),savedRevision:z49.string(),fingerprint:z49.string(),visibility:z49.literal("user-visible"),retention:z49.literal("durable"),expiresAt:z49.null(),merged:z49.literal(!1),published:z49.literal(!1),links:z49.object({preview:z49.url(),changes:z49.url(),conversation:z49.url().nullable()})}),ProposalTextSchema={title:z49.string().trim().min(1).max(80),summary:z49.string().trim().min(1).max(1e3),note:z49.string().trim().min(1).max(2e3).optional()},ProposalEntryInputSchema=z49.strictObject({collection:z49.string().trim().min(1).max(80),id:z49.string().trim().min(1).max(120).optional(),locale:z49.string().trim().min(1).max(20).optional(),fields:z49.record(z49.string(),z49.unknown())}),ProposalShowItemSchema=z49.union([z49.strictObject({page:z49.string().trim().startsWith("/").max(500),note:z49.string().trim().min(1).max(300)}),z49.strictObject({entry:z49.strictObject({collection:z49.string().trim().min(1).max(80),id:z49.string().trim().min(1).max(120)}),note:z49.string().trim().min(1).max(300)})]),ContentProposalInputSchema=z49.strictObject({...ProposalTextSchema,revise:z49.uuid().optional(),entries:z49.array(ProposalEntryInputSchema).min(1).max(20)}),SessionProposalInputSchema=z49.strictObject({...ProposalTextSchema,sessionId:z49.uuid(),show:z49.array(ProposalShowItemSchema).min(1).max(10)}),ProposeInputSchema=z49.strictObject({target:z49.string().trim().min(1).optional(),proposals:z49.array(z49.union([ContentProposalInputSchema,SessionProposalInputSchema])).min(1).max(20)}),StoredProposalEntrySchema=z49.object({collection:z49.string(),documentId:z49.string(),locale:z49.string(),action:z49.enum(["create","update"]),fields:z49.record(z49.string(),z49.unknown()),base:z49.record(z49.string(),z49.unknown()).optional()}),ProposalMetaSchema=z49.object({form:z49.enum(["content","session"]),title:z49.string(),note:z49.string().optional(),target:z49.string(),threadId:z49.uuid().nullable(),invocationId:z49.uuid().nullable(),show:z49.array(ProposalShowItemSchema).optional(),editedAt:z49.string().optional()}),ProposalListInputSchema=z49.strictObject({state:z49.enum(["open","decided","all"]).default("open"),scope:z49.enum(["chat","project"]).default("chat"),limit:z49.number().int().min(1).max(50).default(20),cursor:z49.string().max(200).optional()}),ProposalDecideInputSchema=z49.strictObject({id:z49.uuid(),decision:z49.enum(["accept","discard"]),target:z49.string().trim().min(1).optional()}),AgentBranchProposalDTOSchema=z49.object({id:z49.uuid(),envId:z49.uuid(),sessionId:z49.uuid().nullable(),skillName:z49.string().min(1),classification:AgentBranchClassificationSchema,rationale:z49.string().nullable(),summary:z49.string().nullable(),surfaceDeltas:z49.record(z49.string(),z49.unknown()),review:WorkSessionReviewSchema.optional(),proposal:ProposalMetaSchema.optional(),entries:z49.array(StoredProposalEntrySchema).optional(),createdAt:z49.coerce.date(),decidedAt:z49.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z49.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z49.object({path:z49.enum(["review-merged","review-discarded"]),acceptCurrent:z49.boolean().optional(),target:z49.string().trim().min(1).optional()}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z49.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z49.object({code:z49.literal("merge_conflict"),message:z49.string(),conflicts:z49.record(z49.string(),z49.number().int().nonnegative())}),ProposedSessionSchema=z49.object({proposalId:z49.uuid(),title:z49.string(),form:z49.literal("session"),sessionId:z49.uuid(),reviewUrl:z49.url(),links:WorkSessionReviewResultSchema.shape.links})}});import{z as z50}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=z50.object({projectId:z50.uuid(),reviewId:z50.uuid(),entryId:z50.string().min(1).max(120),contentTypeName:z50.string().min(1).max(120),field:z50.string().min(1).max(120),quote:z50.string().min(1).max(2e4).optional(),locale:z50.string().min(1).max(35).optional(),message:z50.string().trim().min(1).max(4e3),providerMessageId:z50.string().min(1).max(200)}),RewriteDraftWordsRequestSchema=AskDraftChangeRequestSchema.extend({format:z50.enum(["rich","plain"]),words:z50.string().min(1).max(4e4),surroundingText:z50.string().max(2e4).optional()}),DraftChangeStateQuerySchema=z50.object({projectId:z50.uuid(),reviewId:z50.uuid()}),DraftChangeStateSchema=z50.object({busy:z50.boolean(),reply:z50.string().nullable()}),ApproveProposalRequestSchema=z50.object({projectId:z50.uuid(),proposalId:z50.uuid(),providerMessageId:z50.string().min(1).max(200),message:z50.string().trim().min(1).max(200),threadId:z50.uuid().optional()}),ProposalApprovalStateQuerySchema=z50.object({projectId:z50.uuid(),proposalId:z50.uuid(),threadId:z50.uuid().optional()})}});import{z as z51}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=z51.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z51.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=z51.object({description:z51.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z51.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z51.array(z51.uuid()).optional()}),AgentQuestionSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),threadId:z51.uuid(),invocationId:z51.uuid(),agentKey:z51.string().min(1).max(120),anchorEnv:z51.string().min(1).max(64),retainedEnv:z51.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z51.string().min(1).nullable(),continuationInvocationId:z51.uuid().nullable(),askedAt:z51.coerce.date(),expiresAt:z51.coerce.date(),closedAt:z51.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z51.object({questionId:z51.uuid(),invocationId:z51.uuid(),askedAt:z51.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z51.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z51.object({question:AgentQuestionSchema,continuationInvocationId:z51.uuid(),deduped:z51.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z52}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=z52.object({projectId:z52.uuid(),agentId:z52.uuid(),recipientEmail:z52.email().max(320)}).strict(),AgentQuestionFollowUpSchema=z52.object({projectId:z52.uuid(),agentId:z52.uuid(),eligible:z52.boolean(),reason:z52.enum(["ready","no_pending_questions","incomplete_coverage","unavailable"]),agentPendingQuestions:z52.number().int().nonnegative().nullable(),projectPendingQuestions:z52.number().int().nonnegative().nullable(),agentLegacyPendingForms:z52.number().int().nonnegative().nullable(),projectLegacyPendingForms:z52.number().int().nonnegative().nullable(),agentPendingCoverage:z52.enum(["complete","partial","unknown"]),projectPendingCoverage:z52.enum(["complete","partial","unknown"]),snapshotAt:z52.iso.datetime().nullable()}),AgentQuestionFollowUpDTO=createDTO(AgentQuestionFollowUpSchema)}});import{z as z53}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=z53.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z53.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z53.enum(["secret_text"]),IntegrationCredentialUsageSchema=z53.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z53.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z53.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z53.object({mode:IntegrationAuthModeSchema,label:z53.string().min(1),description:z53.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z53.object({id:z53.string().min(1),label:z53.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z53.boolean()}),IntegrationToolDefinitionDTOSchema=z53.object({key:z53.string().min(1),name:z53.string().min(1),description:z53.string().min(1),effect:IntegrationToolEffectSchema,input:z53.record(z53.string(),z53.unknown()).optional()}),IntegrationRecipeDTOSchema=z53.object({title:z53.string().min(1),description:z53.string().min(1),command:z53.string().min(1).optional()}),IntegrationInfoDTOSchema=z53.object({key:z53.string().min(1),name:z53.string().min(1),summary:z53.string().min(1),type:z53.enum(["native","mcp"]).optional(),url:z53.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z53.array(IntegrationAuthModeDTOSchema),credentials:z53.array(IntegrationCredentialDefinitionDTOSchema),tools:z53.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z53.enum(["available","unavailable"]).optional(),connectionCapabilities:z53.object({customIdentityCreation:z53.boolean()}).optional(),recipes:z53.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z53.object({projectId:z53.uuid(),integrationKey:z53.string().min(1),name:z53.string().min(1),summary:z53.string().min(1),installed:z53.boolean(),enabled:z53.boolean(),setupState:z53.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z53.string().nullable(),connectionId:z53.uuid().nullable().optional(),connectionAlias:z53.string().min(1).nullable().optional(),connectionStatus:z53.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z53.array(z53.string()),installedAt:z53.coerce.date().nullable(),updatedAt:z53.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),integrationKey:z53.string().min(1),enabled:z53.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z53.string(),connectionId:z53.uuid().nullable().optional(),connectionAlias:z53.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z53.array(z53.string()),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z53.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z53.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z53.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z53.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z53.object({id:z53.uuid(),organizationId:z53.string().min(1),integrationKey:z53.string().min(1),registrationId:z53.uuid().nullable(),alias:z53.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z53.string().min(1),externalAccountName:z53.string().nullable(),externalBotUserId:z53.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z53.array(z53.string()),connectedAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z53.boolean(),isDefault:z53.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z53.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z53.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z53.record(McpHeaderNameSchema,z53.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z53.object({alias:z53.string().min(1).max(120).optional(),token:z53.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z53.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=z53.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z53.object({displayName:z53.string().trim().min(1).max(35),backgroundColor:z53.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z53.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z53.discriminatedUnion("mode",[z53.object({mode:z53.literal("personal"),alias:z53.string().min(1).max(120),token:z53.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z53.boolean().optional()}),z53.object({mode:z53.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z53.boolean().optional(),registrationId:z53.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=z53.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z53.union([z53.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z53.object({type:z53.literal("mcp"),name:z53.string().trim().min(1).max(120),url:z53.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z53.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z53.string().min(1).optional(),integrationId:z53.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=z53.object({integrationKey:z53.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z53.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z53.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z53.literal("oauth"),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()})]),ReusableMcpServerAuthKindSchema=z53.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z53.object({id:z53.uuid(),name:z53.string().min(1),host:z53.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z53.string().min(1),availability:z53.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z53.object({query:z53.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z53.object({serverId:z53.uuid()}),LinearOAuthApplicationDistributionSchema=z53.enum(["private","public"]),OrganizationLinearAppDTOSchema=z53.object({id:z53.uuid(),displayName:z53.string().min(1),description:z53.string().nullable(),iconUrl:z53.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z53.enum(["active","revoked","disconnected"]),connectionIds:z53.array(z53.uuid()),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z53.object({appName:z53.string().trim().min(2).max(80),description:z53.string().trim().max(1e3).optional(),iconUrl:z53.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z53.object({projectId:z53.uuid(),registrationId:z53.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z53.object({integrationKey:z53.string().min(1),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z53.discriminatedUnion("mode",[z53.object({mode:z53.literal("personal"),integrationKey:z53.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z53.object({mode:z53.literal("oauth"),integrationKey:z53.string().min(1),connectUrl:z53.string().url(),expiresAt:z53.coerce.date()})]),BindProjectChannelRequestSchema=z53.object({ref:z53.string().min(1),connectionAlias:z53.string().min(1).optional(),agentName:z53.string().min(1).max(160).nullable().optional(),force:z53.boolean().optional()}),ListProjectChannelsQuerySchema=z53.object({integrationKey:z53.string().min(1)}),SearchProjectChannelsQuerySchema=z53.object({integrationKey:z53.string().min(1),connectionAlias:z53.string().min(1),query:z53.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z53.object({id:z53.uuid(),projectId:z53.uuid(),integrationKey:z53.string().min(1),connectionId:z53.uuid(),externalWorkspaceId:z53.string().min(1),externalChannelId:z53.string().min(1),externalChannelName:z53.string().nullable(),agentName:z53.string().nullable(),enabled:z53.boolean(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z53.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z53.object({id:z53.string().min(1),name:z53.string().min(1),visibility:z53.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z53.string().min(1).nullable(),canMove:z53.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z53.object({markdown:z53.boolean().optional(),summary:z53.boolean().optional(),links:z53.boolean().optional(),branding:z53.boolean().optional(),images:z53.boolean().optional(),html:z53.union([z53.literal("cleaned"),z53.literal("raw"),z53.boolean()]).optional(),json:z53.union([z53.boolean(),z53.object({prompt:z53.string().min(1).max(1e4),schema:z53.record(z53.string(),z53.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z53.object({url:z53.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional(),waitForMs:z53.number().int().min(0).max(3e4).optional(),maxAgeMs:z53.number().int().min(0).optional(),minAgeMs:z53.number().int().min(0).optional(),storeInCache:z53.boolean().optional(),proxy:z53.enum(["basic","enhanced","auto"]).optional(),mobile:z53.boolean().optional(),location:z53.object({country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z53.array(z53.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z53.object({query:z53.string().min(1),maxResults:z53.number().int().positive().max(20).optional(),sources:z53.array(z53.enum(["web","news","images"])).min(1).max(3).optional(),categories:z53.array(z53.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z53.enum(["hour","day","week","month","year"]).optional(),location:z53.string().min(1).max(160).optional(),country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z53.object({query:z53.string().min(1).max(500),maxResults:z53.number().int().min(1).max(100).optional(),types:z53.array(z53.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z53.array(z53.string().min(1).max(512)).min(1).max(20).optional(),sources:z53.array(z53.string().min(1).max(512)).min(1).max(20).optional(),passages:z53.number().int().min(1).max(5).optional(),skills:z53.literal("only").optional(),language:z53.string().min(1).optional(),topic:z53.string().min(1).optional(),license:z53.string().min(1).optional(),minStars:z53.number().int().min(0).optional(),maxStars:z53.number().int().min(0).optional(),archived:z53.boolean().optional(),fork:z53.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z53.object({query:z53.string().min(1).max(500),maxResults:z53.number().int().min(1).max(500).optional(),authors:z53.array(z53.string().min(1)).min(1).optional(),categories:z53.array(z53.string().min(1)).min(1).optional(),from:z53.iso.date().optional(),to:z53.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z53.object({paperId:z53.string().min(1).max(512),query:z53.string().min(1).max(500).optional(),maxPassages:z53.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z53.object({paperId:z53.string().min(1).max(512),intent:z53.string().min(1).max(500),mode:z53.enum(["similar","citers","references"]).optional(),maxResults:z53.number().int().min(1).max(500).optional(),rerank:z53.boolean().optional(),anchors:z53.array(z53.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z53.object({url:z53.string().url(),search:z53.string().min(1).optional(),limit:z53.number().int().positive().max(200).optional(),includeSubdomains:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z53.object({url:z53.string().url(),limit:z53.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z53.object({text:z53.string().min(1).max(200).optional(),cron:z53.string().min(1).max(120).optional(),timezone:z53.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z53.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z53.boolean().optional(),timeoutMs:z53.number().int().positive().max(12e4).optional(),waitForMs:z53.number().int().min(0).max(3e4).optional(),maxAgeMs:z53.number().int().min(0).optional(),minAgeMs:z53.number().int().min(0).optional(),storeInCache:z53.boolean().optional(),proxy:z53.enum(["basic","enhanced","auto"]).optional(),mobile:z53.boolean().optional(),location:z53.object({country:z53.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z53.array(z53.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z53.union([z53.object({type:z53.enum(["scrape","crawl"]).default("scrape"),urls:z53.array(z53.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z53.object({type:z53.literal("search"),queries:z53.array(z53.string().min(1).max(256)).min(1).max(12),searchWindow:z53.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z53.number().int().min(1).max(50).optional(),includeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z53.array(z53.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z53.object({name:z53.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z53.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z53.string().min(1).max(2e3).optional(),judgeEnabled:z53.boolean().optional(),retentionDays:z53.number().int().min(1).max(365).optional(),notification:z53.object({email:z53.object({enabled:z53.boolean().default(!0),recipients:z53.array(z53.string().email()).min(1).max(20),includeDiffs:z53.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=z53.object({monitorId:z53.string().uuid(),name:z53.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z53.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z53.string().min(1).max(2e3).optional(),judgeEnabled:z53.boolean().optional(),retentionDays:z53.number().int().min(1).max(365).optional(),status:z53.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z53.object({monitorId:z53.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z53.string().uuid()}),RunProjectIntegrationToolRequestSchema=z53.object({tool:z53.string().min(1),input:z53.record(z53.string(),z53.unknown()),connectionAlias:z53.string().min(1).optional(),approval:z53.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z53.object({provider:z53.string().min(1),providerCredits:z53.number().nonnegative().optional(),providerCostUsd:z53.number().nonnegative().optional(),requests:z53.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z53.object({credits:z53.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),title:z53.string().optional(),statusCode:z53.number().optional(),markdown:z53.string().optional(),summary:z53.string().optional(),links:z53.array(z53.string()).optional(),images:z53.array(z53.string()).optional(),html:z53.string().optional(),json:z53.unknown().optional(),branding:z53.record(z53.string(),z53.unknown()).optional(),warning:z53.string().optional()}),FirecrawlSearchToolOutputSchema=z53.object({query:z53.string(),provider:z53.literal("firecrawl"),warning:z53.string().optional(),results:z53.array(z53.object({title:z53.string(),url:z53.string(),snippet:z53.string().optional(),content:z53.string().optional(),score:z53.number().optional(),publishedAt:z53.string().optional()}))}),FirecrawlResearchPaperSchema=z53.object({paperId:z53.string(),primaryId:z53.string().optional(),ids:z53.record(z53.string(),z53.array(z53.string())).optional(),title:z53.string().optional(),abstract:z53.string().optional(),score:z53.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z53.object({text:z53.string(),score:z53.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(z53.object({id:z53.string(),type:z53.string().min(1).optional(),url:z53.string(),title:z53.string().optional(),passages:z53.array(z53.object({text:z53.string()}).passthrough())}).passthrough()),coverage:z53.record(z53.string(),z53.string()).optional(),reranked:z53.boolean().optional(),repos:z53.array(z53.record(z53.string(),z53.unknown())).optional(),sources:z53.array(z53.record(z53.string(),z53.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),paper:z53.record(z53.string(),z53.unknown()),paperId:z53.string().optional(),query:z53.string().optional(),passages:z53.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),results:z53.array(FirecrawlResearchPaperSchema),poolSize:z53.number().int().nonnegative(),truncated:z53.boolean(),note:z53.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),count:z53.number(),links:z53.array(z53.object({url:z53.string(),title:z53.string().optional(),description:z53.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z53.object({url:z53.string(),provider:z53.literal("firecrawl"),total:z53.number(),pages:z53.array(z53.object({url:z53.string(),title:z53.string().optional(),statusCode:z53.number().optional(),markdown:z53.string().optional(),summary:z53.string().optional(),links:z53.array(z53.string()).optional(),images:z53.array(z53.string()).optional(),html:z53.string().optional(),warning:z53.string().optional()})),warning:z53.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z53.object({cron:z53.string().optional(),text:z53.string().optional(),timezone:z53.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z53.object({id:z53.string().optional(),type:z53.enum(["scrape","crawl","search"]).optional(),urls:z53.array(z53.string()).optional(),queries:z53.array(z53.string()).optional(),searchWindow:z53.string().optional(),maxResults:z53.number().optional(),includeDomains:z53.array(z53.string()).optional(),excludeDomains:z53.array(z53.string()).optional(),scrapeOptions:z53.record(z53.string(),z53.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z53.object({id:z53.string(),name:z53.string(),status:z53.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z53.string().nullable().optional(),lastRunAt:z53.string().nullable().optional(),currentCheckId:z53.string().nullable().optional(),targets:z53.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z53.string().nullable().optional(),judgeEnabled:z53.boolean().optional(),estimatedCreditsPerMonth:z53.number().optional(),createdAt:z53.string().optional(),updatedAt:z53.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z53.object({id:z53.string(),monitorId:z53.string(),scheduledFor:z53.string().nullable().optional(),startedAt:z53.string().nullable().optional(),finishedAt:z53.string().nullable().optional(),estimatedCredits:z53.number().nullable().optional(),reservedCredits:z53.number().nullable().optional(),actualCredits:z53.number().nullable().optional(),billingStatus:z53.string().nullable().optional(),summary:z53.object({totalPages:z53.number().optional(),same:z53.number().optional(),changed:z53.number().optional(),new:z53.number().optional(),removed:z53.number().optional(),error:z53.number().optional()}).passthrough().optional(),error:z53.string().nullable().optional(),createdAt:z53.string().optional(),updatedAt:z53.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitors:z53.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),deleted:z53.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),checks:z53.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z53.object({provider:z53.literal("firecrawl"),monitorId:z53.string(),check:FirecrawlMonitorCheckOutputSchema,next:z53.string().optional()}),FirecrawlToolKeySchema=z53.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=z53.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z53.object({projectId:z53.uuid(),integrationKey:z53.string().min(1),tool:z53.string().min(1),connectionAlias:z53.string().min(1).nullable().optional(),output:z53.record(z53.string(),z53.unknown()),executedAt:z53.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z53.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z53.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z53.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z53.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z53.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z53.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z53.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z53.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z53.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z53.array(ProjectChannelCandidateDTOSchema))}});import{z as z54}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=z54.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z54.strictObject({scope:z54.string().min(1),reason:z54.string().min(1).max(200)}),IntegrationOAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("oauth"),actor:z54.literal("user").default("user"),authorizationUrl:z54.url(),tokenUrl:z54.url(),revocationUrl:z54.url().optional(),userInfoUrl:z54.url().optional(),client:z54.strictObject({idEnv:z54.string().min(1),secretEnv:z54.string().min(1)}),authorizeParams:z54.record(z54.string(),z54.string()).default({}),scopes:z54.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("apiKey"),keyLabel:z54.string().min(1).max(80),placeholder:z54.string().min(1).max(40).optional(),helpUrl:z54.url()}),IntegrationProviderAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("provider")}),IntegrationMcpAuthSchema=z54.strictObject({id:z54.string().min(1).max(40),label:z54.string().min(1).max(80),kind:z54.literal("mcp"),methods:z54.array(McpIntegrationSetupAuthSchema).min(1),scopes:z54.array(z54.string().min(1)).min(1).optional(),header:z54.object({name:z54.string().min(1).max(80),valuePrefix:z54.string().max(80)}).optional()}),IntegrationAuthSchema=z54.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z54.strictObject({title:z54.string().min(1).max(80),description:z54.string().min(1).max(300),command:z54.string().min(1).optional()}),IntegrationSettingSchema=z54.strictObject({type:z54.enum(["string","choice"]),label:z54.string().min(1).max(80),description:z54.string().min(1).max(300).optional(),required:z54.boolean().default(!1),optionsFrom:z54.strictObject({tool:z54.string().min(1)}).optional()}),IntegrationToolsSchema=z54.discriminatedUnion("source",[z54.strictObject({source:z54.literal("hosted")}),z54.strictObject({source:z54.literal("mcp"),url:z54.url()})]),IntegrationSkillSchema=z54.strictObject({name:z54.string().min(1).max(64),description:z54.string().min(1).max(300),content:z54.string().min(1)}),IntegrationManifestSchema=z54.strictObject({apiVersion:z54.literal(1),id:IntegrationIdSchema,version:z54.string().regex(/^\d+\.\d+\.\d+$/),listing:z54.strictObject({name:z54.string().min(1).max(60),description:z54.string().min(1).max(200),details:z54.string().min(1).max(1e3),icon:z54.string().min(1),category:z54.enum(["seo","ai-visibility","analytics","communication"]),publisher:z54.string().min(1).max(60),agentReads:z54.strictObject({label:z54.string().min(1).max(80),description:z54.string().min(1).max(200)}).optional()}),auth:z54.array(IntegrationAuthSchema).min(1),identity:z54.strictObject({label:z54.string().min(1)}).optional(),settings:z54.record(z54.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z54.array(IntegrationSkillSchema).default([]),recipes:z54.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z54.object({scope:z54.string(),reason:z54.string()}),IntegrationSettingDefinitionDTOSchema=z54.object({key:z54.string(),type:z54.enum(["string","choice"]),label:z54.string(),description:z54.string().nullable(),required:z54.boolean(),hasOptions:z54.boolean()}),IntegrationKindSchema=z54.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z54.object({id:z54.string(),kind:IntegrationKindSchema,integrationKey:z54.string(),host:z54.string().nullable(),apiKey:z54.object({label:z54.string(),placeholder:z54.string().nullable(),helpUrl:z54.string(),primary:z54.boolean()}).nullable(),mcp:z54.object({url:z54.string(),methods:z54.array(McpIntegrationSetupAuthSchema),header:z54.object({name:z54.string(),valuePrefix:z54.string()}).nullable()}).nullable(),name:z54.string(),description:z54.string(),details:z54.string(),icon:z54.string(),category:z54.string(),publisher:z54.string(),signInLabel:z54.string(),permissions:z54.array(IntegrationPermissionDTOSchema),readOnly:z54.boolean(),settings:z54.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z54.object({connectionId:z54.uuid(),alias:z54.string(),accountName:z54.string().nullable(),status:z54.enum(["active","revoked"]),authKind:z54.enum(["oauth","api_key"]),connectedAt:z54.coerce.date()}),IntegrationSiteDTOSchema=z54.object({projectId:z54.uuid(),projectName:z54.string(),enabled:z54.boolean(),granted:z54.boolean(),connectionId:z54.uuid().nullable(),settings:z54.record(z54.string(),z54.string()),missingSettings:z54.array(z54.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z54.boolean(),accounts:z54.array(IntegrationAccountDTOSchema),siteAccess:z54.enum(["all","selected"]),sites:z54.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z54.boolean(),enabled:z54.boolean(),granted:z54.boolean(),accountName:z54.string().nullable(),settingsValues:z54.record(z54.string(),z54.string()),missingSettings:z54.array(z54.string()),tools:z54.array(z54.object({key:z54.string(),name:z54.string(),description:z54.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z54.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z54.object({projectId:z54.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z54.object({connectUrl:z54.url().nullable(),expiresAt:z54.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z54.string()}),ConnectIntegrationKeyRequestSchema=z54.object({key:z54.string().trim().min(1).max(500),projectId:z54.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z54.object({token:z54.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z54.object({enabled:z54.boolean(),connectionId:z54.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z54.object({access:z54.enum(["all","selected"]).optional(),projectIds:z54.array(z54.uuid()).max(1e3),connectionId:z54.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z54.object({settings:z54.record(z54.string(),z54.string().max(500))}),IntegrationSettingOptionDTOSchema=z54.object({value:z54.string(),label:z54.string(),suggested:z54.boolean()}),IntegrationToolMatchDTOSchema=z54.object({integrationId:z54.string(),integrationName:z54.string(),key:z54.string(),name:z54.string(),description:z54.string(),effect:IntegrationToolEffectSchema,input:z54.record(z54.string(),z54.unknown())}),ProjectIntegrationGuideDTOSchema=z54.object({integrationId:z54.string(),name:z54.string(),description:z54.string(),content:z54.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z54.object({tool:z54.string().min(1).max(120),input:z54.record(z54.string(),z54.unknown()).default({}),approval:z54.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z54.boolean().optional()}),IntegrationApprovalCallShape={integration:z54.object({id:z54.string(),name:z54.string()}),tool:z54.object({key:z54.string(),name:z54.string(),effect:IntegrationToolEffectSchema}),input:z54.record(z54.string(),z54.unknown()),reason:z54.string(),canAlwaysAllow:z54.boolean()},IntegrationToolRunResultDTOSchema=z54.discriminatedUnion("status",[z54.object({status:z54.literal("ok"),output:z54.record(z54.string(),z54.unknown())}),z54.object({status:z54.literal("approval_required"),request:z54.string(),approveUrl:z54.string(),...IntegrationApprovalCallShape}),z54.object({status:z54.literal("blocked"),reason:z54.string()})]),IntegrationApprovalPreviewRequestSchema=z54.object({request:z54.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z54.object({...IntegrationApprovalCallShape,allowOnce:z54.boolean(),expiresAt:z54.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z54.string()}),IntegrationApprovalDecisionSchema=z54.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z54.object({request:z54.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z54.object({decision:IntegrationApprovalDecisionSchema,approval:z54.string().optional(),resumed:z54.boolean().optional()}),IntegrationAgentAccessDTOSchema=z54.object({reads:z54.object({label:z54.string(),description:z54.string()}).nullable(),tools:z54.array(z54.object({tool:z54.string(),label:z54.string(),description:z54.string(),allowed:z54.boolean()}))})}});import{z as z55}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=z55.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z55.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z55.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z55.object({userId:z55.string().min(1),name:z55.string(),email:z55.string().min(1),subscribed:z55.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z55.object({maxSubscribers:z55.number().int().positive(),subscriberCount:z55.number().int().nonnegative(),effectiveRecipientCount:z55.number().int().nonnegative(),currentUserSubscribed:z55.boolean(),candidates:z55.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z55.object({userIds:z55.array(z55.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z55.object({topic:UserManagedNotificationTopicSchema,enabled:z55.boolean(),source:z55.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z55.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z55.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z55.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z55.string().nullable(),maskedEmail:z55.string().min(1),applied:z55.boolean(),expiresAt:z55.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z55.object({scheduleId:z55.string().min(1),scheduleName:z55.string(),projectId:z55.string().min(1),projectName:z55.string(),env:z55.string().min(1)}),FollowedSchedulesSchema=z55.object({schedules:z55.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z56}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=z56.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=z56.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z56.uuid(),env:z56.string().min(1),name:z56.string().min(1),cron:z56.string().min(1),command:z56.string().min(1),secretKeys:z56.array(z56.string().min(1)),enabled:z56.boolean(),lastRunAt:z56.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z56.string().nullable(),suspendedAt:z56.coerce.date().nullable().optional(),suspensionReason:z56.string().nullable().optional(),overPolicyReasons:z56.array(z56.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z56.object({name:z56.string().min(1).max(120),cron:z56.string().min(1).max(120),command:z56.string().min(1).max(500),secretKeys:z56.array(ProjectSecretKeySchema).default([]),enabled:z56.boolean().optional()}),UpdateProjectScheduleRequestSchema=z56.object({name:z56.string().min(1).max(120).optional(),cron:z56.string().min(1).max(120).optional(),command:z56.string().min(1).max(500).optional(),secretKeys:z56.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z56.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z56.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z56.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z56.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z56.object({maxRuns:z56.number().int().positive(),retentionDays:z56.number().int().positive().nullable(),outputRetentionDays:z56.number().int().positive(),maxOutputBytes:z56.number().int().positive()}),SchedulePolicyStateSchema=z56.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z56.object({code:z56.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z56.enum(["cached_subscription","free_fallback"]),activeSchedules:z56.object({used:z56.number().int().nonnegative(),limit:z56.number().int().nonnegative()}),minCadenceMinutes:z56.number().int().positive(),maxRunMs:z56.number().int().positive(),concurrency:z56.object({used:z56.number().int().nonnegative(),limit:z56.number().int().positive()}),compute:z56.object({settledMs:z56.number().int().nonnegative(),activeMs:z56.number().int().nonnegative(),reservedMs:z56.number().int().nonnegative().optional(),includedMs:z56.number().int().nonnegative(),remainingMs:z56.number().int().nonnegative(),resetsAt:z56.coerce.date()}),upgrade:z56.object({code:z56.literal("Pro"),activeSchedulesLimit:z56.number().int().positive(),minCadenceMinutes:z56.number().int().positive(),maxRunMs:z56.number().int().positive(),maxConcurrentRuns:z56.number().int().positive(),computeIncludedMs:z56.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z56.array(z56.string())}),ProjectScheduleUsageSchema=z56.object({runCount:z56.number().int().nonnegative(),runsWithOutput:z56.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z56.object({id:z56.uuid(),scheduleId:z56.uuid(),projectId:z56.uuid(),env:z56.string().min(1),scheduleName:z56.string().min(1),command:z56.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z56.object({id:z56.string().min(1),name:z56.string().min(1)}).nullable(),queuedAt:z56.coerce.date(),startedAt:z56.coerce.date().nullable(),finishedAt:z56.coerce.date().nullable(),exitCode:z56.number().int().nullable(),errorCode:z56.string().nullable(),error:z56.string().nullable(),outputBytes:z56.number().int().nonnegative(),outputTruncated:z56.boolean(),outputExpiresAt:z56.coerce.date().nullable(),metadataExpiresAt:z56.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z56.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z56.coerce.date().nullable(),items:z56.array(z56.object({key:z56.string().min(1),updatedAt:z56.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z56.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z56.object({trigger:z56.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z56.object({limit:z56.coerce.number().int().min(1).max(100).default(25),cursor:z56.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z56.object({items:z56.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z56.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z56.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z56.object({items:z56.array(ProjectScheduleRunDTOSchema),nextCursor:z56.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z57}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=z57.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z57.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z57.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z57.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z57.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z57.discriminatedUnion("kind",[z57.object({kind:z57.literal("user"),userId:z57.string().min(1)}).strict(),z57.object({kind:z57.literal("agent"),agentKey:z57.string().min(1).max(120),agentId:z57.uuid().optional()}).strict(),z57.object({kind:z57.literal("system")}).strict()]),NotificationSummarySchema=z57.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z57.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z57.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z57.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z57.object({sessionId:z57.uuid(),branch:z57.string().min(1),targetBranch:z57.string().min(1),revision:z57.string().min(1),fingerprint:z57.string().min(1)}),NotificationPayloadSchema=z57.discriminatedUnion("topic",[z57.object({topic:z57.literal("database_quota_exceeded"),incidentId:z57.uuid(),observedAt:z57.iso.datetime()}).strict(),z57.object({topic:z57.literal("agent_run_outcome"),threadId:z57.uuid(),invocationId:z57.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("agent_retained_review"),threadId:z57.uuid().optional(),invocationId:z57.uuid().optional(),proposalId:z57.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("agent_conflict"),mergeId:z57.uuid(),threadId:z57.uuid().optional(),invocationId:z57.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z57.object({topic:z57.literal("publication_failed"),publicationId:z57.uuid(),sourceBranch:z57.string().trim().min(1).max(120),failureCode:z57.string().trim().min(1).max(64),failedAt:z57.iso.datetime(),firstPublication:z57.boolean()}).strict()]),NotificationEnvelopeSchema=z57.object({id:z57.uuid(),projectId:z57.uuid(),sourceKey:z57.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z57.literal(1),payload:NotificationPayloadSchema,createdAt:z57.coerce.date()}),NotificationDeliveryStateSchema=z57.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z57.object({id:z57.uuid(),notificationRecipientId:z57.uuid(),projectId:z57.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z57.number().int().nonnegative(),nextAttemptAt:z57.coerce.date().nullable(),lastAttemptAt:z57.coerce.date().nullable(),sentAt:z57.coerce.date().nullable(),failureCode:z57.string().max(80).nullable(),createdAt:z57.coerce.date(),updatedAt:z57.coerce.date()}),NotificationPreferenceSchema=z57.object({topic:WorkNotificationTopicSchema,channel:z57.literal("email"),enabled:z57.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z57.enum(["default","explicit"])})}});import{z as z58}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=z58.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=z58.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z58.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z58.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z58.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z58.object({enabled:z58.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z58.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z58.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z58.discriminatedUnion("kind",[z58.object({kind:z58.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z58.enum(["work_review","publishing","schedule"]),enabled:z58.boolean(),source:PreferenceSourceSchema}).strict(),z58.object({kind:z58.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z58.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z58.object({kind:z58.literal("provider_subscription"),id:z58.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z58.literal("marketing"),name:z58.string(),description:z58.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z58.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z58.object({email:EmailNotificationPreferenceSchema,entries:z58.array(NotificationPreferenceEntrySchema),unavailableGroups:z58.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z58.object({enabled:z58.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z58.discriminatedUnion("kind",[z58.object({kind:z58.literal("toggle"),enabled:z58.boolean()}).strict(),z58.object({kind:z58.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z58.object({kind:z58.literal("provider_subscription"),enabled:z58.boolean()}).strict()])}});import{z as z59}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=z59.object({surface:SurfaceNameSchema,key:z59.string(),label:z59.string()}),InlineSchema=z59.object({text:z59.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z59.discriminatedUnion("type",[z59.object({type:z59.literal("paragraph"),content:z59.array(InlineSchema).max(24)}),z59.object({type:z59.literal("preview"),ref:DiffRefSchema,caption:z59.string().optional()}),z59.object({type:z59.literal("code"),code:z59.string(),lang:z59.string().optional(),caption:z59.string().optional()}),z59.object({type:z59.literal("risk"),level:z59.enum(["warning","error"]),content:z59.array(InlineSchema).max(24)}),z59.object({type:z59.literal("list"),items:z59.array(z59.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z59.object({headline:z59.string(),blocks:z59.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z59.object({summary:EnvDiffSummarySchema,fingerprint:z59.string(),generatedAt:z59.coerce.date(),cached:z59.boolean().optional(),credits:z59.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z60}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=z60.object({date:z60.string(),visitors:z60.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z60.object({key:z60.string(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z60.object({path:z60.string(),pageName:z60.string().nullable().optional(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z60.object({preset:z60.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z60.string(),requestedTo:z60.string(),effectiveFrom:z60.string(),effectiveTo:z60.string(),isRetentionLimited:z60.boolean(),groupBy:z60.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z60.object({date:z60.string(),content:z60.string(),updatedAt:z60.string(),updatedByUserId:z60.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z60.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z60.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z60.number().int().nonnegative(),pageviews:z60.number().int().nonnegative(),botPageviews:z60.number().int().nonnegative(),botVisitors:z60.number().int().nonnegative(),bounceRate:z60.number().min(0).max(100),viewsPerVisit:z60.number().nonnegative(),averageVisitDurationSeconds:z60.number().nonnegative(),visitorsSeries:z60.array(ProjectDailyVisitorsDTOSchema),topPages:z60.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z60.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z60.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z60.object({state:z60.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z60.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z61}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=z61.object({id:z61.string(),email:z61.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z61.coerce.date(),createdAt:z61.coerce.date(),inviterUserId:z61.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z61.object({id:z61.string(),token:z61.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z61.object({success:z61.boolean(),projectId:z61.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z62}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=z62.object({id:z62.string(),name:z62.string(),image:z62.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z62.object({count:z62.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z62.object({counts:z62.object({signed_up:z62.int(),activated:z62.int()}),credits:z62.object({total:z62.int(),earned:z62.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z62.email(),emailVerified:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z63}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=z63.object({id:z63.string(),principalType:ProjectPrincipalTypeSchema,principalId:z63.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z63.coerce.date(),expiresAt:z63.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z63.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:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z63.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z63.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z63.record(z63.string(),z63.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z63.object({access:z63.array(ProjectAccessItemDTOSchema),invites:z63.array(ProjectInviteDTOSchema),organization:z63.object({name:z63.string().nullable(),logo:z63.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z63.object({success:z63.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z63.object({success:z63.boolean(),projectId:z63.uuid()}))}});import{z as z64}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=z64.object({publicationStatus:PublicationStatusSchema,appUrl:z64.string().nullable(),lastPublishedAt:z64.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z65}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=z65.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z65.object({branch:BranchSchema,revision:z65.string().min(1).max(64).nullable(),generation:z65.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z65.url().nullable()})}});import{z as z66}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=z66.object({code:z66.literal("PREVIEW_UPGRADE_REQUIRED"),message:z66.string(),currentVersion:z66.number().int().positive(),targetVersion:z66.literal(4)}),PreviewBridgePackageSchema=z66.object({name:z66.string().min(1),version:z66.string().min(1)}),PreviewBridgeCapabilitySchema=z66.object({integrated:z66.boolean(),packages:z66.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z66.object({url:z66.url(),expiresAt:z66.iso.datetime().nullable(),source:z66.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z66.object({name:z66.string().min(1),locator:z66.string().min(1).optional(),source:z66.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z66.object({kind:z66.literal("dependency_build_scripts_blocked"),packageManager:z66.enum(["pnpm","yarn","bun"]),packages:z66.array(z66.string()),targets:z66.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z66.string(),approvalKey:z66.string(),command:z66.string().optional(),approval:z66.object({id:z66.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z66.object({code:z66.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z66.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z66.object({code:z66.literal("PREVIEW_START_FAILED"),message:z66.string(),logTail:z66.array(z66.string()).optional(),logTailTruncated:z66.boolean().optional()}),SandboxPullPhaseSchema=z66.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z66.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z66.object({message:z66.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z66.number().int().optional().catch(void 0),logTail:z66.array(z66.string()).optional().catch(void 0),logTailTruncated:z66.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z66.object({approvalId:z66.uuid()}),PreviewInstallPolicyApprovalEventSchema=z66.discriminatedUnion("type",[z66.object({type:z66.literal("progress"),step:z66.enum(["approval","install","restart","readiness"]),message:z66.string()}),z66.object({type:z66.literal("approved")}),z66.object({type:z66.literal("complete")}),z66.object({type:z66.literal("error"),code:z66.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z66.string()})])}});import{z as z67}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:z67.string(),slug:z67.string().nullable(),logo:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z67.object({id:z67.string(),name:z67.string(),email:z67.email(),image:z67.string().nullable()}),OrganizationMemberDTOSchema=z67.object({id:z67.string(),userId:z67.string(),organizationId:z67.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z67.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z67.object({canCreateProject:z67.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z68}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=z68.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z68.object({reason:CancellationReasonCodeSchema,details:z68.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z68.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z68.object({offerVersion:z68.string().trim().min(1),unusedPremiumCreditAmount:z68.number().int().nonnegative(),amountDueNow:z68.number().int().nonnegative(),renewsOn:z68.string()}),PlanMigrationPreviewDTOSchema=z68.object({currency:z68.string().trim().min(1),unusedPremiumCreditAmount:z68.number().int().nonnegative(),amountDueNow:z68.number().int().nonnegative(),startsAt:z68.string(),renewsAt:z68.string(),nextRenewalAmount:z68.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z68.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z68.object({id:z68.string(),organizationId:z68.string(),legacySubscriptionId:z68.string(),offeredPlanCode:z68.string(),offeredPlanName:z68.string(),offeredPriceAmount:z68.number(),offeredCurrency:z68.string(),offerVersion:z68.string(),state:PlanMigrationStateSchema,checkoutToken:z68.string().nullable(),deadlineAt:z68.string(),transitions:z68.array(z68.object({event:z68.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z68.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z68.object({included:z68.number().optional(),unitPrice:z68.number().optional(),dailyCap:z68.number().nullable().optional()}),EntitlementsDTOSchema=z68.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z68.object({retentionDays:z68.number().int().positive(),canUseExtendedDateRanges:z68.boolean()}).optional(),history:z68.object({retentionDays:z68.number().int().positive()}).optional(),members:z68.object({canInvite:z68.boolean(),maxMembers:z68.number().int().positive().nullable()}).optional(),projects:z68.object({maxProjects:z68.number().int().positive().nullable()}).optional(),domains:z68.object({canUseCustomDomains:z68.boolean(),maxDomains:z68.number().int().nonnegative().nullable()}).optional(),media_storage:z68.object({limitBytes:z68.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z68.object({usedBytes:z68.number().int().nonnegative().nullable(),limitBytes:z68.number().int().nonnegative().nullable(),state:z68.enum(["ready","unavailable"]),measuredAt:z68.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z68.object({toPlanCode:TemplateCodeSchema,effectiveAt:z68.string(),scheduledAt:z68.string().nullable()}),AutomaticSpendStopDTOSchema=z68.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z68.string(),spendStopped:z68.boolean(),settlementEndsAt:z68.string()}),HostingOverageStatusDTOSchema=z68.object({state:z68.enum(["ready","unavailable"]),planCode:z68.string(),overageAvailable:z68.boolean(),overageEnabled:z68.boolean(),monthlyCapUsd:z68.number().int().positive().nullable(),periodStart:z68.iso.datetime().nullable(),periodEnd:z68.iso.datetime().nullable(),usedBytes:z68.number().nonnegative().nullable(),includedBytes:z68.number().nonnegative().nullable(),overageBytes:z68.number().nonnegative(),currentOverageAmountMicros:z68.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z68.number().nonnegative().nullable(),currency:z68.string().nullable(),status:z68.enum(["ok","near_limit","paused"]),databaseCompute:z68.object({includedHoursPerSite:z68.number().nonnegative().nullable(),overageHours:z68.number().nonnegative(),fundedHours:z68.number().nonnegative(),sitesOverAllowance:z68.number().int().nonnegative(),rateMicrosPerHour:z68.number().nonnegative().nullable(),amountMicros:z68.number().nonnegative().nullable(),budgetSpent:z68.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z68.object({enabled:z68.boolean(),monthlyCapUsd:z68.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z68.object({id:z68.string(),external_id:z68.string(),customerId:z68.string(),planId:z68.string(),planCode:z68.union([TemplateCodeSchema,z68.literal("Unknown")]),currentPeriod:z68.object({start:z68.string(),end:z68.string().nullable()}),cancelAt:z68.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z68.string(),nextPaymentAt:z68.string().nullable(),baseAmount:z68.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z68.object({totalCap:z68.number(),dailyCap:z68.number(),usedTotal:z68.number()}),CreditBalanceDTOSchema=z68.object({total:z68.number(),base:z68.number(),dailyBase:z68.number(),purchases:z68.number(),awards:z68.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z68.object({total:z68.number(),nearLimit:z68.boolean(),canChat:z68.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z68.object({dailyFreeAvailable:z68.number(),monthlyAvailable:z68.number(),purchasedAvailable:z68.number(),awardedAvailable:z68.number()}),ProjectDailyCreditAllowanceDTOSchema=z68.object({periodCap:z68.number(),dailyGrant:z68.number(),usedThisPeriod:z68.number(),remainingThisPeriod:z68.number()}),ProjectCreditBalanceDTOSchema=z68.object({projectId:z68.uuid(),organizationId:z68.string(),balance:z68.object({totalAvailable:z68.number(),nearLimit:z68.boolean(),canUseAi:z68.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z68.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z68.discriminatedUnion("enabled",[z68.object({enabled:z68.literal(!0),thresholdUsd:z68.number().nonnegative(),refillAmountUsd:z68.number().nonnegative()}),z68.object({enabled:z68.literal(!1),thresholdUsd:z68.number().nonnegative().nullable(),refillAmountUsd:z68.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z68.discriminatedUnion("enabled",[z68.object({enabled:z68.literal(!0),thresholdUsd:z68.number().min(.01).multipleOf(.01),refillAmountUsd:z68.number().min(.01).multipleOf(.01),expectedRateToken:z68.string().trim().min(1).max(40)}).strict(),z68.object({enabled:z68.literal(!1),thresholdUsd:z68.number().min(.01).multipleOf(.01),expectedRateToken:z68.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z68.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z68.object({planCode:z68.union([TemplateCodeSchema,z68.literal("Unknown")]).nullable(),canPurchase:z68.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z68.number().int().positive(),minAmountUsd:z68.number().positive(),maxAmountUsd:z68.number().positive(),rateToken:z68.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z68.object({amountUsd:z68.number(),idempotencyKey:z68.string().trim().min(8).max(120),expectedRateToken:z68.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z68.object({invoiceId:z68.string(),newBalance:z68.int(),creditCount:z68.int(),amountUsd:z68.number(),creditsPerDollar:z68.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z68.object({url:z68.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z68.object({id:z68.string(),number:z68.string().nullable(),status:z68.string(),amountDue:z68.int(),currency:z68.string(),issuedAt:z68.string().nullable(),hostedInvoiceUrl:z68.string().nullable()}),PaymentRecoveryDTOSchema=z68.discriminatedUnion("status",[z68.object({status:z68.literal("eligible"),checkedAt:z68.string()}),z68.object({status:z68.literal("recovery_required"),checkedAt:z68.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z68.int().min(1)}),z68.object({status:z68.literal("unavailable"),checkedAt:z68.string(),reason:z68.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 z69}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=z69.object({brand:z69.string(),last4:z69.string(),exp:z69.string(),isDefault:z69.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z70}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=z70.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=z70.object({type:z70.literal("renameField"),contentType:z70.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z70.object({enabled:z70.boolean()}).strict(),ContentFieldGroupSchema=z70.object({id:z70.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z70.string().min(1).max(255),default:z70.boolean().optional()}).strict(),ContentTypeDTOSchema=z70.object({id:z70.string(),name:z70.string(),label:z70.string(),isSingleton:z70.boolean(),i18n:ContentTypeI18nSchema,description:z70.string().nullable().default(null),groups:z70.array(ContentFieldGroupSchema).default([]),fields:z70.record(z70.string(),FieldDefinitionSchema),createdAt:z70.string(),updatedAt:z70.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z70.object({contentTypes:z70.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z70.object({id:z70.string(),entryId:z70.string(),documentId:z70.string(),slug:z70.string(),locale:z70.string().optional(),createdAt:z70.string(),updatedAt:z70.string(),__fimo:z70.object({contentType:z70.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({limit:z70.number(),offset:z70.number(),total:z70.number(),hasMore:z70.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z70.object({contentType:z70.string(),count:z70.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z70.object({counts:z70.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z70.object({count:z70.number().int().nonnegative(),sourceLocale:z70.string(),targetLocale:z70.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z70.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z70.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z70.union([z70.string(),z70.number(),z70.boolean(),z70.null()]),entryWhereOperatorSchema=z70.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z70.array(entryWhereScalarSchema).optional(),$nin:z70.array(entryWhereScalarSchema).optional(),$contains:z70.string().optional(),$startsWith:z70.string().optional(),$null:z70.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z70.record(z70.string(),z70.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z70.record(z70.string(),z70.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z70.object({data:z70.record(z70.string(),z70.unknown()),locale:z70.string().min(1).optional(),documentId:z70.uuid().optional()}),entryIdsSchema=z70.array(z70.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z70.object({sql:z70.string().min(1)}),BulkCreateEntriesRequestSchema=z70.object({entries:z70.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z70.union([z70.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z70.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z70.object({updates:z70.array(z70.object({id:z70.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z70.union([z70.object({ids:entryIdsSchema,locale:z70.string().min(1).optional()}),z70.object({where:EntryWhereSchema,locale:z70.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z70.object({data:z70.array(z70.record(z70.string(),z70.unknown())),meta:z70.object({rowCount:z70.number().int().nonnegative(),truncated:z70.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({created:z70.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({updated:z70.number().int().nonnegative(),missing:z70.array(z70.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z70.object({data:z70.array(EntryDTOSchema),meta:z70.object({deleted:z70.number().int().nonnegative(),missing:z70.array(z70.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z71}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z71.object({index:z71.number().int().nonnegative(),contentType:z71.string(),field:z71.string(),value:z71.string(),against:z71.enum(["stored","batch"]),ownerDocumentId:z71.uuid().optional(),ownerIndex:z71.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z71.object({code:z71.literal("unique_conflict"),message:z71.string(),conflicts:z71.array(UniqueConflictSchema),truncated:z71.boolean().optional()})}});import{z as z72}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=z72.object({kind:z72.literal("unique_conflict"),contentType:z72.string(),field:z72.string(),value:z72.string(),documentCount:z72.number().int().positive(),documentIds:z72.array(z72.uuid()),documentIdsTruncated:z72.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z72.object({code:z72.literal("schema_transition_rejected"),message:z72.string(),issues:z72.array(SchemaTransitionIssueSchema),truncated:z72.boolean().optional()})}});import{z as z73}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=z73.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z73.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z73.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z73.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z73.object({field:CmsFieldNameSchema,direction:z73.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z73.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z73.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z73.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z73.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z73.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z74}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=z74.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z75}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=z75.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z75.object({event:ClientTrackedEventSchema,properties:z75.record(z75.string(),z75.unknown()).default({})})}});import{z as z76}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=z76.object({id:z76.string(),name:z76.string()}),AssetDTOSchema=z76.object({id:z76.string(),name:z76.string(),type:AssetTypeSchema,originalFileName:z76.string().nullable(),parentId:z76.string().nullable(),mimeType:z76.string().nullable(),fileSize:z76.number().nullable(),url:z76.string().nullable(),storageKey:z76.string().nullable(),createdAt:z76.string(),updatedAt:z76.string(),altText:z76.string().nullable().optional(),caption:z76.string().nullable().optional(),aiCaption:z76.string().nullable().optional(),aiAltText:z76.string().nullable().optional(),aiTags:z76.array(z76.string()).nullable().optional(),aiPrimaryColor:z76.string().nullable().optional(),aiProcessingStatus:z76.string().nullable().optional(),width:z76.number().nullable().optional(),height:z76.number().nullable().optional(),path:z76.array(AssetPathItemSchema).optional(),hasChildren:z76.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z76.lazy(()=>z76.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z76.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z76.object({error:z76.string(),code:z76.literal("media_storage_limit_exceeded"),usedBytes:z76.number().int().nonnegative(),limitBytes:z76.number().int().positive(),incomingBytes:z76.number().int().nonnegative()}),AssetReferenceScopeSchema=z76.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z76.object({assetIds:z76.array(z76.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z76.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z76.object({totalFiles:z76.number().int().nonnegative(),checkedFiles:z76.number().int().nonnegative(),limit:z76.number().int().positive()}),AssetReferenceFindingDTOSchema=z76.object({assetId:z76.uuid(),entryId:z76.string(),documentId:z76.string(),contentType:z76.string(),locale:z76.string().nullable(),slug:z76.string(),fieldPath:z76.string()}),AssetReferenceScopeResultDTOSchema=z76.object({scope:AssetReferenceScopeSchema,label:z76.string(),state:z76.enum(["available","not-published","failed"]),coverage:z76.enum(["complete","partial","failed"]),referenceCount:z76.number().int().nonnegative().optional(),codeReferenceCount:z76.number().int().nonnegative().optional(),referencedAssetIds:z76.array(z76.uuid()).optional(),references:z76.array(AssetReferenceFindingDTOSchema),reason:z76.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z76.discriminatedUnion("type",[z76.object({type:z76.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z76.object({type:z76.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z76.object({type:z76.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z76.object({replacementAssetId:z76.uuid()}),AssetReferenceReplacementResultSchema=z76.object({referencesReplaced:z76.number().int().nonnegative(),entriesChanged:z76.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z76.object({referencesReplaced:z76.number().int().nonnegative(),filesChanged:z76.number().int().nonnegative(),commitSha:z76.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z76.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=z76.object({error:z76.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z76.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=z76.object({intent:AssetRemovalIntentSchema,assetIds:z76.array(z76.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z76.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=z76.object({id:z76.uuid(),intent:AssetRemovalIntentSchema,assetIds:z76.array(z76.uuid()),replacementAssetId:z76.uuid().nullable(),expiresAt:z76.iso.datetime(),undoable:z76.boolean(),requestedByMe:z76.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z76.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z76.object({error:z76.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z77}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z77.object({key:z77.string(),value:z77.string().optional(),defaultValue:z77.string(),locale:z77.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z78}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=z78.object({id:z78.string(),name:z78.string(),type:z78.enum(["file","folder"]),path:z78.string(),children:z78.lazy(()=>z78.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z78.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z78.object({path:z78.string(),exists:z78.boolean(),type:z78.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z79}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=z79.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z79.object({minLength:z79.number().optional(),maxLength:z79.number().optional(),min:z79.number().optional(),max:z79.number().optional(),pattern:z79.string().optional(),maxFileSize:z79.number().optional(),accept:z79.array(z79.string()).optional()}),FormFieldSchema=z79.object({type:FormFieldTypeSchema,label:z79.string(),placeholder:z79.string().optional(),required:z79.boolean().optional(),defaultValue:z79.string().optional(),options:z79.array(z79.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z79.record(z79.string(),FormFieldSchema),FormContentSchema=z79.object({name:z79.string().min(1).max(255),label:z79.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 z80}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z80.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z80.object({id:z80.string().uuid(),label:z80.string(),status:ChatTaskStatusSchema,startedAt:z80.string(),endedAt:z80.string().nullable(),result:z80.string().nullable()}),ChatTaskListDTOSchema=z80.object({tasks:z80.array(ChatTaskDTOSchema)})}});import{z as z81}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=z81.object({name:z81.string().trim().min(1).max(120).optional(),description:z81.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z81.string().min(1)).optional(),live:z81.literal(!0).optional()}),AgentToolInputSchema=AgentPatchSchema.extend({create:z81.literal(!0).optional()}),AgentToolRoutineSchema=z81.object({id:z81.string(),name:z81.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z81.string().nullable()}),AgentToolErrorCodeSchema=z81.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z81.discriminatedUnion("ok",[z81.object({ok:z81.literal(!0),agent:z81.object({id:z81.string(),name:z81.string(),live:z81.boolean(),routines:z81.array(AgentToolRoutineSchema)}),revisionId:z81.string().optional()}),z81.object({ok:z81.literal(!1),error:z81.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z81.object({kind:z81.enum(["person","agent"]),id:z81.string().nullable(),name:z81.string().nullable()}),AgentInstructionRevisionDTOSchema=z81.object({id:z81.string().uuid(),previous:z81.string().nullable(),instructions:z81.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z81.string()}),AgentInstructionRevisionListDTOSchema=z81.object({revisions:z81.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z81.object({revisionId:z81.string().uuid()})}});import{z as z82}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=z82.object({url:z82.string().url(),key:z82.string(),size:z82.number(),contentType:z82.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z83}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=z83.object({canAccess:z83.boolean(),permissions:z83.record(z83.string(),z83.boolean()),role:z83.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z84}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:z84.string().trim().default(""),sort:z84.enum(["recent","name","relevance"]).default("recent"),category:z84.string().optional()})}});import{z as z85}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=z85.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z85.enum(["fimo","external"]),PaymentStatusSchema=z85.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z85.object({id:z85.string().uuid(),domain:z85.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z85.boolean(),price:z85.number().int().nullable(),renewalPrice:z85.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z85.string().nullable(),failureReason:z85.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z85.object({domain:z85.string(),available:z85.boolean(),premium:z85.boolean(),price:z85.number().nullable(),renewalPrice:z85.number().nullable(),purchaseType:z85.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z85.object({domain:z85.string(),price:z85.number().nullable(),renewalPrice:z85.number().nullable(),premium:z85.boolean(),allowedYears:z85.array(z85.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z85.object({firstName:z85.string().max(100),lastName:z85.string().max(100),companyName:z85.string().max(100).optional(),address1:z85.string().max(255),address2:z85.string().max(255).optional(),city:z85.string().max(100),state:z85.string().max(100),zip:z85.string().max(20),country:z85.string().max(2),phone:z85.string().max(30),email:z85.union([z85.string().email().max(255),z85.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z85.object({firstName:z85.string().min(1).max(100),lastName:z85.string().min(1).max(100),companyName:z85.string().max(100).optional(),address1:z85.string().min(1).max(255),address2:z85.string().max(255).optional(),city:z85.string().min(1).max(100),state:z85.string().min(1).max(100),zip:z85.string().min(1).max(20),country:z85.string().min(1).max(2),phone:z85.string().min(1).max(30),email:z85.string().email().max(255)}),SearchDomainsRequestSchema=z85.object({keyword:z85.string().min(1).max(100),tldFilter:z85.array(z85.string()).optional()}),CheckAvailabilityRequestSchema=z85.object({domains:z85.array(z85.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=z85.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z85.object({domain:DomainNameSchema,years:z85.number().int().min(1).max(10).optional().default(3),autoRenew:z85.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z85.object({autoRenew:z85.boolean().optional()}),RenewDomainRequestSchema=z85.object({years:z85.number().int().min(1).max(10).optional().default(1),autoRenew:z85.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z85.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z85.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z85.object({verified:z85.boolean(),email:z85.string().nullable(),verifyBy:z85.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z86}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=z86.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=z86.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=z86.object({txtName:z86.string().nullable().optional(),txtValue:z86.string().nullable().optional(),httpUrl:z86.string().nullable().optional(),httpBody:z86.string().nullable().optional(),cname:z86.string().nullable().optional(),cnameTarget:z86.string().nullable().optional()}),SSLValidationErrorSchema=z86.object({message:z86.string()}),OwnershipVerificationSchema=z86.object({type:z86.string(),name:z86.string(),value:z86.string()}),ProjectDomainSSLDTOSchema=z86.object({status:z86.string(),method:z86.string().nullable(),type:z86.string().nullable(),validationRecords:z86.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z86.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z86.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z86.enum(["subdomain","apex"]),RedirectStatusSchema=z86.union([z86.literal(301),z86.literal(302),z86.literal(307),z86.literal(308)]),DomainRedirectSchema=z86.object({targetDomainId:z86.string(),targetHostname:z86.string(),status:RedirectStatusSchema}).nullable(),ProjectDomainDTOSchema=z86.object({id:z86.string(),hostname:z86.string(),status:z86.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z86.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z86.string(),scdCnameTarget:z86.string().optional(),apexTargets:z86.array(z86.string()),dnsAutoConfigured:z86.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirect:DomainRedirectSchema,migrationStatus:z86.string().nullable().optional(),primary:z86.boolean()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z86.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z86.object({hostname:z86.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:z86.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z86.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z86.object({available:z86.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z86.object({success:z86.boolean(),hostname:z86.string(),removed:z86.array(z86.object({id:z86.string(),hostname:z86.string()}))})),DEFAULT_REDIRECT_STATUS=307,SetProjectDomainRedirectRequestSchema=z86.object({targetDomainId:z86.uuid().toLowerCase(),status:RedirectStatusSchema.default(DEFAULT_REDIRECT_STATUS)})}});import{z as z87}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=z87.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z87.object({available:z87.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z87.object({slug:z87.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z87.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z87.object({subdomain:z87.string(),subdomainUpdatedAt:z87.coerce.date()})),SubdomainSuggestionsQuerySchema=z87.object({base:z87.string().max(100).optional(),max:z87.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z87.object({suggestions:z87.array(z87.string())}))}});import{z as z88}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","source_registered_domain"],ProjectTransferBlockerCodeSchema=z88.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z88.object({code:ProjectTransferBlockerCodeSchema,message:z88.string(),count:z88.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z88.object({targetOrganizationId:z88.string().min(1)}),ProjectTransferResultDTO=createDTO(z88.object({projectId:z88.string(),sourceOrganizationId:z88.string(),targetOrganizationId:z88.string(),movedThreads:z88.number().int().nonnegative(),revokedInvites:z88.number().int().nonnegative(),revokedGrants:z88.number().int().nonnegative(),preservedGrants:z88.number().int().nonnegative(),warnings:z88.array(z88.string())}))}});import{z as z89}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=z89.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z89.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=z89.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z89.object({displayName:z89.string().trim().min(1).max(80),machineId:z89.string().trim().min(1).max(128).optional(),cliVersion:z89.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z89.object({ttlHours:z89.number().int().positive(),lockedFeatures:z89.array(UnclaimedLockedFeatureSchema),media:z89.object({totalBytes:z89.number().int().nonnegative(),fileBytes:z89.number().int().positive(),maxFiles:z89.number().int().nonnegative(),mimeTypes:z89.array(z89.string())}),database:z89.object({storageBytes:z89.number().int().positive(),computeSeconds:z89.number().int().positive(),maxComputeUnits:z89.number().positive()})}),UnclaimedProjectClaimSchema=z89.object({url:z89.string().url(),expiresAt:z89.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z89.object({project:ProjectDTOSchema,token:z89.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z89.object({state:UnclaimedClaimStateSchema,displayName:z89.string().nullable(),expiresAt:z89.coerce.date().nullable(),projectId:z89.string().nullable()})),UnclaimedClaimSecretSchema=z89.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z89.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z89.object({secrets:z89.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z89.object({claims:z89.array(z89.object({state:UnclaimedClaimStateSchema,expiresAt:z89.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z89.object({secret:UnclaimedClaimSecretSchema,organizationId:z89.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z89.object({projectId:z89.string(),organizationId:z89.string()})),ProjectTokenSelfDTO=createDTO(z89.object({kind:z89.literal("project_token"),projectId:z89.string(),projectName:z89.string(),displayName:z89.string().nullable(),organizationId:z89.string().nullable(),organizationName:z89.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z89.coerce.date().nullable(),tokenExpiresAt:z89.coerce.date().nullable()}))}});import{z as z90}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=z90.object({translated:z90.number().int().nonnegative(),total:z90.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z90.object({locale:z90.string(),isDefault:z90.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z90.object({defaultLocale:z90.string(),locales:z90.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z90.object({locale:z90.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z90.object({locale:z90.string().min(1).max(40)}),ProjectLocaleMutationSchema=z90.object({locale:z90.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z90.object({locale:z90.string(),entriesDeleted:z90.number().int().nonnegative(),labelsDeleted:z90.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z91}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=z91.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z91.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=z91.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z91.number(),credits:z91.number().optional(),billingMode:z91.enum(["fimo-credits","provider-account"]).optional(),confidence:z91.enum(["exact","estimated","metered"]),basis:z91.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z92}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=z92.object({options:z92.record(z92.string(),z92.unknown()),name:z92.string().optional(),parentId:z92.string().nullable().optional(),altText:z92.string().optional(),caption:z92.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z92.string().min(1).optional(),model:z92.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=z92.object({jobId:z92.string(),status:z92.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z92.string().nullable().optional(),credits:z92.number().optional(),costUsd:z92.number().optional(),billingMode:z92.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z92.object({error:z92.string(),code:z92.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:z92.array(GenerationTaskIdSchema).optional(),availableModels:z92.array(z92.string()).optional(),issues:z92.array(z92.unknown()).optional()})}});import{z as z93}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=z93.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z93.object({name:z93.string(),key:z93.string(),description:z93.string(),type:FlagTypeSchema,required:z93.boolean(),defaultValue:z93.unknown().optional(),enumValues:z93.array(z93.string()).optional(),isArray:z93.boolean()}),AssetModelPriceSchema=z93.object({unitPrice:z93.number(),unit:z93.string(),confidence:z93.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z93.object({id:z93.string(),shortName:z93.string(),provider:z93.string(),source:z93.string(),modality:z93.enum(["image","video","audio"]),tags:z93.array(z93.string()),displayName:z93.string(),description:z93.string(),flags:z93.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z93.object({model:z93.string(),costUsd:z93.number(),credits:z93.number(),billingMode:z93.enum(["fimo-credits","provider-account"]),confidence:z93.enum(["exact","estimated","metered"]),basis:z93.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z94}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=z94.object({tourId:z94.string(),version:z94.string(),status:z94.string(),completedAt:z94.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z94.array(UserTourDTOSchema))}});import{z as z95}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=z95.object({backendProfile:OpsBackendProfileSchema,provider:z95.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z95.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z95.object({backendProfile:OpsBackendProfileSchema,provider:z95.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z95.literal(!1),reason:z95.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z96}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=z96.object({packageManager:z96.string().trim().min(1).max(200).nullable(),trackedLockfiles:z96.array(z96.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z96.string().trim().min(1)}),OpsProjectPackageManagerSchema=z96.object({target:z96.object({backendProfile:OpsBackendProfileSchema,projectId:z96.uuid(),projectEnv:z96.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z97}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:z97.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z97.union([z97.object({name:z97.string().trim().min(1).max(120),description:z97.string().trim().min(1).max(2e3)}).strict(),z97.object({template:z97.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z97.object({agent:OpsAgentChatAgentSpecSchema,routines:z97.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:z97.string().trim().min(1).max(1e3),dryRun:z97.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z97.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z97.object({id:z97.string().uuid().nullable(),name:z97.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z97.string().nullable(),paused:z97.boolean(),outcome:z97.enum(["created","would_create"]),source:z97.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z97.object({target:z97.object({backendProfile:OpsBackendProfileSchema,projectId:z97.string().uuid()}),dryRun:z97.boolean(),applied:z97.boolean(),createdBy:z97.object({userId:z97.string()}),agent:z97.object({id:z97.string().uuid().nullable(),title:z97.string(),template:z97.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z97.array(OpsAgentChatRoutineResultSchema),skipped:z97.array(z97.object({name:z97.string(),reason:z97.literal("routine_exists")})),refused:z97.array(z97.object({name:z97.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z98}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=z98.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z98.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z98.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z98.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z98.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z98.object({reason:WebhookEntryChangeReasonSchema,operationId:z98.string().optional(),batch:z98.object({index:z98.number().int().positive(),total:z98.number().int().positive()}).optional(),changes:z98.array(z98.object({action:WebhookEntryChangeActionSchema,contentType:z98.string(),id:z98.string(),documentId:z98.string(),locale:z98.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z98.object({form:z98.object({id:z98.string(),label:z98.string()}),submission:z98.object({id:z98.string(),data:z98.record(z98.string(),z98.unknown()),submittedAt:z98.string()})}),PublishStartedWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("publishing"),startedAt:z98.string()})}),PublishSucceededWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("published"),url:z98.string(),publishedAt:z98.string(),firstPublish:z98.boolean()})}),PublishFailedWebhookEventDataSchema=z98.object({publication:z98.object({status:z98.literal("failed"),reason:z98.string()})}),PublishUnpublishedWebhookEventDataSchema=z98.object({publication:z98.object({previousUrl:z98.string(),unpublishedAt:z98.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z98.object({report:z98.object({weekStart:z98.string(),weekEnd:z98.string(),pageviews:z98.number(),visitors:z98.number(),previousPageviews:z98.number(),previousVisitors:z98.number()})}),MediaAssetWebhookEventDataSchema=z98.object({id:z98.string().nullable(),name:z98.string().nullable(),type:z98.string(),mimeType:z98.string().nullable(),fileSize:z98.number().nullable()}),MediaUploadedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("updated")}),MediaDeletedWebhookEventDataSchema=z98.object({asset:MediaAssetWebhookEventDataSchema,operation:z98.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z98.object({domain:z98.object({id:z98.string(),hostname:z98.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z98.object({domain:z98.object({id:z98.string(),hostname:z98.string()})}),LabelChangedWebhookEventDataSchema=z98.object({changes:z98.array(z98.object({action:z98.enum(["created","updated","deleted"]),key:z98.string(),locale:z98.string(),value:z98.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),isDefault:z98.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),previousCode:z98.string()})}),LocaleDeletedWebhookEventDataSchema=z98.object({locale:z98.object({code:z98.string(),entriesDeleted:z98.number().int().nonnegative(),labelsDeleted:z98.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z98.object({environment:z98.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z98.object({environment:z98.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z98.object({merge:z98.object({id:z98.string(),from:BranchSchema,to:BranchSchema,applied:z98.array(z98.object({surface:SurfaceNameSchema,count:z98.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z98.object({branch:z98.object({name:BranchSchema}),version:z98.object({versionId:z98.uuid(),name:z98.string()})}),WebhookEventFamilySchema=z98.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z98.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z98.discriminatedUnion("source",[z98.object({source:z98.literal("literal"),value:z98.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z98.object({source:z98.literal("secret"),key:z98.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z98.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z98.object({name:z98.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z98.object({name:z98.string(),source:z98.enum(["literal","secret"]),secretKey:z98.string().nullable(),secretPrefix:z98.string().nullable(),configured:z98.literal(!0)}),WebhookFilterSchema=z98.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z98.string().min(1).max(255).optional(),mediaType:z98.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z98.string().min(1).max(255).optional(),locale:z98.string().min(1).max(120).optional()}),JsonValueSchema=z98.lazy(()=>z98.union([z98.string(),z98.number(),z98.boolean(),z98.null(),z98.array(JsonValueSchema),z98.record(z98.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z98.object({name:z98.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z98.url(),enabled:z98.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z98.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z98.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z98.object({name:z98.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z98.url().optional(),enabled:z98.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z98.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z98.boolean().optional()}),TestProjectWebhookRequestSchema=z98.object({eventType:WebhookEventTypeSchema.optional(),data:z98.record(z98.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z98.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z98.uuid(),name:z98.string(),eventType:WebhookEventTypeSchema,enabled:z98.boolean(),destination:z98.object({host:z98.string(),maskedUrl:z98.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z98.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z98.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z98.coerce.date().nullable(),deliveryStats24h:z98.object({succeeded:z98.number().int().nonnegative(),failed:z98.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z98.uuid(),projectId:z98.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z98.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z98.number().int().positive(),test:z98.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z98.number().int().nonnegative(),responseStatus:z98.number().int().nullable(),lastErrorCode:z98.string().nullable(),lastErrorMessage:z98.string().nullable(),payloadAvailable:z98.boolean(),destination:z98.object({host:z98.string(),maskedUrl:z98.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z98.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z98.string().nullable(),qstashMessageId:z98.string().nullable(),deliveredAt:z98.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z98.object({items:z98.array(WebhookDeliveryDTOSchema),pagination:z98.object({page:z98.number().int().positive(),limit:z98.number().int().positive(),total:z98.number().int().nonnegative(),totalPages:z98.number().int().positive(),hasMore:z98.boolean()}),stats:z98.object({total:z98.number().int().nonnegative(),succeeded:z98.number().int().nonnegative(),failed:z98.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z98.object({id:z98.uuid(),deliveryId:z98.uuid(),attempt:z98.number().int().positive(),status:z98.enum(["delivering","succeeded","failed"]),responseStatus:z98.number().int().nullable(),durationMs:z98.number().int().nonnegative(),responseExcerpt:z98.string().nullable(),errorCode:z98.string().nullable(),errorMessage:z98.string().nullable(),createdAt:z98.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z98.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z98.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z99}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=z99.object({key:z99.literal("fimo-2"),enabled:z99.boolean(),dismissed:z99.boolean().default(!1),interacted:z99.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z100}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,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=z100.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z100.enum(["running","done","failed"]),SiteCloneStatusSchema=z100.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z100.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z100.object({code:SiteRefusalCodeSchema,suggestedUrl:z100.string().nullable()}),SiteCheckGroupSchema=z100.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z100.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=z100.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z100.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z100.record(z100.string(),z100.union([z100.string(),z100.number(),z100.boolean(),z100.array(z100.string())])),SiteCheckResultSchema=z100.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z100.object({id:SiteCheckGroupSchema,score:z100.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z100.object({answers:z100.number().int().min(0),domains:z100.record(z100.string(),z100.number().int().min(0))}),SiteMarketSchema=z100.object({domain:z100.string(),competitors:z100.array(z100.string()),rankings:z100.array(z100.object({domain:z100.string(),averagePosition:z100.number().min(1).nullable()})),keywords:z100.array(z100.object({keyword:z100.string(),positions:z100.record(z100.string(),z100.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z100.record(z100.string(),z100.string()).optional(),fetchedAt:z100.coerce.date()}),SitePageViewSchema=z100.object({url:z100.string(),title:z100.string().nullable(),description:z100.string().nullable(),h1:z100.string().nullable(),structuredData:z100.array(z100.string()),wordCount:z100.number().int().min(0),capturedAt:z100.coerce.date()}),SiteSectionStatusSchema=z100.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z100.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z100.coerce.date().optional(),afterQueuedAt:z100.coerce.date().optional()}),SiteReportSchema=z100.object({siteUrl:z100.string(),scannedAt:z100.coerce.date(),seoScore:z100.number().int().min(0).max(100).nullable(),geoScore:z100.number().int().min(0).max(100).nullable(),groups:z100.array(SiteReportGroupSchema),checks:z100.array(SiteCheckResultSchema),blockers:z100.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z100.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z100.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z100.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z100.object({name:z100.string(),summary:z100.string(),audience:z100.string(),positioning:z100.string(),homepage:z100.string()}),SiteSuggestionSchema=z100.object({label:z100.string(),url:z100.string().nullable()}),SiteInterviewSuggestionsSchema=z100.record(z100.string(),z100.record(z100.string(),z100.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z100.record(z100.string().max(50),z100.union([z100.string().trim().max(2e3),z100.array(z100.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z100.object({status:z100.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z100.record(z100.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z100.object({questionId:z100.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z100.object({fixes:z100.array(z100.object({checkId:SiteCheckIdSchema,status:z100.enum(["fixed","not_fixed","not_applicable"]),note:z100.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z100.object({fixes:SiteFixesReportSchema.nullable(),summary:z100.string().nullable()}),StartSiteOnboardingRequestSchema=z100.object({organizationId:z100.string().min(1),url:z100.string().trim().min(1).max(2048),locale:z100.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z100.object({projectId:z100.string()})),SiteOnboardingRefusedResponseSchema=z100.object({error:z100.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z100.object({projectId:z100.string(),siteUrl:z100.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z100.boolean(),budgetExhausted:z100.boolean(),sponsored:z100.boolean(),outOfCredits:z100.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z100.string().nullable(),welcomeThreadId:z100.string().nullable(),competitors:z100.array(z100.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z100.coerce.date(),openedAt:z100.coerce.date().nullable(),bannerDismissed:z100.boolean(),completed:z100.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z100.object({task:z100.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z100.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z100.object({search:z100.string().trim().max(200).optional(),organizationId:z100.string().trim().min(1).max(200).optional(),startDate:z100.coerce.date().optional(),endDate:z100.coerce.date().optional(),outcomes:z100.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z100.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z100.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z100.array(SiteTypeSchema).optional()),page:z100.coerce.number().int().min(1).default(1),pageSize:z100.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z100.object({projectId:z100.string(),projectName:z100.string(),organizationId:z100.string(),organizationName:z100.string().nullable(),ownerEmail:z100.string().nullable(),ownerName:z100.string().nullable(),siteUrl:z100.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z100.boolean(),cloneRetries:z100.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z100.number(),interviewQuestions:z100.number().nullable(),seoScore:z100.number().nullable(),geoScore:z100.number().nullable(),spentUsd:z100.number(),budgetCapUsd:z100.number(),capReached:z100.boolean(),cloneSeconds:z100.number().nullable(),createdAt:z100.coerce.date(),openedAt:z100.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z100.object({onboardings:z100.array(AdminSiteOnboardingDTOSchema),page:z100.number(),limit:z100.number(),total:z100.number(),totalPages:z100.number()})),AdminSiteOnboardingStatsSchema=z100.object({total:z100.number(),outcomes:z100.record(SiteOnboardingOutcomeSchema,z100.number()),funnel:z100.object({started:z100.number(),confirmed:z100.number(),finished:z100.number(),opened:z100.number()}),bySiteType:z100.array(z100.object({siteType:SiteTypeSchema,total:z100.number(),finished:z100.number(),opened:z100.number()})),granularity:z100.enum(["hour","day"]),series:z100.array(z100.object({at:z100.coerce.date(),outcomes:z100.record(SiteOnboardingOutcomeSchema,z100.number())})),spentUsd:z100.object({total:z100.number(),average:z100.number().nullable()}),sponsored:z100.number(),paidByOrganization:z100.object({usd:z100.number(),credits:z100.number()}),capReached:z100.number(),cloneSeconds:z100.object({median:z100.number().nullable(),average:z100.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z100.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z100.string(),cloneThreadId:z100.string().nullable(),paidByOrganizationUsd:z100.number()}),interview:SiteInterviewSchema.extend({invocationIds:z100.array(z100.string())}).nullable(),knowledgeWritten:z100.string().nullable(),knowledgeNow:z100.object({content:z100.string(),updatedAt:z100.coerce.date().nullable(),updatedBy:z100.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z101}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=z101.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z101.object({total:z101.number(),base:z101.number(),purchases:z101.number(),awards:z101.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z101.object({id:z101.string(),name:z101.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z101.object({type:z101.string(),brand:z101.string().nullable(),last4:z101.string().nullable(),expirationDate:z101.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z101.object({currency:z101.string(),nextPaymentAmount:z101.number().nullable(),nextPaymentAt:z101.string().nullable(),billingInterval:z101.string().nullable(),totalAmount:z101.number().nullable(),discountAmount:z101.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z101.object({id:z101.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z101.string().nullable(),currentPeriodEndsAt:z101.string().nullable(),renewsAt:z101.string().nullable(),cancelAt:z101.string().nullable(),renewAutomatically:z101.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z101.object({type:z101.enum(["low_balance","critical_balance","approaching_limit"]),message:z101.string(),estimatedPromptsRemaining:z101.number().nullable(),avgCostPerPrompt:z101.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z101.object({monthlyCredits:z101.number().nullable(),usedThisPeriod:z101.number(),remainingThisPeriod:z101.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z101.object({organizationId:z101.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z101.string().nullable(),tenureDays:z101.number().int().nonnegative(),capturedAt:z101.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z101.object({hasSubscription:z101.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z101.number().nullable(),alerts:z101.array(CreditAlertDTOSchema),portalUrl:z101.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z101.object({creditCount:z101.number().int().positive(),expiresAt:z101.string().datetime().nullable().optional(),message:z101.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z101.literal("free"),amountCents:z101.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z101.literal("purchase"),amountCents:z101.number().int().positive()}),CreditTopupRequestDTOSchema=z101.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z101.object({success:z101.boolean(),transactionId:z101.string().nullable(),newBalance:z101.number(),creditCount:z101.number(),type:z101.enum(["free","purchase"]),invoiceId:z101.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z102}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=z102.object({totalCredits:z102.number(),totalCostUsd:z102.number(),totalMessages:z102.number(),avgCostPerMessage:z102.number(),periodStart:z102.string().nullable(),periodEnd:z102.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z102.object({projectId:z102.string(),projectName:z102.string(),projectDisplayName:z102.string().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z102.object({userId:z102.string(),userName:z102.string().nullable(),userEmail:z102.string().email().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z102.object({date:z102.string(),credits:z102.number(),costUsd:z102.number(),messages:z102.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z102.object({userId:z102.string(),userName:z102.string().nullable(),userEmail:z102.string().email().nullable(),credits:z102.number(),costUsd:z102.number(),messages:z102.number(),percentage:z102.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z102.object({projectId:z102.string(),projectName:z102.string(),projectDisplayName:z102.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z102.array(UsageByUserForProjectDTOSchema),timeline:z102.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z102.object({summary:UsageSummaryDTOSchema,byProject:z102.array(UsageByProjectDTOSchema),byUser:z102.array(UsageByUserDTOSchema),timeline:z102.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z103}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=z103.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z103.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z103.object({startDate:z103.string().optional(),endDate:z103.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z103.coerce.number().int().positive().default(1),limit:z103.coerce.number().int().positive().max(100).default(20),sortBy:z103.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z103.string().optional(),activeOnly:z103.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z103.object({totalCredits:z103.number(),totalCostUsd:z103.number(),totalMessages:z103.number(),automatedMessages:z103.number(),avgCostPerMessage:z103.number(),avgCreditsPerMessage:z103.number(),periodStart:z103.string(),periodEnd:z103.string(),creditsChange:z103.number().nullable(),costChange:z103.number().nullable(),messagesChange:z103.number().nullable(),unattributedCredits:z103.number(),unattributedCostUsd:z103.number(),unattributedMessages:z103.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z103.object({date:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z103.object({organizationId:z103.string(),organizationName:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),userCount:z103.number(),projectCount:z103.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z103.object({userId:z103.string(),userName:z103.string().nullable(),userEmail:z103.string().nullable(),userImage:z103.string().nullable(),organizationId:z103.string().nullable(),organizationName:z103.string().nullable(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),projectCount:z103.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z103.object({projectId:z103.string(),projectName:z103.string(),projectDisplayName:z103.string().nullable(),organizationId:z103.string(),organizationName:z103.string(),credits:z103.number(),costUsd:z103.number(),messages:z103.number(),percentage:z103.number(),userCount:z103.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z103.object({id:z103.string(),name:z103.string(),value:z103.number(),percentage:z103.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z103.object({day:z103.number(),hour:z103.number(),value:z103.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z103.object({summary:UsageOverviewSummaryDTOSchema,timeline:z103.array(UsageTimelinePointDTOSchema),topOrganizations:z103.array(OrganizationUsageRowDTOSchema),topUsers:z103.array(UserUsageRowDTOSchema),topProjects:z103.array(ProjectUsageRowDTOSchema),creditDistribution:z103.array(UsageDistributionItemDTOSchema),userDistribution:z103.array(UsageDistributionItemDTOSchema),heatmap:z103.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z103.object({page:z103.number(),limit:z103.number(),totalItems:z103.number(),totalPages:z103.number(),hasMore:z103.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z103.object({organizations:z103.array(OrganizationUsageRowDTOSchema),top:z103.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z103.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z103.object({users:z103.array(ExtendedUserUsageRowDTOSchema),top:z103.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z103.string(),ownerName:z103.string().nullable(),ownerEmail:z103.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z103.object({projects:z103.array(ExtendedProjectUsageRowDTOSchema),top:z103.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z103.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z103.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z103.object({credits:z103.number(),costUsd:z103.number(),messages:z103.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z103.object({id:z103.string(),name:z103.string(),createdAt:z103.string(),memberCount:z103.number(),projectCount:z103.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z103.object({id:z103.string(),name:z103.string().nullable(),email:z103.string(),image:z103.string().nullable(),createdAt:z103.string(),organizationCount:z103.number(),projectCount:z103.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z103.object({id:z103.string(),name:z103.string(),displayName:z103.string().nullable(),createdAt:z103.string(),organizationId:z103.string(),organizationName:z103.string(),ownerId:z103.string(),ownerName:z103.string().nullable(),ownerEmail:z103.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z103.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z104}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=z104.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z104.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z104.object({command:z104.string().min(1).max(1e4),cwd:z104.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z104.record(z104.string(),z104.string()).optional(),name:z104.string().optional(),waitForCompletion:z104.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=z104.object({identifier:z104.string(),status:SandboxProcessStatusSchema,command:z104.string().optional(),startedAt:z104.string().optional(),exitCode:z104.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z104.object({processes:z104.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z104.object({processId:z104.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z104.object({success:z104.boolean(),message:z104.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z105}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=z105.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z105.object({search:z105.string().trim().max(200).optional(),startDate:z105.coerce.date().optional(),endDate:z105.coerce.date().optional(),states:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(AdminUnclaimedStateSchema).optional()),cliVersions:z105.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z105.array(z105.string().max(64)).optional()),page:z105.coerce.number().int().min(1).default(1),pageSize:z105.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z105.object({projectId:z105.string(),displayName:z105.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z105.string().nullable(),createdAt:z105.coerce.date(),expiresAt:z105.coerce.date(),claimedAt:z105.coerce.date().nullable(),claimedOrganizationId:z105.string().nullable(),claimedOrganizationName:z105.string().nullable(),claimedByEmail:z105.string().nullable(),projectExists:z105.boolean(),previewUrl:z105.string().nullable(),hostingCostUsd:z105.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z105.object({projects:z105.array(AdminUnclaimedProjectDTOSchema),page:z105.number(),limit:z105.number(),total:z105.number(),totalPages:z105.number()})),ClaimOutcomesSchema=z105.object({total:z105.number(),claimed:z105.number(),archived:z105.number(),claimRate:z105.number().nullable(),medianTimeToClaimSeconds:z105.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z105.record(AdminUnclaimedStateSchema,z105.number()),averageTimeToClaimSeconds:z105.number().nullable(),byCliVersion:z105.array(ClaimOutcomesSchema.extend({cliVersion:z105.string().nullable()})),granularity:z105.enum(["hour","day"]),series:z105.array(z105.object({at:z105.coerce.date(),states:z105.record(AdminUnclaimedStateSchema,z105.number()),alive:z105.number(),hostingCostUsd:z105.number()})),hostingCostUsd:z105.number(),costPerProjectUsd:z105.number().nullable(),leftovers:z105.object({overdue:z105.number(),claiming:z105.number(),archivedNotDeleted:z105.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z106}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z106.enum(["internal","user-visible"]),SessionSetRetentionSchema=z106.object({additionalDays:z106.number().int().min(1).max(30)}).strict()}});import{z as z107}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=z107.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=z107.object({content:ProjectKnowledgeContentSchema,updatedAt:z107.string().nullable(),updatedBy:z107.string().nullable()}),ProjectKnowledgeUpdateSchema=z107.object({content:ProjectKnowledgeContentSchema,expectedUpdatedAt:z107.iso.datetime().nullable().optional()}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z107.object({id:z107.uuid(),status:z107.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z107.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z107.object({idempotencyKey:z107.uuid()})}});import{z as z108}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_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_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_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_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 renderMessage(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(renderMessage,"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}
@@ -41,7 +41,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
41
41
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process9.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process9.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
42
42
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path52.basename(filename,path52.extname(filename)),this}executableDir(path53){return path53===void 0?this._executableDir:(this._executableDir=path53,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text2=helper.formatHelp(this,helper);return context.hasColors?text2:this._outputConfiguration.stripColor(text2)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process9.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text2){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
43
43
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text2=="function"?helpStr=text2({error:context.error,command:context.command}):helpStr=text2,helpStr&&context.write(`${helpStr}
44
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";import path2 from"node:path";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function findProjectToken(cfg=loadConfig(),start=process.cwd()){let dir=path2.resolve(start);for(;;){let candidate=path2.join(dir,PROJECT_TOKEN_FILE);if(fs2.existsSync(candidate)){let file=JSON.parse(fs2.readFileSync(candidate,"utf-8"));return normalizeApiUrl(file.apiUrl)===normalizeApiUrl(cfg.apiUrl)?{root:dir,file}:null}let parent=path2.dirname(dir);if(parent===dir)return null;dir=parent}}function writeProjectToken(root,file){let target=path2.join(root,PROJECT_TOKEN_FILE);fs2.mkdirSync(path2.dirname(target),{recursive:!0}),ignoreLocalCredentials(path2.dirname(target)),fs2.writeFileSync(target,`${JSON.stringify(file,null,2)}
44
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";import path2 from"node:path";function ensureCredentialsDir(cfg){fs2.mkdirSync(cfg.credentialsDir,{recursive:!0,mode:448}),fs2.chmodSync(cfg.credentialsDir,448)}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.rmSync(tmpFile,{force:!0}),fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2),{mode:384}),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function findProjectToken(cfg=loadConfig(),start=process.cwd()){let dir=path2.resolve(start);for(;;){let candidate=path2.join(dir,PROJECT_TOKEN_FILE);if(fs2.existsSync(candidate)){let file=JSON.parse(fs2.readFileSync(candidate,"utf-8"));return normalizeApiUrl(file.apiUrl)===normalizeApiUrl(cfg.apiUrl)?{root:dir,file}:null}let parent=path2.dirname(dir);if(parent===dir)return null;dir=parent}}function writeProjectToken(root,file){let target=path2.join(root,PROJECT_TOKEN_FILE);fs2.mkdirSync(path2.dirname(target),{recursive:!0}),ignoreLocalCredentials(path2.dirname(target)),fs2.writeFileSync(target,`${JSON.stringify(file,null,2)}
45
45
  `,{mode:384})}function ignoreLocalCredentials(fimoDir){let ignorePath=path2.join(fimoDir,".gitignore"),current=fs2.existsSync(ignorePath)?fs2.readFileSync(ignorePath,"utf-8"):"";if(current.split(`
46
46
  `).includes(LOCAL_CREDENTIALS_RULE))return;let separator=current===""||current.endsWith(`
47
47
  `)?"":`
@@ -1228,7 +1228,7 @@ async function crawl() {
1228
1228
  if (!configFile) console.log('No .fimo/config.json (nor fimo-config.json) in this project: the public address and the languages are unknown.');
1229
1229
  else try { config = JSON.parse(fs.readFileSync(configFile, 'utf8')); } catch (e) { console.log(configFile + ' could not be read (' + e.message + '): the public address and the languages are unknown.'); }
1230
1230
  let pub = null;
1231
- try { pub = new URL(config.seo.url).origin; } catch {}
1231
+ try { pub = new URL(config.seo.url || process.env.FIMO_SITE_URL).origin; } catch {}
1232
1232
  const local = new URL(origin).host;
1233
1233
  const hosts = new Set([local, pub && new URL(pub).host]);
1234
1234
  const { started, deadline } = lock;
@@ -1605,12 +1605,13 @@ function findings(site) {
1605
1605
 
1606
1606
  const T = 'technical';
1607
1607
  if (site.robotsState === 'missing') add('robots-missing', T, 'auto', '/robots.txt', 'no robots.txt');
1608
- else if (site.robotsState === 'ok' && !site.sitemaps.length) add('robots-no-sitemap', T, 'auto', '/robots.txt', 'no Sitemap line');
1608
+ // With no address, the canonicals, the sitemap and its Sitemap line cannot exist yet: site-url-missing names that once.
1609
+ else if (site.robotsState === 'ok' && !site.sitemaps.length) { if (site.pub) add('robots-no-sitemap', T, 'auto', '/robots.txt', 'no Sitemap line'); }
1609
1610
  else for (const s of site.sitemaps) if (!/^https?:\/\//.test(s)) add('robots-sitemap-relative', T, 'auto', '/robots.txt', 'Sitemap: ' + s);
1610
- if (site.sitemapState === 'missing') add('sitemap-missing', T, 'auto', '/sitemap.xml', 'no sitemap URLs');
1611
- if (!site.pub) add('site-url-missing', T, 'suggest', '/', 'no seo.url in .fimo/config.json');
1612
- // The site is served on another host than seo.url names: one finding, not one per canonical and sitemap entry.
1613
- else if (site.served) add('site-url-mismatch', T, 'auto', '/', 'seo.url is ' + site.pub + ', the canonicals and the sitemap use ' + site.served);
1611
+ if (site.sitemapState === 'missing' && site.pub) add('sitemap-missing', T, 'auto', '/sitemap.xml', 'no sitemap URLs');
1612
+ if (!site.pub) add('site-url-missing', T, 'suggest', '/', 'no public address: not published, no primary domain, and no seo.url in .fimo/config.json');
1613
+ // The site is served on another host than its address names: one finding, not one per canonical and sitemap entry.
1614
+ else if (site.served) add('site-url-mismatch', T, 'suggest', '/', 'the site address is ' + site.pub + ', the canonicals and the sitemap use ' + site.served);
1614
1615
  const publicHosts = [site.pub && new URL(site.pub).host, site.served].filter(Boolean);
1615
1616
  for (const [path, p] of pages) {
1616
1617
  if (p.inSitemap && p.state === 'broken') add('sitemap-non-200', T, 'auto', path, 'in the sitemap, ' + say(p));
@@ -1628,7 +1629,7 @@ function findings(site) {
1628
1629
  }
1629
1630
  for (const [path, p] of live) {
1630
1631
  if (noindex(p) && p.inSitemap) add('noindex-in-sitemap', T, 'suggest', path, 'noindex but in the sitemap');
1631
- if (!p.canonical) add('canonical-missing', T, 'auto', path, 'no rel=canonical');
1632
+ if (!p.canonical) { if (site.pub) add('canonical-missing', T, 'auto', path, 'no rel=canonical'); }
1632
1633
  // The crawl's own host is a preview, unless the crawl runs on the public host: then the canonical is the page's own.
1633
1634
  else if (p.canon === null || (p.canonHost === site.local && !publicHosts.includes(p.canonHost))) {
1634
1635
  if (preview(p.canonHost)) add('canonical-preview-host', T, 'auto', path, 'canonical on a preview host: ' + p.canonical);
@@ -1861,7 +1862,7 @@ function geoFindings(site, { add, unsure, indexable, st, say, permanent, localeO
1861
1862
  }
1862
1863
 
1863
1864
  const h = site.hosted;
1864
- if (!h) unsure(A, 'hosting', 'hosting: no public address (seo.url) to read what AI crawlers get from');
1865
+ if (!h) unsure(A, 'hosting', 'hosting: no public address (seo.url or FIMO_SITE_URL) to read what AI crawlers get from');
1865
1866
  else if (h.bot.status === 0) unsure(A, 'hosting', 'hosting: ' + h.origin + ' did not answer (' + h.bot.error + '); AI crawler access was not checked');
1866
1867
  else {
1867
1868
  if (h.bot.challenge || h.bot.status < 200 || h.bot.status >= 300) unsure(A, 'hosting', 'hosting: ' + h.origin + ' answered GPTBot with ' + (h.bot.challenge ? 'a bot check' : h.bot.status) + ', so whether AI crawlers can read it is not known');
@@ -2845,7 +2846,7 @@ Remote config and local checkout are synchronized.`}__name(renderMutationResult,
2845
2846
  `)}__name(renderModelHuman,"renderModelHuman");init_dist();init_auth();init_config();init_sdk_transport();async function orgsListCommand(){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),activeId=requireAccountCredentials(cfg)?.activeOrganization?.id,{data:orgs2}=await fimo.execute("organizations.list",{});if(orgs2.length===0){ui.info({command:"orgs list",message:"No organizations found for this account."});return}ui.table({command:"orgs list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"slug",label:"SLUG"}],rows:orgs2.map(org=>({id:org.id,name:org.name,slug:org.slug})),isActive:__name(row2=>row2.id===activeId,"isActive")})}__name(orgsListCommand,"orgsListCommand");async function orgsMembersCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),creds=requireAccountCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"orgs members",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let members=await fimo.execute("organizations.members",{organizationId});if(members.length===0){ui.info({command:"orgs members",message:"No members found."});return}ui.table({command:"orgs members",columns:[{key:"role",label:"ROLE"},{key:"email",label:"EMAIL"},{key:"name",label:"NAME"}],rows:members.map(m=>({role:m.role,email:m.user?.email??"\u2014",name:m.user?.name??"\u2014"}))})}__name(orgsMembersCommand,"orgsMembersCommand");init_esm();init_dist();import fs40 from"node:fs";init_config();init_sdk_transport();init_project_context();init_project2();var PAGE_PARAM_KEYS=["schema","queryField","displayField"],ENTRY_PARAM_KEYS=new Set(["type",...PAGE_PARAM_KEYS,"query"]),LOCALE_PARAM_SEGMENT=/:(locale|lang|language)\*?(?=\/|$)/gi,MAX_EXPANDED_PAGE_INSTANCES=1e4;function configPathFor(cwd){return resolveFimoConfigPath(cwd)}__name(configPathFor,"configPathFor");function readPageRegistry(cwd,command){let file=configPathFor(cwd);fs40.existsSync(file)||(ui.error({command,code:"PAGE_REGISTRY_MISSING",message:"No fimo-config.json was found in this site."}),process.exit(1));let config;try{config=JSON.parse(fs40.readFileSync(file,"utf8"))}catch{ui.error({command,code:"CONFIG_PARSE_FAILED",message:"fimo-config.json is not valid JSON."}),process.exit(1)}return{config,routes:config.routes??{},file}}__name(readPageRegistry,"readPageRegistry");function pageStatus(route){let placeholders=pageContentParamNames(route.path??"");if(placeholders.length===0)return"static";let contentParams=pageContentParamNames(route.path??"",route.params);return contentParams.some(param=>!isEntryParamBinding(route.params?.[param]))?"dynamic:unbound":contentParams.length<placeholders.length?"dynamic:external":"dynamic:bound"}__name(pageStatus,"pageStatus");function entryFieldValue(entry,field){if(entry[field]!==void 0)return entry[field];let data=entry.data;if(data&&typeof data=="object")return data[field]}__name(entryFieldValue,"entryFieldValue");function responseRows(response){if(Array.isArray(response))return response;if(!response||typeof response!="object")return[];let data=response.data;return Array.isArray(data)?data:data&&typeof data=="object"&&Array.isArray(data.data)?data.data:[]}__name(responseRows,"responseRows");function responsePagination(response){if(!response||typeof response!="object")return null;let meta=response.meta;if(!meta||typeof meta!="object")return null;let{offset,limit,hasMore}=meta;return typeof offset=="number"&&typeof limit=="number"&&typeof hasMore=="boolean"?{offset,limit,hasMore}:null}__name(responsePagination,"responsePagination");function fieldList2(value){return typeof value=="string"?[value]:value??[]}__name(fieldList2,"fieldList");async function fetchEntries(api,projectId2,schema,query,materializationField,maxRows,onLimitExceeded){let filters={};query.where&&Object.keys(query.where).length>0&&(filters.where=JSON.stringify(query.where)),query.search&&(filters.search=query.search);for(let[key,value]of[["sort",fieldList2(query.sort)],["fields",fieldList2(query.fields)],["populate",fieldList2(query.populate)]])value.length>0&&(filters[key]=value.join(","));let rows=[],offset=query.offset??0,selectedRows=0;for(;;){let remainingQueryRows=query.limit===void 0?100:Math.min(100,query.limit-selectedRows),response=await api.listEntries(projectId2,schema,{...filters,limit:String(remainingQueryRows),offset:String(offset)}),pageRows=responseRows(response);selectedRows+=pageRows.length;let materializableRows=pageRows.filter(row2=>{let value=entryFieldValue(row2,materializationField);return value!=null&&value!==""});if(maxRows!==void 0&&rows.length+materializableRows.length>maxRows)throw onLimitExceeded?.(),new Error(`Entries for "${schema}" exceed the expansion limit.`);if(rows.push(...materializableRows),query.limit!==void 0&&selectedRows>=query.limit)return rows;let pagination=responsePagination(response);if(maxRows!==void 0&&rows.length===maxRows&&pagination?.hasMore)throw onLimitExceeded?.(),new Error(`Entries for "${schema}" exceed the expansion limit.`);if(!pagination){if(pageRows.length>=100)throw new Error(`Entries response for "${schema}" returned 100 rows without pagination metadata, so Pages cannot safely expand every entry.`);return rows}if(!pagination.hasMore)return rows;let nextOffset=pagination.offset+pagination.limit;if(nextOffset<=offset)throw new Error(`Entries pagination for "${schema}" did not advance past offset ${offset}.`);offset=nextOffset}}__name(fetchEntries,"fetchEntries");function substituteLocaleParams(routePath,locale){return locale?routePath.replace(LOCALE_PARAM_SEGMENT,()=>encodeURIComponent(locale)):routePath}__name(substituteLocaleParams,"substituteLocaleParams");function encodeRouteParam(value,catchAll){return catchAll?value.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(value)}__name(encodeRouteParam,"encodeRouteParam");function substituteRouteParam(routePath,param,value){return routePath.split("/").map(segment=>{let catchAll=segment.endsWith("*");return segment===`:${param}`||catchAll&&segment.slice(1,-1)===param?encodeRouteParam(value,catchAll):segment}).join("/")}__name(substituteRouteParam,"substituteRouteParam");function isLabelPattern(pattern){let wildcardIndex=pattern.indexOf("*");return wildcardIndex===-1||pattern.length>2&&pattern.endsWith(".*")&&wildcardIndex===pattern.length-1}__name(isLabelPattern,"isLabelPattern");function isObject(value){return!!value&&typeof value=="object"&&!Array.isArray(value)}__name(isObject,"isObject");function fail(command,code2,message){ui.error({command,code:code2,message}),process.exit(1)}__name(fail,"fail");function writePageRegistry(file,config,routes){config.routes=routes,fs40.writeFileSync(file,`${JSON.stringify(config,null,2)}
2846
2847
  `)}__name(writePageRegistry,"writePageRegistry");var COLLECTION_QUERY_KEYS=new Set(["where","search","sort","limit","offset","fields","populate"]);function stringOrStrings(value){return typeof value=="string"&&value.length>0||Array.isArray(value)&&value.length>0&&value.every(item=>typeof item=="string"&&item.length>0)}__name(stringOrStrings,"stringOrStrings");function parseCollectionQuery(raw,subject){let invalid=__name(message=>fail("pages set","PAGE_SOURCE_QUERY_INVALID",`${subject} ${message}`),"invalid");if(!isObject(raw)||Object.keys(raw).some(key=>!COLLECTION_QUERY_KEYS.has(key)))return invalid("has an invalid query.");if(raw.where!==void 0&&!isObject(raw.where))return invalid("query where must be an object.");if(raw.search!==void 0&&typeof raw.search!="string")return invalid("query search must be a string.");for(let key of["sort","fields","populate"])if(raw[key]!==void 0&&!stringOrStrings(raw[key]))return invalid(`query ${key} must be a field or field list.`);return raw.limit!==void 0&&(!Number.isInteger(raw.limit)||raw.limit<1||raw.limit>100)?invalid("query limit must be between 1 and 100."):raw.offset!==void 0&&(!Number.isInteger(raw.offset)||raw.offset<0)?invalid("query offset must be zero or greater."):raw}__name(parseCollectionQuery,"parseCollectionQuery");function parseSources(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a JSON object keyed by a stable source name.")}if(!isObject(parsed)||Object.keys(parsed).length===0)return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a non-empty JSON object. Use --clear-sources to remove them.");let sources={};for(let[name,rawSource]of Object.entries(parsed)){if(!/^[A-Za-z][\w-]*$/.test(name)||!isObject(rawSource)||typeof rawSource.type!="string")return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" needs a stable name and a valid type.`);if(rawSource.type==="labels"){if(!Array.isArray(rawSource.match)||rawSource.match.length===0||!rawSource.match.every(item=>typeof item=="string"))return fail("pages set","PAGE_SOURCE_INVALID",`Labels source "${name}" requires a non-empty match array.`);let invalidPattern=rawSource.match.find(pattern=>!isLabelPattern(pattern));if(invalidPattern)return fail("pages set","PAGE_LABEL_PATTERN_INVALID",`Label pattern "${invalidPattern}" must be an exact key or a literal prefix ending with ".*".`);sources[name]={type:"labels",match:[...new Set(rawSource.match)]};continue}if(rawSource.type==="single"){if(typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Single source "${name}" requires a schema.`);sources[name]={type:"single",schema:rawSource.schema};continue}if(rawSource.type!=="collection"||typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" must be labels, single, or collection.`);let query=rawSource.query===void 0?void 0:parseCollectionQuery(rawSource.query,`Collection source "${name}"`);sources[name]={type:"collection",schema:rawSource.schema,...query?{query}:{}}}return sources}__name(parseSources,"parseSources");function queryFields2(query){if(!query)return[];let fields=new Set;for(let field of Object.keys(query.where??{}))field.startsWith("$")||fields.add(field.split(".")[0]);for(let sort of fieldList2(query.sort))fields.add(sort.replace(/^-/,"").split(".")[0]);for(let field of[...fieldList2(query.fields),...fieldList2(query.populate)])fields.add(field.split(".")[0]);return[...fields]}__name(queryFields2,"queryFields");function entryFields(schema){return new Set([...Object.keys(schema.fields??{}),"id","slug"])}__name(entryFields,"entryFields");async function assertParamExpressions(query,subject,available,getSchema){for(let expression of pageSourceParamExpressions(query)){let parsed=parsePageParamExpression(expression);parsed||fail("pages set","PAGE_PARAM_EXPRESSION_INVALID",`Expression "${expression}" must use $params.<param>.<field>.`);let binding=Object.hasOwn(available,parsed.param)?available[parsed.param]:void 0;binding||fail("pages set","PAGE_PARAM_UNKNOWN",`${subject} references param "${parsed.param}", which this page does not bind before it.`),isEntryParamBinding(binding)||fail("pages set","PAGE_PARAM_KIND_INVALID",`${subject} references param "${parsed.param}", which is not a Collection entry param.`);let boundSchema=await getSchema(binding.schema),field=parsed.field.split(".")[0];(!boundSchema||!entryFields(boundSchema).has(field))&&fail("pages set","PAGE_PARAM_FIELD_UNKNOWN",`Field "${field}" does not exist on bound schema "${binding.schema}" (${expression}).`)}}__name(assertParamExpressions,"assertParamExpressions");function uniqueSourceName(sources,preferred){if(!sources[preferred])return preferred;let suffix=2;for(;sources[`${preferred}-${suffix}`];)suffix+=1;return`${preferred}-${suffix}`}__name(uniqueSourceName,"uniqueSourceName");function normalizedPageSources(route){let sources={...route.sources??{}},labels2=(route.content?.labels??[]).filter(isLabelPattern);labels2.length>0&&!Object.values(sources).some(source=>source.type==="labels")&&(sources[uniqueSourceName(sources,"labels")]={type:"labels",match:[...new Set(labels2)]});for(let schema of route.content?.singles??[]){if(!schema||Object.values(sources).some(source=>source.type==="single"&&source.schema===schema))continue;let preferred=`single-${schema}`;sources[uniqueSourceName(sources,preferred)]={type:"single",schema}}return sources}__name(normalizedPageSources,"normalizedPageSources");async function pagesListCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes}=readPageRegistry(cwd,"pages list"),templates=Object.entries(routes).filter(entry=>typeof entry[1]?.path=="string").map(([id,route])=>{let sources=normalizedPageSources(route);return{id,path:route.path,label:route.label??route.path,status:pageStatus(route),...route.params?{params:route.params}:{},...Object.keys(sources).length>0?{sources}:{}}});if(!options.expand){ui.result({command:"pages list",data:{pages:templates},render:__name(()=>templates.length===0?"No pages are registered yet. Add one with `fimo pages set <id> --path <path>`.":templates.map(page=>`${page.status.padEnd(15)} ${page.path} (id ${page.id})`).join(`
2847
2848
  `),"render")});return}let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let i18n=config.i18n,defaultLocale=i18n?.defaultLocale??i18n?.locales?.[0]??"en",instances=[],skipped=[];for(let page of templates){let routePath=substituteLocaleParams(page.path,defaultLocale),contentParams=pageContentParamNames(routePath);if(contentParams.length===0){instances.push({id:page.id,path:routePath});continue}if(page.status==="dynamic:external"){let external=contentParams.filter(param=>!isEntryParamBinding(page.params?.[param]));skipped.push({id:page.id,path:page.path,reason:`values for ${external.map(param=>`":${param}"`).join(", ")} are owned by the application`});continue}if(page.status!=="dynamic:bound"){skipped.push({id:page.id,path:page.path,reason:"no schema binding; bind it with `fimo pages set`"});continue}let materialized=[{path:routePath,params:{}}],failedReason;for(let param of contentParams){let binding=page.params?.[param];if(!isEntryParamBinding(binding)){failedReason=`no binding for "${param}"`;break}let expanded=[],failExpansionLimit=__name(()=>fail("pages list","PAGE_EXPANSION_LIMIT_EXCEEDED",`Page "${page.id}" expands beyond ${MAX_EXPANDED_PAGE_INSTANCES.toLocaleString()} instances. Narrow its param queries with where or limit before using --expand.`),"failExpansionLimit");for(let candidate of materialized){let resolution=resolvePageSourceQuery(binding.query,candidate.params);if(!resolution.ok)continue;let rows=await fetchEntries(content2,ctx.projectId,binding.schema,resolution.query,binding.queryField,MAX_EXPANDED_PAGE_INSTANCES-expanded.length,failExpansionLimit);for(let row2 of rows){let value=entryFieldValue(row2,binding.queryField);value==null||value===""||(expanded.length>=MAX_EXPANDED_PAGE_INSTANCES&&failExpansionLimit(),expanded.push({path:substituteRouteParam(candidate.path,param,String(value)),params:{...candidate.params,[param]:row2}}))}}if(expanded.length===0){failedReason=`no ${binding.schema} entries to materialize`;break}materialized=expanded}if(failedReason){skipped.push({id:page.id,path:page.path,reason:failedReason});continue}instances.push(...materialized.map(instance=>({id:page.id,path:instance.path,from:Object.values(page.params??{}).filter(isEntryParamBinding).map(binding=>`${binding.schema}.${binding.queryField}`).join(", ")})))}ui.result({command:"pages list",data:{pages:templates,instances,skipped},render:__name(()=>[...instances.map(instance=>`${instance.path}${instance.from?` (${instance.id} \u2190 ${instance.from})`:""}`),...skipped.map(entry=>`SKIPPED ${entry.path}: ${entry.reason}`),`${instances.length} page instance(s) from ${templates.length} template(s)`].join(`
2848
- `),"render")})}__name(pagesListCommand,"pagesListCommand");function parseParams(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(!parsed||typeof parsed!="object"||Array.isArray(parsed)||Object.keys(parsed).length===0)return null;for(let[param,value]of Object.entries(parsed)){if(!isObject(value))return null;if(value.type==="external"){if(Object.keys(value).length!==1)return null;continue}if(value.type==="locale"){if(Object.keys(value).some(key=>key!=="type"&&key!=="optional")||value.optional!==void 0&&typeof value.optional!="boolean")return null;continue}if(value.type!==void 0&&value.type!=="entry"||Object.keys(value).some(key=>!ENTRY_PARAM_KEYS.has(key)))return null;for(let key of PAGE_PARAM_KEYS)if(typeof value[key]!="string"||!value[key])return null;value.query!==void 0&&parseCollectionQuery(value.query,`Param "${param}"`)}return parsed}__name(parseParams,"parseParams");async function pagesSetCommand(id,options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages set");options.path!==void 0||options.label!==void 0||options.group!==void 0||options.sources!==void 0||options.clearSources===!0||options.icon!==void 0||options.params!==void 0||options.clearParams===!0||(ui.error({command:"pages set",code:"PAGE_SET_EMPTY",message:"Nothing to set. Pass --path, --label, --group, --sources, --clear-sources, --icon, --params, and/or --clear-params."}),process.exit(1)),options.sources!==void 0&&options.clearSources&&fail("pages set","PAGE_SOURCES_CONFLICT","Pass either --sources or --clear-sources, not both."),options.params!==void 0&&options.clearParams&&fail("pages set","PAGE_PARAMS_CONFLICT","Pass either --params or --clear-params, not both."),options.icon!==void 0&&options.icon!==""&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.icon)&&(ui.error({command:"pages set",code:"PAGE_ICON_INVALID",message:'Icons use kebab-case Lucide names, for example "newspaper". Pass an empty value to clear it.'}),process.exit(1));let existing=routes[id];!existing&&!options.path&&(ui.error({command:"pages set",code:"PAGE_NOT_FOUND",message:`No page "${id}" exists in the registry. Creating one requires --path.`}),process.exit(1)),options.path!==void 0&&(!options.path.startsWith("/")||/[[\]]/.test(options.path))&&(ui.error({command:"pages set",code:"PAGE_PATH_INVALID",message:'Page paths start with "/" and use :param syntax, never [param].'}),process.exit(1));let next={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next.sources=normalizedSources),delete next.content}if(options.path!==void 0&&(next.path=options.path),options.label!==void 0&&(options.label===""?delete next.label:next.label=options.label),options.group!==void 0&&(options.group===""?delete next.group:next.group=options.group),options.icon!==void 0&&(options.icon===""?delete next.icon:next.icon=options.icon),options.sources!==void 0&&(next.sources=parseSources(options.sources)),options.clearSources&&delete next.sources,options.params!==void 0){let params=parseParams(options.params)??void 0;params||(ui.error({command:"pages set",code:"PAGE_PARAMS_INVALID",message:'Expected {"<param>":{"schema":"<Type>","queryField":"<field>","displayField":"<field>"}} for a Collection entry, or {"<param>":{"type":"external"}} when the application owns the values.'}),process.exit(1)),next.params=params}if(options.clearParams&&delete next.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next.params){let bindableParams=new Set(pageRouteParamNames(next.path??"")),retainedParams=Object.fromEntries(Object.entries(next.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next.params=retainedParams:delete next.params}let projectContextPromise,schemas3=new Map,getSchema=__name(async schemaName=>{if(schemas3.has(schemaName))return schemas3.get(schemaName)??null;projectContextPromise??=bootstrapProjectCommand(options,cmd);let{ctx,fimo}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let schema;try{schema=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName:schemaName})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next.path??"",placeholders=pageRouteParamNames(effectivePath),contentParams=pageContentParamNames(effectivePath),effectiveParams=next.params??{};for(let[param,binding]of Object.entries(effectiveParams)){if((binding.type==="locale"?placeholders.includes(param)&&!contentParams.includes(param):contentParams.includes(param))||fail("pages set","PAGE_PARAM_UNKNOWN",binding.type==="locale"?`Param "${param}" is not the locale placeholder of the page path "${effectivePath}".`:placeholders.includes(param)?`Param "${param}" is the locale placeholder of the page path "${effectivePath}", not a content one.`:`Param "${param}" does not exist in the page path "${effectivePath}".`),!isEntryParamBinding(binding))continue;let schema=await getSchema(binding.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${binding.schema}" does not exist (param "${param}").`),schema.isSingleton!==!1&&fail("pages set","PAGE_PARAM_KIND_INVALID",`Param "${param}" needs a known Collection schema, but "${binding.schema}" is not marked as a Collection.`);let fields=entryFields(schema);for(let key of["queryField","displayField"])fields.has(binding[key])||fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${binding[key]}" does not exist on "${binding.schema}".`);if(!["id","slug"].includes(binding.queryField)){let definition=schema.fields?.[binding.queryField];(!isObject(definition)||definition.required!==!0)&&fail("pages set","PAGE_QUERY_FIELD_OPTIONAL",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "required": true.`),definition.unique!==!0&&fail("pages set","PAGE_QUERY_FIELD_NOT_UNIQUE",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "unique": true.`)}if(!binding.query)continue;let queryableFields2=new Set([...fields,"createdAt","updatedAt"]),unknownField=queryFields2(binding.query).find(field=>!queryableFields2.has(field));unknownField&&fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${unknownField}" does not exist on "${binding.schema}".`);let selectedBefore=Object.fromEntries(contentParams.slice(0,contentParams.indexOf(param)).flatMap(earlier=>effectiveParams[earlier]?[[earlier,effectiveParams[earlier]]]:[]));await assertParamExpressions(binding.query,`Param "${param}"`,selectedBefore,getSchema)}for(let[sourceName,source]of Object.entries(next.sources??{})){if(source.type==="labels")continue;let schema=await getSchema(source.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${source.schema}" does not exist (source "${sourceName}").`),source.type==="single"&&schema.isSingleton!==!0&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Single, but "${source.schema}" is not marked as a Single.`),source.type==="collection"&&schema.isSingleton!==!1&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Collection, but "${source.schema}" is not marked as a Collection.`);let query=source.type==="collection"?source.query:void 0,fields=new Set([...entryFields(schema),"createdAt","updatedAt"]),unknownSourceField=queryFields2(query).find(field=>!fields.has(field));unknownSourceField&&fail("pages set","PAGE_SOURCE_FIELD_UNKNOWN",`Field "${unknownSourceField}" does not exist on "${source.schema}" (source "${sourceName}").`),await assertParamExpressions(query,`Source "${sourceName}"`,effectiveParams,getSchema)}routes[id]=next,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next},render:__name(()=>`Page "${id}" now points to ${next.path}.`,"render")})}__name(pagesSetCommand,"pagesSetCommand");function pagesDeleteCommand(id,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages delete");routes[id]||fail("pages delete","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),delete routes[id],writePageRegistry(file,config,routes),ui.result({command:"pages delete",data:{id},render:__name(()=>`Deleted page "${id}" from the registry.`,"render")})}__name(pagesDeleteCommand,"pagesDeleteCommand");function pagesRenameCommand(id,nextId,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages rename");routes[id]||fail("pages rename","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),id!==nextId&&routes[nextId]&&fail("pages rename","PAGE_ALREADY_EXISTS",`Page "${nextId}" already exists in the registry.`);let renamed=Object.fromEntries(Object.entries(routes).map(([routeId,route])=>[routeId===id?nextId:routeId,route]));writePageRegistry(file,config,renamed),ui.result({command:"pages rename",data:{id:nextId,previousId:id},render:__name(()=>`Renamed page "${id}" to "${nextId}".`,"render")})}__name(pagesRenameCommand,"pagesRenameCommand");init_esm();init_dist();init_config();init_project_services();async function waitForHostedPreview(read,timeoutMs,sleep2=ms=>new Promise(resolve10=>setTimeout(resolve10,ms))){let deadline=Date.now()+timeoutMs,delayMs=2e3;for(;;){let preview=await read();if(preview===null)return{kind:"none"};if(preview.status==="ready")return preview.url?{kind:"ready",url:preview.url,preview}:{kind:"no-url",preview};if(preview.status==="failed")return{kind:"failed",preview};if(Date.now()+delayMs>=deadline)return{kind:"pending",preview};await sleep2(delayMs),delayMs=Math.min(Math.round(delayMs*1.5),15e3)}}__name(waitForHostedPreview,"waitForHostedPreview");init_project_context();var WAIT_TIMEOUT_MS=300*1e3,PreviewUrlError=class extends Error{constructor(failure){super(failure.message);this.failure=failure;this.name="PreviewUrlError"}static{__name(this,"PreviewUrlError")}};function noHostedPreview(branch){return isProductionBranch(branch)?{message:`Branch '${branch}' is production and has no hosted preview.`,hint:"Publish with `fimo deploy --publish` and open the live site instead."}:{message:`Branch '${branch}' has no hosted preview yet.`,hint:"Run `fimo deploy` to push a change; that is what asks for a hosted preview."}}__name(noHostedPreview,"noHostedPreview");function errorMessage4(error){return error instanceof Error?error.message:String(error)}__name(errorMessage4,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.preview.url",{projectId:ctx.projectId,branch:ctx.branch});let studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.branch);try{let sandbox=createSandboxService(loadConfig(),ctx.branch),hosted=await waitForHostedPreview(()=>sandbox.getHostedPreview(ctx.projectId,ctx.branch),WAIT_TIMEOUT_MS);if(hosted.kind==="none")throw new PreviewUrlError(noHostedPreview(ctx.branch));if(hosted.kind==="failed")throw new PreviewUrlError({message:"The hosted preview build failed.",hint:"Fix the site, then run `fimo deploy` to build the Branch again."});if(hosted.kind==="pending")throw new PreviewUrlError({message:hosted.preview.status==="queued"?"The hosted preview is still waiting to build.":"The hosted preview is still building.",hint:`Try \`fimo preview url\` again in a moment, or watch the Branch in Fimo: ${studioUrl}`});if(hosted.kind==="no-url")throw new PreviewUrlError({message:"The hosted preview is ready but did not return a URL.",hint:`Open the Branch in Fimo: ${studioUrl}`});let url=hosted.url;ui.result({command:"preview url",data:{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,preview_url:url},render:__name(context=>terminalLink("Open preview",url,context.hyperlinks),"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage4(error)}`,hint:error instanceof PreviewUrlError?error.failure.hint:`Open the Branch in Fimo while it builds: ${studioUrl}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get the hosted preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_config();init_sdk_transport();import fs41 from"node:fs";import path44 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec,notes=[]){let block2=renderBlock(entries2,spec,notes),normalized=existing.replace(/\r\n/g,`
2849
+ `),"render")})}__name(pagesListCommand,"pagesListCommand");function parseParams(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(!parsed||typeof parsed!="object"||Array.isArray(parsed)||Object.keys(parsed).length===0)return null;for(let[param,value]of Object.entries(parsed)){if(!isObject(value))return null;if(value.type==="external"){if(Object.keys(value).length!==1)return null;continue}if(value.type==="locale"){if(Object.keys(value).some(key=>key!=="type"&&key!=="optional")||value.optional!==void 0&&typeof value.optional!="boolean")return null;continue}if(value.type!==void 0&&value.type!=="entry"||Object.keys(value).some(key=>!ENTRY_PARAM_KEYS.has(key)))return null;for(let key of PAGE_PARAM_KEYS)if(typeof value[key]!="string"||!value[key])return null;value.query!==void 0&&parseCollectionQuery(value.query,`Param "${param}"`)}return parsed}__name(parseParams,"parseParams");async function pagesSetCommand(id,options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages set");options.path!==void 0||options.label!==void 0||options.group!==void 0||options.sources!==void 0||options.clearSources===!0||options.icon!==void 0||options.params!==void 0||options.clearParams===!0||(ui.error({command:"pages set",code:"PAGE_SET_EMPTY",message:"Nothing to set. Pass --path, --label, --group, --sources, --clear-sources, --icon, --params, and/or --clear-params."}),process.exit(1)),options.sources!==void 0&&options.clearSources&&fail("pages set","PAGE_SOURCES_CONFLICT","Pass either --sources or --clear-sources, not both."),options.params!==void 0&&options.clearParams&&fail("pages set","PAGE_PARAMS_CONFLICT","Pass either --params or --clear-params, not both."),options.icon!==void 0&&options.icon!==""&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.icon)&&(ui.error({command:"pages set",code:"PAGE_ICON_INVALID",message:'Icons use kebab-case Lucide names, for example "newspaper". Pass an empty value to clear it.'}),process.exit(1));let existing=routes[id];!existing&&!options.path&&(ui.error({command:"pages set",code:"PAGE_NOT_FOUND",message:`No page "${id}" exists in the registry. Creating one requires --path.`}),process.exit(1)),options.path!==void 0&&(!options.path.startsWith("/")||/[[\]]/.test(options.path))&&(ui.error({command:"pages set",code:"PAGE_PATH_INVALID",message:'Page paths start with "/" and use :param syntax, never [param].'}),process.exit(1));let next={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next.sources=normalizedSources),delete next.content}if(options.path!==void 0&&(next.path=options.path),options.label!==void 0&&(options.label===""?delete next.label:next.label=options.label),options.group!==void 0&&(options.group===""?delete next.group:next.group=options.group),options.icon!==void 0&&(options.icon===""?delete next.icon:next.icon=options.icon),options.sources!==void 0&&(next.sources=parseSources(options.sources)),options.clearSources&&delete next.sources,options.params!==void 0){let params=parseParams(options.params)??void 0;params||(ui.error({command:"pages set",code:"PAGE_PARAMS_INVALID",message:'Expected {"<param>":{"schema":"<Type>","queryField":"<field>","displayField":"<field>"}} for a Collection entry, or {"<param>":{"type":"external"}} when the application owns the values.'}),process.exit(1)),next.params=params}if(options.clearParams&&delete next.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next.params){let bindableParams=new Set(pageRouteParamNames(next.path??"")),retainedParams=Object.fromEntries(Object.entries(next.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next.params=retainedParams:delete next.params}let projectContextPromise,schemas3=new Map,getSchema=__name(async schemaName=>{if(schemas3.has(schemaName))return schemas3.get(schemaName)??null;projectContextPromise??=bootstrapProjectCommand(options,cmd);let{ctx,fimo}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let schema;try{schema=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName:schemaName})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next.path??"",placeholders=pageRouteParamNames(effectivePath),contentParams=pageContentParamNames(effectivePath),effectiveParams=next.params??{};for(let[param,binding]of Object.entries(effectiveParams)){if((binding.type==="locale"?placeholders.includes(param)&&!contentParams.includes(param):contentParams.includes(param))||fail("pages set","PAGE_PARAM_UNKNOWN",binding.type==="locale"?`Param "${param}" is not the locale placeholder of the page path "${effectivePath}".`:placeholders.includes(param)?`Param "${param}" is the locale placeholder of the page path "${effectivePath}", not a content one.`:`Param "${param}" does not exist in the page path "${effectivePath}".`),!isEntryParamBinding(binding))continue;let schema=await getSchema(binding.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${binding.schema}" does not exist (param "${param}").`),schema.isSingleton!==!1&&fail("pages set","PAGE_PARAM_KIND_INVALID",`Param "${param}" needs a known Collection schema, but "${binding.schema}" is not marked as a Collection.`);let fields=entryFields(schema);for(let key of["queryField","displayField"])fields.has(binding[key])||fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${binding[key]}" does not exist on "${binding.schema}".`);if(!["id","slug"].includes(binding.queryField)){let definition=schema.fields?.[binding.queryField];(!isObject(definition)||definition.required!==!0)&&fail("pages set","PAGE_QUERY_FIELD_OPTIONAL",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "required": true.`),definition.unique!==!0&&fail("pages set","PAGE_QUERY_FIELD_NOT_UNIQUE",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "unique": true.`)}if(!binding.query)continue;let queryableFields2=new Set([...fields,"createdAt","updatedAt"]),unknownField=queryFields2(binding.query).find(field=>!queryableFields2.has(field));unknownField&&fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${unknownField}" does not exist on "${binding.schema}".`);let selectedBefore=Object.fromEntries(contentParams.slice(0,contentParams.indexOf(param)).flatMap(earlier=>effectiveParams[earlier]?[[earlier,effectiveParams[earlier]]]:[]));await assertParamExpressions(binding.query,`Param "${param}"`,selectedBefore,getSchema)}for(let[sourceName,source]of Object.entries(next.sources??{})){if(source.type==="labels")continue;let schema=await getSchema(source.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${source.schema}" does not exist (source "${sourceName}").`),source.type==="single"&&schema.isSingleton!==!0&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Single, but "${source.schema}" is not marked as a Single.`),source.type==="collection"&&schema.isSingleton!==!1&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Collection, but "${source.schema}" is not marked as a Collection.`);let query=source.type==="collection"?source.query:void 0,fields=new Set([...entryFields(schema),"createdAt","updatedAt"]),unknownSourceField=queryFields2(query).find(field=>!fields.has(field));unknownSourceField&&fail("pages set","PAGE_SOURCE_FIELD_UNKNOWN",`Field "${unknownSourceField}" does not exist on "${source.schema}" (source "${sourceName}").`),await assertParamExpressions(query,`Source "${sourceName}"`,effectiveParams,getSchema)}routes[id]=next,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next},render:__name(()=>`Page "${id}" now points to ${next.path}.`,"render")})}__name(pagesSetCommand,"pagesSetCommand");function pagesDeleteCommand(id,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages delete");routes[id]||fail("pages delete","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),delete routes[id],writePageRegistry(file,config,routes),ui.result({command:"pages delete",data:{id},render:__name(()=>`Deleted page "${id}" from the registry.`,"render")})}__name(pagesDeleteCommand,"pagesDeleteCommand");function pagesRenameCommand(id,nextId,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages rename");routes[id]||fail("pages rename","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),id!==nextId&&routes[nextId]&&fail("pages rename","PAGE_ALREADY_EXISTS",`Page "${nextId}" already exists in the registry.`);let renamed=Object.fromEntries(Object.entries(routes).map(([routeId,route])=>[routeId===id?nextId:routeId,route]));writePageRegistry(file,config,renamed),ui.result({command:"pages rename",data:{id:nextId,previousId:id},render:__name(()=>`Renamed page "${id}" to "${nextId}".`,"render")})}__name(pagesRenameCommand,"pagesRenameCommand");init_esm();init_dist();init_config();init_project_services();async function waitForHostedPreview(read,timeoutMs,sleep2=ms=>new Promise(resolve10=>setTimeout(resolve10,ms))){let deadline=Date.now()+timeoutMs,delayMs=2e3;for(;;){let preview=await read();if(preview===null)return{kind:"none"};if(preview.status==="ready")return preview.url?{kind:"ready",url:preview.url,preview}:{kind:"no-url",preview};if(preview.status==="failed")return{kind:"failed",preview};if(Date.now()+delayMs>=deadline)return{kind:"pending",preview};await sleep2(delayMs),delayMs=Math.min(Math.round(delayMs*1.5),15e3)}}__name(waitForHostedPreview,"waitForHostedPreview");init_project_context();var WAIT_TIMEOUT_MS=300*1e3,PreviewUrlError=class extends Error{constructor(failure){super(failure.message);this.failure=failure;this.name="PreviewUrlError"}static{__name(this,"PreviewUrlError")}};function noHostedPreview(branch){return isProductionBranch(branch)?{message:`Branch '${branch}' is production and has no hosted preview.`,hint:"Publish with `fimo deploy --publish` and open the live site instead."}:{message:`Branch '${branch}' has no hosted preview yet.`,hint:"Run `fimo deploy` to push a change; that is what asks for a hosted preview."}}__name(noHostedPreview,"noHostedPreview");function errorMessage4(error){return error instanceof Error?error.message:String(error)}__name(errorMessage4,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.preview.url",{projectId:ctx.projectId,branch:ctx.branch});let studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.branch);try{let sandbox=createSandboxService(loadConfig(),ctx.branch),hosted=await waitForHostedPreview(()=>sandbox.getHostedPreview(ctx.projectId,ctx.branch),WAIT_TIMEOUT_MS);if(hosted.kind==="none")throw new PreviewUrlError(noHostedPreview(ctx.branch));if(hosted.kind==="failed")throw new PreviewUrlError({message:"The hosted preview build failed.",hint:"Fix the site, then run `fimo deploy` to build the Branch again."});if(hosted.kind==="pending")throw new PreviewUrlError({message:hosted.preview.status==="queued"?"The hosted preview is still waiting to build.":"The hosted preview is still building.",hint:`Try \`fimo preview url --branch ${ctx.branch}\` again in a moment, or watch the Branch in Fimo: ${studioUrl}`});if(hosted.kind==="no-url")throw new PreviewUrlError({message:"The hosted preview is ready but did not return a URL.",hint:`Open the Branch in Fimo: ${studioUrl}`});let url=hosted.url;ui.result({command:"preview url",data:{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,preview_url:url},render:__name(context=>terminalLink("Open preview",url,context.hyperlinks),"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage4(error)}`,hint:error instanceof PreviewUrlError?error.failure.hint:`Open the Branch in Fimo while it builds: ${studioUrl}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get the hosted preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_config();init_sdk_transport();import fs41 from"node:fs";import path44 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec,notes=[]){let block2=renderBlock(entries2,spec,notes),normalized=existing.replace(/\r\n/g,`
2849
2850
  `),lines=normalized.endsWith(`
2850
2851
  `)?normalized.slice(0,-1).split(`
2851
2852
  `):normalized.split(`