fimo 2.8.0-staging.16 → 2.8.0-staging.18
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/assets/skills/fimo-studio/SKILL.md +0 -1
- package/assets/skills/fimo-studio/references/ai-chat.md +2 -3
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +3 -3
- package/package.json +8 -8
- package/templates/astro/package.json +3 -3
- package/templates/nextjs/package.json +4 -4
- package/templates/react-router/package.json +5 -5
- package/templates/sveltekit/package.json +3 -3
- package/templates/vite/package.json +5 -5
- package/assets/skills/fimo-studio/references/drawing-and-wireframing.md +0 -61
package/dist/cli/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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:(a,b)=>(typeof require<"u"?require:a)[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","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 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 h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function 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(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${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,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_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"],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,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,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_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_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_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_agent_branch_discard","admin_resource_read","merge_force"],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";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_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,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_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z12.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"],OpsPermissionSchema=z12.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:organization:features:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops: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"],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=z12.object({permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),enabled:z12.boolean().default(!0)}),OpsServiceTokenInputSchema=z12.object({name:z12.string().trim().min(1).max(120),permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),expiresAt:z12.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=z12.object({importanceReason:z12.string().trim().min(1).max(1e3),ownerUserId:z12.string().trim().min(1).nullable().optional(),framework:z12.string().trim().max(120).nullable().optional(),packageManager:z12.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z12.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z12.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z12.object({projectId:z12.uuid(),title:z12.string().trim().min(1).max(240),userReport:z12.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z12.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z12.string().trim().max(1e4).nullable().optional(),outcome:z12.string().trim().max(1e4).nullable().optional(),evidence:z12.array(z12.record(z12.string(),z12.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=z12.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z12.object({fingerprint:z12.string().trim().min(1).max(240),title:z12.string().trim().min(1).max(240),description:z12.string().trim().min(1).max(1e4),affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z12.array(z12.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z12.string().trim().min(1).max(64).nullable().optional(),workaround:z12.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100),detectionQueries:z12.array(z12.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=z12.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z12.object({changeReference:z12.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z12.string().trim().min(1).max(1e4),evidence:z12.array(z12.record(z12.string(),z12.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z12.object({recipientEmail:z12.email().optional(),subject:z12.string().trim().min(1).max(200).default("An update from Fimo"),message:z12.string().trim().min(1).max(5e3),locale:z12.string().trim().min(2).max(20),reason:z12.string().trim().min(1).max(1e3),acknowledgePolicy:z12.literal(!0)}),OpsPylonIssueIdSchema=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z12.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z12.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z12.string().trim().min(1).max(255),OpsPylonEmailListSchema=z12.array(z12.email()).max(50).default([]),OpsPylonResolveInputSchema=z12.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z12.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z12.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z12.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=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z12.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z12.object({projectId:z12.uuid(),from:z12.coerce.date(),to:z12.coerce.date(),reason:z12.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=z12.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z12.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z12.object({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),agentKey:z12.string().trim().min(1).max(120).optional(),threadId:z12.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z12.coerce.date().optional(),minCostUsd:z12.coerce.number().min(0).optional(),tracedOnly:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z12.object({limit:z12.coerce.number().int().min(1).max(500).default(200),reason:z12.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z12.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z12.object({maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z12.object({messageIndex:z12.coerce.number().int().min(0).optional(),maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),reason:z12.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z12.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z12.strictObject({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z12.string().trim().min(1).max(120).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z12.strictObject({organizationId:z12.string().trim().min(1).max(255).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.object({projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),reason:z12.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"}),opsChatHistoryWindow={projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),reason:z12.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z12.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,limit:z12.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,sample:z12.coerce.number().int().min(1).max(25).default(10)})),OpsChatHistoryJudgeCalibrationInputSchema=z12.strictObject({reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z12.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z12.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z12.object({since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z12.coerce.number().min(0).optional(),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.object({since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),model:z12.string().trim().min(1).max(120).optional(),provider:z12.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z12.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z12.boolean().default(!1),correlationLimit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.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=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z12.object({reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1),cursor:z12.string().min(1).optional(),batchSize:z12.number().int().min(1).max(100).default(50),concurrency:z12.number().int().min(1).max(10).default(2)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z12.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z12.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z12.discriminatedUnion("kind",[z12.object({kind:z12.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z12.object({kind:z12.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z12.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z12.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z12.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z12.object({migrationId:OpsMigrationIdSchema,projectEnv:z12.string().trim().min(1).max(255).default("main"),reason:z12.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z12.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z12.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z12.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z12.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z12.object({pattern:z12.string().min(1).max(300).optional(),limit:z12.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z12.object({pattern:z12.string().min(1).max(200),include:z12.string().min(1).max(300).optional(),caseInsensitive:z12.boolean().default(!1),maxMatches:z12.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z12.object({path:OpsProjectFilePathSchema,content:z12.string().max(256*1024),overwrite:z12.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z12.string().trim().length(64),consentReference:z12.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z12.intersection(OpsProjectOperationPlanInputSchema,z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z12.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=z12.strictObject({projectId:z12.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z12.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=z12.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=z12.strictObject({completeAggregate:z12.boolean(),truncated:z12.boolean().nullable(),sampled:z12.boolean().nullable(),pagination:z12.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z12.literal(!1),providerAsOf:z12.null(),projectFilter:z12.literal("exact properties.projectId equality"),environmentFilterSupported:z12.literal(!1),excludesMissingProjectId:z12.literal(!0),transport:z12.literal("server"),consentCoverage:z12.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z12.literal(!1)}),OpsPosthogCountsSchema=z12.array(z12.strictObject({event:z12.enum(OPS_POSTHOG_EVENTS),captureCount:z12.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z12.strictObject({schemaVersion:z12.literal(1),questionId:z12.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z12.uuid().nullable(),projectEnvironment:z12.literal("mixed_or_unrecorded"),window:z12.strictObject({from:z12.iso.datetime(),to:z12.iso.datetime(),bounds:z12.literal("[from,to)")}).nullable(),source:z12.literal("posthog"),sourceStatus:z12.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z12.iso.datetime(),auditId:z12.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=z12.object({reason:z12.string().trim().min(1).max(1e3),limit:z12.number().int().min(1).max(100).default(25),checkProvider:z12.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z12.object({branch:z12.string().trim().min(1).max(255),canaryPath:z12.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:z12.iso.datetime({offset:!0}),until:z12.iso.datetime({offset:!0}),reason:z12.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 z13}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z13.object({kind:z13.literal("say"),label:z13.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z13.string().min(1).max(240).optional(),message:z13.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z13.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z13.discriminatedUnion("command",[z13.object({kind:z13.literal("app"),command:z13.literal("publish")}).strict(),z13.object({kind:z13.literal("app"),command:z13.literal("connect"),integrationKey:z13.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z13.object({fallback:z13.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z13.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z13.literal("choices"),text:z13.string().max(500).optional(),actions:z13.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("entry"),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("asset"),assetId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("url"),url:z13.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z13.literal("table"),columns:z13.array(z13.object({label:z13.string().min(1).max(24)})).min(2).max(4),rows:z13.array(z13.object({cells:z13.array(z13.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:z13.literal("cards"),layout:z13.enum(["rail","stack"]).optional(),items:z13.array(z13.object({title:z13.string().min(1).max(60),subtitle:z13.string().min(1).max(120).optional(),imageUrl:z13.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z13.literal("entry"),label:z13.string().min(1).max(80),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120),path:z13.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z13.literal("assets"),items:z13.array(z13.object({url:z13.url({protocol:/^https$/}).max(2e3),alt:z13.string().min(1).max(120),label:z13.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z13.literal("callout"),title:z13.string().min(1).max(80),text:z13.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z13.literal("stat"),items:z13.array(z13.object({label:z13.string().min(1).max(24),value:z13.string().min(1).max(16),delta:z13.string().min(1).max(12).optional(),tone:z13.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z13.literal("chart"),unit:z13.string().min(1).max(12).optional(),points:z13.array(z13.object({label:z13.string().min(1).max(12),value:z13.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z13.literal("text"),placeholder:z13.string().min(1).max(120).optional(),multiline:z13.boolean().optional()}).strict(),ChatFormStepIdSchema=z13.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z13.object({id:ChatFormStepIdSchema,token:z13.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z13.string().trim().min(1).max(60),reason:z13.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z13.literal("capabilities"),items:z13.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z13.object({id:ChatFormStepIdSchema.optional(),question:z13.string().min(1).max(500),header:z13.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z13.boolean().optional(),recommended:z13.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"})),FormBlockSchema=BlockBaseSchema.extend({type:z13.literal("form"),steps:z13.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z13.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z13.object({stepId:ChatFormStepIdSchema.optional(),header:z13.string().min(1).max(25),question:z13.string().min(1).max(500),answer:z13.string().min(1),selectedLabels:z13.array(z13.string().min(1).max(120)).max(8),freeText:z13.string(),skipped:z13.boolean()}),ChatFormAnswerMetadataSchema=z13.object({toolCallId:z13.string().max(255).optional(),shortTitle:z13.string().max(80).optional(),questions:z13.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z13.string().min(1).max(255),partial:z13.boolean().optional()})}});import{z as z14}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=z14.object({shape:z14.enum(CHAT_PORTRAIT_SHAPES),eyes:z14.enum(CHAT_PORTRAIT_EYES),mouth:z14.enum(CHAT_PORTRAIT_MOUTHS),color:z14.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z15}from"zod";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}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(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
|
|
5
|
-
`)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.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=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z15.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z15.object({type:z15.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.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=z15.object({type:z15.literal("list"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema.optional(),label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("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=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z15.object({type:z15.literal("media"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z15.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z15.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49,params){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param)&¶ms?.[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 z17}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","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=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z17.object({name:z17.string().optional(),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z17.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z17.object({code:z17.literal("PUBLISH_UPGRADE_REQUIRED"),message:z17.string(),currentVersion:z17.number().int().positive(),targetVersion:z17.literal(4)}),ProjectLatestPublicationAttemptSchema=z17.object({publicationId:z17.uuid(),status:z17.enum(["queued","building","published","failed","canceled"]),failureCode:z17.string().nullable(),sourceBranch:z17.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z17.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional(),url:z17.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}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=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z18.object({sessionId:z18.uuid(),name:z18.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.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=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.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=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:BranchSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}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=z23.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative(),assets:z23.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200),assets:z23.array(z23.object({key:z23.string().min(1).max(512),name:z23.string().min(1).max(512),verb:z23.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z24}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=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z24.object({sessionId:z24.uuid(),branch:z24.string().min(1),targetBranch:z24.string().min(1),revision:z24.string().min(1),fingerprint:z24.string().min(1),source:z24.enum(["studio","slack","mcp"]),threadId:z24.uuid().nullable(),invocationId:z24.uuid().nullable(),conversationBranch:z24.string().nullable(),capturedAt:z24.string(),surfaces:z24.array(PerSurfaceDeltaSchema).optional(),counts:z24.record(z24.string(),z24.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z24.strictObject({sessionId:z24.uuid(),summary:z24.string().trim().min(1).max(240),targetBranch:z24.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z24.object({requested:z24.literal(!0),alreadyRequested:z24.boolean(),reviewId:z24.uuid(),reviewUrl:z24.url(),status:z24.literal("pending"),sessionId:z24.uuid(),branch:z24.string(),targetBranch:z24.string(),revision:z24.string(),savedRevision:z24.string(),fingerprint:z24.string(),visibility:z24.literal("user-visible"),retention:z24.literal("durable"),expiresAt:z24.null(),merged:z24.literal(!1),published:z24.literal(!1),links:z24.object({preview:z24.url(),changes:z24.url(),conversation:z24.url().nullable()})}),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}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=z25.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z25.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=z25.object({description:z25.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z25.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z25.array(z25.uuid()).optional()}),AgentQuestionSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),threadId:z25.uuid(),invocationId:z25.uuid(),agentKey:z25.string().min(1).max(120),anchorEnv:z25.string().min(1).max(64),retainedEnv:z25.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z25.string().min(1).nullable(),continuationInvocationId:z25.uuid().nullable(),askedAt:z25.coerce.date(),expiresAt:z25.coerce.date(),closedAt:z25.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z25.object({questionId:z25.uuid(),invocationId:z25.uuid(),askedAt:z25.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z25.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z25.object({question:AgentQuestionSchema,continuationInvocationId:z25.uuid(),deduped:z25.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z26}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=z26.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z26.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z26.enum(["secret_text"]),IntegrationCredentialUsageSchema=z26.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z26.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z26.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z26.object({mode:IntegrationAuthModeSchema,label:z26.string().min(1),description:z26.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z26.object({id:z26.string().min(1),label:z26.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z26.boolean()}),IntegrationToolDefinitionDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),description:z26.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z26.object({title:z26.string().min(1),description:z26.string().min(1),command:z26.string().min(1).optional()}),IntegrationInfoDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),type:z26.enum(["native","mcp"]).optional(),url:z26.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z26.array(IntegrationAuthModeDTOSchema),credentials:z26.array(IntegrationCredentialDefinitionDTOSchema),tools:z26.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z26.enum(["available","unavailable"]).optional(),connectionCapabilities:z26.object({customIdentityCreation:z26.boolean()}).optional(),recipes:z26.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),installed:z26.boolean(),enabled:z26.boolean(),setupState:z26.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z26.string().nullable(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),connectionStatus:z26.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),installedAt:z26.coerce.date().nullable(),updatedAt:z26.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),enabled:z26.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z26.string(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z26.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z26.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z26.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z26.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z26.object({id:z26.uuid(),organizationId:z26.string().min(1),integrationKey:z26.string().min(1),registrationId:z26.uuid().nullable(),alias:z26.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z26.string().min(1),externalAccountName:z26.string().nullable(),externalBotUserId:z26.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z26.array(z26.string()),connectedAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z26.boolean(),isDefault:z26.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z26.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z26.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z26.record(McpHeaderNameSchema,z26.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z26.object({alias:z26.string().min(1).max(120).optional(),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.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=z26.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z26.object({displayName:z26.string().trim().min(1).max(35),backgroundColor:z26.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z26.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),alias:z26.string().min(1).max(120),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}),z26.object({mode:z26.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z26.boolean().optional(),registrationId:z26.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=z26.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z26.union([z26.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z26.object({type:z26.literal("mcp"),name:z26.string().trim().min(1).max(120),url:z26.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z26.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z26.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z26.object({integrationKey:z26.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z26.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("oauth"),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),ReusableMcpServerAuthKindSchema=z26.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z26.object({id:z26.uuid(),name:z26.string().min(1),host:z26.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z26.string().min(1),availability:z26.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z26.object({query:z26.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z26.object({serverId:z26.uuid()}),LinearOAuthApplicationDistributionSchema=z26.enum(["private","public"]),OrganizationLinearAppDTOSchema=z26.object({id:z26.uuid(),displayName:z26.string().min(1),description:z26.string().nullable(),iconUrl:z26.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z26.enum(["active","revoked"]),connectionIds:z26.array(z26.uuid()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z26.object({appName:z26.string().trim().min(2).max(80),description:z26.string().trim().max(1e3).optional(),iconUrl:z26.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z26.object({projectId:z26.uuid(),registrationId:z26.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z26.object({integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),integrationKey:z26.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z26.object({mode:z26.literal("oauth"),integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),BindProjectChannelRequestSchema=z26.object({ref:z26.string().min(1),connectionAlias:z26.string().min(1).optional(),agentName:z26.string().min(1).max(160).nullable().optional(),force:z26.boolean().optional()}),ListProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1)}),SearchProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1),connectionAlias:z26.string().min(1),query:z26.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),connectionId:z26.uuid(),externalWorkspaceId:z26.string().min(1),externalChannelId:z26.string().min(1),externalChannelName:z26.string().nullable(),agentName:z26.string().nullable(),enabled:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z26.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z26.object({id:z26.string().min(1),name:z26.string().min(1),visibility:z26.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z26.string().min(1).nullable(),canMove:z26.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z26.object({markdown:z26.boolean().optional(),summary:z26.boolean().optional(),links:z26.boolean().optional(),branding:z26.boolean().optional(),images:z26.boolean().optional(),html:z26.union([z26.literal("cleaned"),z26.literal("raw"),z26.boolean()]).optional(),json:z26.union([z26.boolean(),z26.object({prompt:z26.string().min(1).max(1e4),schema:z26.record(z26.string(),z26.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z26.object({url:z26.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z26.object({query:z26.string().min(1),maxResults:z26.number().int().positive().max(20).optional(),sources:z26.array(z26.enum(["web","news","images"])).min(1).max(3).optional(),categories:z26.array(z26.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z26.enum(["hour","day","week","month","year"]).optional(),location:z26.string().min(1).max(160).optional(),country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(100).optional(),types:z26.array(z26.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),sources:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),passages:z26.number().int().min(1).max(5).optional(),skills:z26.literal("only").optional(),language:z26.string().min(1).optional(),topic:z26.string().min(1).optional(),license:z26.string().min(1).optional(),minStars:z26.number().int().min(0).optional(),maxStars:z26.number().int().min(0).optional(),archived:z26.boolean().optional(),fork:z26.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(500).optional(),authors:z26.array(z26.string().min(1)).min(1).optional(),categories:z26.array(z26.string().min(1)).min(1).optional(),from:z26.iso.date().optional(),to:z26.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),query:z26.string().min(1).max(500).optional(),maxPassages:z26.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),intent:z26.string().min(1).max(500),mode:z26.enum(["similar","citers","references"]).optional(),maxResults:z26.number().int().min(1).max(500).optional(),rerank:z26.boolean().optional(),anchors:z26.array(z26.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z26.object({url:z26.string().url(),search:z26.string().min(1).optional(),limit:z26.number().int().positive().max(200).optional(),includeSubdomains:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z26.object({url:z26.string().url(),limit:z26.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z26.object({text:z26.string().min(1).max(200).optional(),cron:z26.string().min(1).max(120).optional(),timezone:z26.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z26.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z26.union([z26.object({type:z26.enum(["scrape","crawl"]).default("scrape"),urls:z26.array(z26.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z26.object({type:z26.literal("search"),queries:z26.array(z26.string().min(1).max(256)).min(1).max(12),searchWindow:z26.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z26.number().int().min(1).max(50).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z26.object({name:z26.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),notification:z26.object({email:z26.object({enabled:z26.boolean().default(!0),recipients:z26.array(z26.string().email()).min(1).max(20),includeDiffs:z26.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=z26.object({monitorId:z26.string().uuid(),name:z26.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),status:z26.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z26.object({monitorId:z26.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z26.string().uuid()}),RunProjectIntegrationToolRequestSchema=z26.object({tool:z26.string().min(1),input:z26.record(z26.string(),z26.unknown()),connectionAlias:z26.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z26.object({provider:z26.string().min(1),providerCredits:z26.number().nonnegative().optional(),providerCostUsd:z26.number().nonnegative().optional(),requests:z26.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z26.object({credits:z26.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),json:z26.unknown().optional(),branding:z26.record(z26.string(),z26.unknown()).optional(),warning:z26.string().optional()}),FirecrawlSearchToolOutputSchema=z26.object({query:z26.string(),provider:z26.literal("firecrawl"),warning:z26.string().optional(),results:z26.array(z26.object({title:z26.string(),url:z26.string(),snippet:z26.string().optional(),content:z26.string().optional(),score:z26.number().optional(),publishedAt:z26.string().optional()}))}),FirecrawlResearchPaperSchema=z26.object({paperId:z26.string(),primaryId:z26.string().optional(),ids:z26.record(z26.string(),z26.array(z26.string())).optional(),title:z26.string().optional(),abstract:z26.string().optional(),score:z26.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z26.object({text:z26.string(),score:z26.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(z26.object({id:z26.string(),type:z26.string().min(1).optional(),url:z26.string(),title:z26.string().optional(),passages:z26.array(z26.object({text:z26.string()}).passthrough())}).passthrough()),coverage:z26.record(z26.string(),z26.string()).optional(),reranked:z26.boolean().optional(),repos:z26.array(z26.record(z26.string(),z26.unknown())).optional(),sources:z26.array(z26.record(z26.string(),z26.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),paper:z26.record(z26.string(),z26.unknown()),paperId:z26.string().optional(),query:z26.string().optional(),passages:z26.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema),poolSize:z26.number().int().nonnegative(),truncated:z26.boolean(),note:z26.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),count:z26.number(),links:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),description:z26.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),total:z26.number(),pages:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),warning:z26.string().optional()})),warning:z26.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z26.object({cron:z26.string().optional(),text:z26.string().optional(),timezone:z26.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z26.object({id:z26.string().optional(),type:z26.enum(["scrape","crawl","search"]).optional(),urls:z26.array(z26.string()).optional(),queries:z26.array(z26.string()).optional(),searchWindow:z26.string().optional(),maxResults:z26.number().optional(),includeDomains:z26.array(z26.string()).optional(),excludeDomains:z26.array(z26.string()).optional(),scrapeOptions:z26.record(z26.string(),z26.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z26.object({id:z26.string(),name:z26.string(),status:z26.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z26.string().nullable().optional(),lastRunAt:z26.string().nullable().optional(),currentCheckId:z26.string().nullable().optional(),targets:z26.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z26.string().nullable().optional(),judgeEnabled:z26.boolean().optional(),estimatedCreditsPerMonth:z26.number().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z26.object({id:z26.string(),monitorId:z26.string(),scheduledFor:z26.string().nullable().optional(),startedAt:z26.string().nullable().optional(),finishedAt:z26.string().nullable().optional(),estimatedCredits:z26.number().nullable().optional(),reservedCredits:z26.number().nullable().optional(),actualCredits:z26.number().nullable().optional(),billingStatus:z26.string().nullable().optional(),summary:z26.object({totalPages:z26.number().optional(),same:z26.number().optional(),changed:z26.number().optional(),new:z26.number().optional(),removed:z26.number().optional(),error:z26.number().optional()}).passthrough().optional(),error:z26.string().nullable().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitors:z26.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),deleted:z26.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),checks:z26.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),check:FirecrawlMonitorCheckOutputSchema,next:z26.string().optional()}),FirecrawlToolKeySchema=z26.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=z26.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),tool:z26.string().min(1),connectionAlias:z26.string().min(1).nullable().optional(),output:z26.record(z26.string(),z26.unknown()),executedAt:z26.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z26.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z26.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z26.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z26.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z26.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z26.array(ProjectChannelCandidateDTOSchema))}});import{z as z27}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=z27.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z27.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z27.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z27.object({userId:z27.string().min(1),name:z27.string(),email:z27.string().min(1),subscribed:z27.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z27.object({maxSubscribers:z27.number().int().positive(),subscriberCount:z27.number().int().nonnegative(),effectiveRecipientCount:z27.number().int().nonnegative(),currentUserSubscribed:z27.boolean(),candidates:z27.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z27.object({userIds:z27.array(z27.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z27.object({topic:UserManagedNotificationTopicSchema,enabled:z27.boolean(),source:z27.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z27.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z27.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z27.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z27.string().nullable(),maskedEmail:z27.string().min(1),applied:z27.boolean(),expiresAt:z27.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z27.object({scheduleId:z27.string().min(1),scheduleName:z27.string(),projectId:z27.string().min(1),projectName:z27.string(),env:z27.string().min(1)}),FollowedSchedulesSchema=z27.object({schedules:z27.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z28}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=z28.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=z28.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z28.uuid(),env:z28.string().min(1),name:z28.string().min(1),cron:z28.string().min(1),command:z28.string().min(1),secretKeys:z28.array(z28.string().min(1)),enabled:z28.boolean(),lastRunAt:z28.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z28.string().nullable(),suspendedAt:z28.coerce.date().nullable().optional(),suspensionReason:z28.string().nullable().optional(),overPolicyReasons:z28.array(z28.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120),cron:z28.string().min(1).max(120),command:z28.string().min(1).max(500),secretKeys:z28.array(ProjectSecretKeySchema).default([]),enabled:z28.boolean().optional()}),UpdateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120).optional(),cron:z28.string().min(1).max(120).optional(),command:z28.string().min(1).max(500).optional(),secretKeys:z28.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z28.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z28.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z28.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z28.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z28.object({maxRuns:z28.number().int().positive(),retentionDays:z28.number().int().positive().nullable(),outputRetentionDays:z28.number().int().positive(),maxOutputBytes:z28.number().int().positive()}),SchedulePolicyStateSchema=z28.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z28.object({code:z28.enum(["Free","PAYG","Premium","Pro"]),source:z28.enum(["cached_subscription","free_fallback"]),activeSchedules:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().nonnegative()}),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),concurrency:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().positive()}),compute:z28.object({settledMs:z28.number().int().nonnegative(),activeMs:z28.number().int().nonnegative(),reservedMs:z28.number().int().nonnegative().optional(),includedMs:z28.number().int().nonnegative(),remainingMs:z28.number().int().nonnegative(),resetsAt:z28.coerce.date()}),upgrade:z28.object({code:z28.literal("Pro"),activeSchedulesLimit:z28.number().int().positive(),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),maxConcurrentRuns:z28.number().int().positive(),computeIncludedMs:z28.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z28.array(z28.string())}),ProjectScheduleUsageSchema=z28.object({runCount:z28.number().int().nonnegative(),runsWithOutput:z28.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z28.object({id:z28.uuid(),scheduleId:z28.uuid(),projectId:z28.uuid(),env:z28.string().min(1),scheduleName:z28.string().min(1),command:z28.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z28.object({id:z28.string().min(1),name:z28.string().min(1)}).nullable(),queuedAt:z28.coerce.date(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),exitCode:z28.number().int().nullable(),errorCode:z28.string().nullable(),error:z28.string().nullable(),outputBytes:z28.number().int().nonnegative(),outputTruncated:z28.boolean(),outputExpiresAt:z28.coerce.date().nullable(),metadataExpiresAt:z28.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z28.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z28.coerce.date().nullable(),items:z28.array(z28.object({key:z28.string().min(1),updatedAt:z28.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z28.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z28.object({trigger:z28.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z28.object({limit:z28.coerce.number().int().min(1).max(100).default(25),cursor:z28.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z28.object({items:z28.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z28.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z28.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z28.object({items:z28.array(ProjectScheduleRunDTOSchema),nextCursor:z28.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z29}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=z29.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z29.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z29.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z29.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z29.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z29.discriminatedUnion("kind",[z29.object({kind:z29.literal("user"),userId:z29.string().min(1)}).strict(),z29.object({kind:z29.literal("agent"),agentKey:z29.string().min(1).max(120),agentId:z29.uuid().optional()}).strict(),z29.object({kind:z29.literal("system")}).strict()]),NotificationSummarySchema=z29.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z29.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z29.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z29.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z29.object({sessionId:z29.uuid(),branch:z29.string().min(1),targetBranch:z29.string().min(1),revision:z29.string().min(1),fingerprint:z29.string().min(1)}),NotificationPayloadSchema=z29.discriminatedUnion("topic",[z29.object({topic:z29.literal("agent_run_outcome"),threadId:z29.uuid(),invocationId:z29.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_retained_review"),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),proposalId:z29.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_conflict"),mergeId:z29.uuid(),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("publication_failed"),publicationId:z29.uuid(),sourceBranch:z29.string().trim().min(1).max(120),failureCode:z29.string().trim().min(1).max(64),failedAt:z29.iso.datetime(),firstPublication:z29.boolean()}).strict()]),NotificationEnvelopeSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),sourceKey:z29.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z29.literal(1),payload:NotificationPayloadSchema,createdAt:z29.coerce.date()}),NotificationDeliveryStateSchema=z29.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z29.object({id:z29.uuid(),notificationRecipientId:z29.uuid(),projectId:z29.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z29.number().int().nonnegative(),nextAttemptAt:z29.coerce.date().nullable(),lastAttemptAt:z29.coerce.date().nullable(),sentAt:z29.coerce.date().nullable(),failureCode:z29.string().max(80).nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),NotificationPreferenceSchema=z29.object({topic:WorkNotificationTopicSchema,channel:z29.literal("email"),enabled:z29.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z29.enum(["default","explicit"])})}});import{z as z30}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=z30.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance"],FimoTogglePreferenceEntryIdSchema=z30.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z30.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z30.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z30.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z30.object({enabled:z30.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z30.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z30.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z30.enum(["work_review","publishing","schedule"]),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z30.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),id:z30.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z30.literal("marketing"),name:z30.string(),description:z30.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z30.object({email:EmailNotificationPreferenceSchema,entries:z30.array(NotificationPreferenceEntrySchema),unavailableGroups:z30.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),enabled:z30.boolean()}).strict(),z30.object({kind:z30.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),enabled:z30.boolean()}).strict()])}});import{z as z31}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=z31.object({surface:SurfaceNameSchema,key:z31.string(),label:z31.string()}),InlineSchema=z31.object({text:z31.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z31.discriminatedUnion("type",[z31.object({type:z31.literal("paragraph"),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("preview"),ref:DiffRefSchema,caption:z31.string().optional()}),z31.object({type:z31.literal("code"),code:z31.string(),lang:z31.string().optional(),caption:z31.string().optional()}),z31.object({type:z31.literal("risk"),level:z31.enum(["warning","error"]),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("list"),items:z31.array(z31.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z31.object({headline:z31.string(),blocks:z31.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z31.object({summary:EnvDiffSummarySchema,fingerprint:z31.string(),generatedAt:z31.coerce.date(),cached:z31.boolean().optional(),credits:z31.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z32}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=z32.object({date:z32.string(),visitors:z32.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z32.object({key:z32.string(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z32.object({path:z32.string(),pageName:z32.string().nullable().optional(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z32.object({preset:z32.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z32.string(),requestedTo:z32.string(),effectiveFrom:z32.string(),effectiveTo:z32.string(),isRetentionLimited:z32.boolean(),groupBy:z32.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z32.object({date:z32.string(),content:z32.string(),updatedAt:z32.string(),updatedByUserId:z32.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z32.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z32.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative(),botPageviews:z32.number().int().nonnegative(),botVisitors:z32.number().int().nonnegative(),bounceRate:z32.number().min(0).max(100),viewsPerVisit:z32.number().nonnegative(),averageVisitDurationSeconds:z32.number().nonnegative(),visitorsSeries:z32.array(ProjectDailyVisitorsDTOSchema),topPages:z32.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z32.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z32.object({state:z32.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z32.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z33}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=z33.object({id:z33.string(),email:z33.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z33.coerce.date(),createdAt:z33.coerce.date(),inviterUserId:z33.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z33.object({id:z33.string(),token:z33.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z33.object({success:z33.boolean(),projectId:z33.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z34}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=z34.object({id:z34.string(),name:z34.string(),image:z34.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z34.object({count:z34.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z34.object({counts:z34.object({signed_up:z34.int(),activated:z34.int()}),credits:z34.object({total:z34.int(),earned:z34.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z34.email(),emailVerified:z34.boolean(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z35}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=z35.object({id:z35.string(),principalType:ProjectPrincipalTypeSchema,principalId:z35.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z35.coerce.date(),expiresAt:z35.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","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=z35.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z35.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z35.record(z35.string(),z35.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z35.object({access:z35.array(ProjectAccessItemDTOSchema),invites:z35.array(ProjectInviteDTOSchema),organization:z35.object({name:z35.string().nullable(),logo:z35.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z35.object({success:z35.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z35.object({success:z35.boolean(),projectId:z35.uuid()}))}});import{z as z36}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=z36.object({publicationStatus:PublicationStatusSchema,appUrl:z36.string().nullable(),lastPublishedAt:z36.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z37}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=z37.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z37.object({branch:BranchSchema,revision:z37.string().min(1).max(64).nullable(),generation:z37.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z37.url().nullable()})}});import{z as z38}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,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=z38.object({code:z38.literal("PREVIEW_UPGRADE_REQUIRED"),message:z38.string(),currentVersion:z38.number().int().positive(),targetVersion:z38.literal(4)}),PreviewBridgePackageSchema=z38.object({name:z38.string().min(1),version:z38.string().min(1)}),PreviewBridgeCapabilitySchema=z38.object({integrated:z38.boolean(),packages:z38.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z38.object({url:z38.url(),expiresAt:z38.iso.datetime().nullable(),source:z38.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z38.object({name:z38.string().min(1),locator:z38.string().min(1).optional(),source:z38.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z38.object({kind:z38.literal("dependency_build_scripts_blocked"),packageManager:z38.enum(["pnpm","yarn","bun"]),packages:z38.array(z38.string()),targets:z38.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z38.string(),approvalKey:z38.string(),command:z38.string().optional(),approval:z38.object({id:z38.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z38.object({code:z38.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z38.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z38.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z38.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z38.object({message:z38.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z38.number().int().optional().catch(void 0),logTail:z38.array(z38.string()).optional().catch(void 0),logTailTruncated:z38.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z38.object({approvalId:z38.uuid()}),PreviewInstallPolicyApprovalEventSchema=z38.discriminatedUnion("type",[z38.object({type:z38.literal("progress"),step:z38.enum(["approval","install","restart","readiness"]),message:z38.string()}),z38.object({type:z38.literal("approved")}),z38.object({type:z38.literal("complete")}),z38.object({type:z38.literal("error"),code:z38.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z38.string()})])}});import{z as z39}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z39.string(),slug:z39.string().nullable(),logo:z39.string().nullable(),metadata:z39.record(z39.string(),z39.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z39.object({id:z39.string(),name:z39.string(),email:z39.email(),image:z39.string().nullable()}),OrganizationMemberDTOSchema=z39.object({id:z39.string(),userId:z39.string(),organizationId:z39.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z39.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z40}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=z40.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z40.object({reason:CancellationReasonCodeSchema,details:z40.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z40.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z40.object({offerVersion:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),renewsOn:z40.string()}),PlanMigrationPreviewDTOSchema=z40.object({currency:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),startsAt:z40.string(),renewsAt:z40.string(),nextRenewalAmount:z40.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z40.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z40.object({id:z40.string(),organizationId:z40.string(),legacySubscriptionId:z40.string(),offeredPlanCode:z40.string(),offeredPlanName:z40.string(),offeredPriceAmount:z40.number(),offeredCurrency:z40.string(),offerVersion:z40.string(),state:PlanMigrationStateSchema,checkoutToken:z40.string().nullable(),deadlineAt:z40.string(),transitions:z40.array(z40.object({event:z40.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z40.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z40.object({included:z40.number().optional(),unitPrice:z40.number().optional(),dailyCap:z40.number().nullable().optional()}),EntitlementsDTOSchema=z40.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z40.object({retentionDays:z40.number().int().positive(),canUseExtendedDateRanges:z40.boolean()}).optional(),history:z40.object({retentionDays:z40.number().int().positive()}).optional(),members:z40.object({canInvite:z40.boolean(),maxMembers:z40.number().int().positive().nullable()}).optional(),projects:z40.object({maxProjects:z40.number().int().positive().nullable()}).optional(),domains:z40.object({canUseCustomDomains:z40.boolean(),maxDomains:z40.number().int().nonnegative().nullable()}).optional(),media_storage:z40.object({limitBytes:z40.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z40.object({usedBytes:z40.number().int().nonnegative().nullable(),limitBytes:z40.number().int().nonnegative().nullable(),state:z40.enum(["ready","unavailable"]),measuredAt:z40.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z40.object({toPlanCode:TemplateCodeSchema,effectiveAt:z40.string(),scheduledAt:z40.string().nullable()}),AutomaticSpendStopDTOSchema=z40.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z40.string(),spendStopped:z40.boolean(),settlementEndsAt:z40.string()}),HostingOverageStatusDTOSchema=z40.object({state:z40.enum(["ready","unavailable"]),planCode:z40.string(),overageAvailable:z40.boolean(),overageEnabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().nullable(),periodStart:z40.iso.datetime().nullable(),periodEnd:z40.iso.datetime().nullable(),usedBytes:z40.number().nonnegative().nullable(),includedBytes:z40.number().nonnegative().nullable(),overageBytes:z40.number().nonnegative(),currentOverageAmountMicros:z40.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z40.number().nonnegative().nullable(),currency:z40.string().nullable(),status:z40.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z40.object({enabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z40.object({id:z40.string(),external_id:z40.string(),customerId:z40.string(),planId:z40.string(),planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]),currentPeriod:z40.object({start:z40.string(),end:z40.string().nullable()}),cancelAt:z40.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z40.string(),nextPaymentAt:z40.string().nullable(),baseAmount:z40.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z40.object({totalCap:z40.number(),dailyCap:z40.number(),usedTotal:z40.number()}),CreditBalanceDTOSchema=z40.object({total:z40.number(),base:z40.number(),dailyBase:z40.number(),purchases:z40.number(),awards:z40.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z40.object({total:z40.number(),nearLimit:z40.boolean(),canChat:z40.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z40.object({dailyFreeAvailable:z40.number(),monthlyAvailable:z40.number(),purchasedAvailable:z40.number(),awardedAvailable:z40.number()}),ProjectDailyCreditAllowanceDTOSchema=z40.object({periodCap:z40.number(),dailyGrant:z40.number(),usedThisPeriod:z40.number(),remainingThisPeriod:z40.number()}),ProjectCreditBalanceDTOSchema=z40.object({projectId:z40.uuid(),organizationId:z40.string(),balance:z40.object({totalAvailable:z40.number(),nearLimit:z40.boolean(),canUseAi:z40.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z40.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().nonnegative(),refillAmountUsd:z40.number().nonnegative()}),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().nonnegative().nullable(),refillAmountUsd:z40.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().min(.01).multipleOf(.01),refillAmountUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z40.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z40.object({planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]).nullable(),canPurchase:z40.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z40.number().int().positive(),minAmountUsd:z40.number().positive(),maxAmountUsd:z40.number().positive(),rateToken:z40.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z40.object({amountUsd:z40.number(),idempotencyKey:z40.string().trim().min(8).max(120),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z40.object({invoiceId:z40.string(),newBalance:z40.int(),creditCount:z40.int(),amountUsd:z40.number(),creditsPerDollar:z40.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z40.object({url:z40.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z40.object({id:z40.string(),number:z40.string().nullable(),status:z40.string(),amountDue:z40.int(),currency:z40.string(),issuedAt:z40.string().nullable(),hostedInvoiceUrl:z40.string().nullable()}),PaymentRecoveryDTOSchema=z40.discriminatedUnion("status",[z40.object({status:z40.literal("eligible"),checkedAt:z40.string()}),z40.object({status:z40.literal("recovery_required"),checkedAt:z40.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z40.int().min(1)}),z40.object({status:z40.literal("unavailable"),checkedAt:z40.string(),reason:z40.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 z41}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=z41.object({brand:z41.string(),last4:z41.string(),exp:z41.string(),isDefault:z41.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z42}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=z42.string().superRefine((path49,ctx)=>{let segments=path49.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=z42.object({type:z42.literal("renameField"),contentType:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z42.object({enabled:z42.boolean()}).strict(),ContentFieldGroupSchema=z42.object({id:z42.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z42.string().min(1).max(255),default:z42.boolean().optional()}).strict(),ContentTypeDTOSchema=z42.object({id:z42.string(),name:z42.string(),label:z42.string(),isSingleton:z42.boolean(),i18n:ContentTypeI18nSchema,groups:z42.array(ContentFieldGroupSchema).default([]),fields:z42.record(z42.string(),FieldDefinitionSchema),createdAt:z42.string(),updatedAt:z42.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z42.object({contentTypes:z42.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z42.object({id:z42.string(),entryId:z42.string(),documentId:z42.string(),slug:z42.string(),locale:z42.string().optional(),createdAt:z42.string(),updatedAt:z42.string(),__fimo:z42.object({contentType:z42.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({limit:z42.number(),offset:z42.number(),total:z42.number(),hasMore:z42.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z42.object({contentType:z42.string(),count:z42.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z42.object({counts:z42.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z42.object({count:z42.number().int().nonnegative(),sourceLocale:z42.string(),targetLocale:z42.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z42.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z42.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z42.union([z42.string(),z42.number(),z42.boolean(),z42.null()]),entryWhereOperatorSchema=z42.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z42.array(entryWhereScalarSchema).optional(),$nin:z42.array(entryWhereScalarSchema).optional(),$contains:z42.string().optional(),$startsWith:z42.string().optional(),$null:z42.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z42.object({data:z42.record(z42.string(),z42.unknown()),locale:z42.string().min(1).optional(),documentId:z42.uuid().optional()}),entryIdsSchema=z42.array(z42.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z42.object({sql:z42.string().min(1)}),BulkCreateEntriesRequestSchema=z42.object({entries:z42.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z42.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z42.object({updates:z42.array(z42.object({id:z42.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,locale:z42.string().min(1).optional()}),z42.object({where:EntryWhereSchema,locale:z42.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z42.object({data:z42.array(z42.record(z42.string(),z42.unknown())),meta:z42.object({rowCount:z42.number().int().nonnegative(),truncated:z42.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({created:z42.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({updated:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({deleted:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z43}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z43.object({index:z43.number().int().nonnegative(),contentType:z43.string(),field:z43.string(),value:z43.string(),against:z43.enum(["stored","batch"]),ownerDocumentId:z43.uuid().optional(),ownerIndex:z43.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z43.object({code:z43.literal("unique_conflict"),message:z43.string(),conflicts:z43.array(UniqueConflictSchema),truncated:z43.boolean().optional()})}});import{z as z44}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=z44.object({kind:z44.literal("unique_conflict"),contentType:z44.string(),field:z44.string(),value:z44.string(),documentCount:z44.number().int().positive(),documentIds:z44.array(z44.uuid()),documentIdsTruncated:z44.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z44.object({code:z44.literal("schema_transition_rejected"),message:z44.string(),issues:z44.array(SchemaTransitionIssueSchema),truncated:z44.boolean().optional()})}});import{z as z45}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=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z45.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z45.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z45.object({field:CmsFieldNameSchema,direction:z45.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z45.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z45.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z45.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z45.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z45.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z46}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=z46.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z47}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=z47.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z47.object({event:ClientTrackedEventSchema,properties:z47.record(z47.string(),z47.unknown()).default({})})}});import{z as z48}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=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z48.object({error:z48.string(),code:z48.literal("media_storage_limit_exceeded"),usedBytes:z48.number().int().nonnegative(),limitBytes:z48.number().int().positive(),incomingBytes:z48.number().int().nonnegative()}),AssetReferenceScopeSchema=z48.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z48.object({assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z48.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z48.object({totalFiles:z48.number().int().nonnegative(),checkedFiles:z48.number().int().nonnegative(),limit:z48.number().int().positive()}),AssetReferenceFindingDTOSchema=z48.object({assetId:z48.uuid(),entryId:z48.string(),documentId:z48.string(),contentType:z48.string(),locale:z48.string().nullable(),slug:z48.string(),fieldPath:z48.string()}),AssetReferenceScopeResultDTOSchema=z48.object({scope:AssetReferenceScopeSchema,label:z48.string(),state:z48.enum(["available","not-published","failed"]),coverage:z48.enum(["complete","partial","failed"]),referenceCount:z48.number().int().nonnegative().optional(),codeReferenceCount:z48.number().int().nonnegative().optional(),referencedAssetIds:z48.array(z48.uuid()).optional(),references:z48.array(AssetReferenceFindingDTOSchema),reason:z48.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z48.discriminatedUnion("type",[z48.object({type:z48.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z48.object({type:z48.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z48.object({type:z48.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z48.object({replacementAssetId:z48.uuid()}),AssetReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),entriesChanged:z48.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),filesChanged:z48.number().int().nonnegative(),commitSha:z48.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z48.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=z48.object({error:z48.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z48.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=z48.object({intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z48.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=z48.object({id:z48.uuid(),intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()),replacementAssetId:z48.uuid().nullable(),expiresAt:z48.iso.datetime(),undoable:z48.boolean(),requestedByMe:z48.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z48.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z48.object({error:z48.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z51.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z51.object({minLength:z51.number().optional(),maxLength:z51.number().optional(),min:z51.number().optional(),max:z51.number().optional(),pattern:z51.string().optional(),maxFileSize:z51.number().optional(),accept:z51.array(z51.string()).optional()}),FormFieldSchema=z51.object({type:FormFieldTypeSchema,label:z51.string(),placeholder:z51.string().optional(),required:z51.boolean().optional(),defaultValue:z51.string().optional(),options:z51.array(z51.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z51.record(z51.string(),FormFieldSchema),FormContentSchema=z51.object({name:z51.string().min(1).max(255),label:z51.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 z52}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineModelSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,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=z52.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z52.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z52.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z52.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z52.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z52.string().trim().min(1).max(120),ChatRoutineEventTriggerDTOSchema=z52.object({text:z52.string(),title:z52.string(),explanation:z52.string()}),ChatRoutineEventTriggerInputSchema=z52.object({text:z52.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z52.object({manual:z52.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z52.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z52.object({message:z52.string().trim().min(1).max(2e4),decision:z52.boolean().optional(),incomplete:z52.boolean().optional()}).refine(report=>!(report.decision===!0&&report.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z52.object({id:z52.string().uuid(),threadId:z52.string().uuid(),runThreadId:z52.string().uuid(),name:z52.string(),instructions:z52.string(),triggers:ChatRoutineTriggersDTOSchema,model:z52.string(),modelIsDefault:z52.boolean(),paused:z52.boolean(),nextRunAt:z52.string().nullable(),lastRunAt:z52.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),createdAt:z52.string(),updatedAt:z52.string()}),ChatRoutineListDTOSchema=z52.object({routines:z52.array(ChatRoutineDTOSchema)}),ChatRoutineCreateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional()}),ChatRoutineUpdateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),paused:z52.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z52.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown"]),ChatRoutineRefusalDTOSchema=z52.object({message:z52.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z52.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z52.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z52.object({kind:z52.enum(["person","agent"]),name:z52.string().nullable()}),ChatRoutineRunDTOSchema=z52.object({messageId:z52.string().uuid(),invocationId:z52.string().uuid().nullable(),startedAt:z52.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z52.string().nullable(),events:z52.number().int().min(1)}),ChatRoutineRunListDTOSchema=z52.object({runs:z52.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z52.object({message:z52.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z52.object({kind:z52.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z52.string().uuid().nullable()})}});import{z as z53}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,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_project_dto();ChatMessageListDTOSchema=z53.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z53.object({items:z53.array(ProjectMessagePublicDTOSchema),nextCursor:z53.string().nullable()}),ChatLiveTurnDTOSchema=z53.object({invocationId:z53.string(),step:z53.enum(["preparing","working","compacting","merging"]),startedAt:z53.string(),continuesInvocationId:z53.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z53.object({threadId:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z53.object({kind:z53.enum(["person","agent","routine","system"]),id:z53.string().nullable()}),ChatThreadMessageDTOSchema=z53.object({id:z53.string(),role:z53.enum(["user","assistant"]),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),versionId:z53.string().nullable().optional(),createdAt:z53.date().transform(value=>value.toISOString()),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z53.string().nullable().optional(),invocationStatus:z53.string().nullable().optional(),invocationTerminalReason:z53.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z53.object({id:z53.string(),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z53.boolean(),queuedAt:z53.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z53.object({type:z53.literal("merge_conflict"),merge:z53.object({mergeId:z53.string().uuid(),projectId:z53.string(),fromBranch:z53.string(),toBranch:z53.string()}),publishAfterMerge:z53.boolean()}),ChatThreadMessagesPageDTOSchema=z53.object({threadId:z53.string().nullable(),title:z53.string().nullable(),messages:z53.array(ChatThreadMessageDTOSchema),nextCursor:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z53.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z53.boolean().optional(),queueWaitUntil:z53.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z53.object({kind:z53.literal("replay"),threadId:z53.string(),userMessageId:z53.string()}),ChatQueuedOutcomeDTOSchema=z53.object({kind:z53.literal("queued"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatBusyOutcomeDTOSchema=z53.object({kind:z53.literal("busy"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatRefusedOutcomeDTOSchema=z53.object({kind:z53.literal("refused"),threadId:z53.string(),userMessageId:z53.string(),refusedInvocationId:z53.string(),terminalReason:z53.string()}),ChatNonStreamingOutcomeDTOSchema=z53.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z53.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z53.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z53.object({quietRuns:z53.number().int().nonnegative(),since:z53.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z53.string().nullable(),nextRunAt:z53.string().nullable()}),ProjectChatDescriptionSchema=z53.string().trim().max(2e3),ProjectChatDTOSchema=z53.object({id:z53.string().uuid(),kind:ProjectChatKindSchema,title:z53.string().nullable(),description:z53.string().nullable(),template:z53.string().nullable(),parentThreadId:z53.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z53.string(),lastMessageAt:z53.string().nullable(),preview:z53.string().nullable(),running:z53.boolean(),awaitingAnswer:z53.boolean(),unread:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z53.object({chats:z53.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z53.object({id:z53.string().uuid()}),ProjectChatTitleSchema=z53.string().trim().min(1).max(120),ProjectChatCreateSchema=z53.object({id:z53.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z53.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema}).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"),ProjectChatUpdateSchema=z53.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.portrait!==void 0,"Set a title, a description or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z53.object({cron:z53.string()}),ChatTemplateRoutineDTOSchema=z53.object({name:z53.string(),instructions:z53.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable()}),ChatTemplateDTOSchema=z53.object({id:z53.string(),name:z53.string(),summary:z53.string(),description:z53.string(),portrait:ChatPortraitSchema,routines:z53.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z53.object({templates:z53.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z53.object({read:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.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 z54}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=z54.object({url:z54.string().url(),key:z54.string(),size:z54.number(),contentType:z54.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z55}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=z55.object({canAccess:z55.boolean(),permissions:z55.record(z55.string(),z55.boolean()),role:z55.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z56}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:z56.string().trim().default(""),sort:z56.enum(["recent","name","relevance"]).default("recent"),category:z56.string().optional()})}});import{z as z57}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=z57.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z57.enum(["fimo","external"]),PaymentStatusSchema=z57.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z57.object({id:z57.string().uuid(),domain:z57.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z57.boolean(),price:z57.number().int().nullable(),renewalPrice:z57.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z57.string().nullable(),failureReason:z57.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z57.object({domain:z57.string(),available:z57.boolean(),premium:z57.boolean(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),purchaseType:z57.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z57.object({domain:z57.string(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),premium:z57.boolean(),allowedYears:z57.array(z57.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z57.object({firstName:z57.string().max(100),lastName:z57.string().max(100),companyName:z57.string().max(100).optional(),address1:z57.string().max(255),address2:z57.string().max(255).optional(),city:z57.string().max(100),state:z57.string().max(100),zip:z57.string().max(20),country:z57.string().max(2),phone:z57.string().max(30),email:z57.union([z57.string().email().max(255),z57.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z57.object({firstName:z57.string().min(1).max(100),lastName:z57.string().min(1).max(100),companyName:z57.string().max(100).optional(),address1:z57.string().min(1).max(255),address2:z57.string().max(255).optional(),city:z57.string().min(1).max(100),state:z57.string().min(1).max(100),zip:z57.string().min(1).max(20),country:z57.string().min(1).max(2),phone:z57.string().min(1).max(30),email:z57.string().email().max(255)}),SearchDomainsRequestSchema=z57.object({keyword:z57.string().min(1).max(100),tldFilter:z57.array(z57.string()).optional()}),CheckAvailabilityRequestSchema=z57.object({domains:z57.array(z57.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=z57.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z57.object({domain:DomainNameSchema,years:z57.number().int().min(1).max(10).optional().default(3),autoRenew:z57.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z57.object({autoRenew:z57.boolean().optional()}),RenewDomainRequestSchema=z57.object({years:z57.number().int().min(1).max(10).optional().default(1),autoRenew:z57.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z57.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z57.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z57.object({verified:z57.boolean(),email:z57.string().nullable(),verifyBy:z57.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z58}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z58.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=z58.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=z58.object({txtName:z58.string().nullable().optional(),txtValue:z58.string().nullable().optional(),httpUrl:z58.string().nullable().optional(),httpBody:z58.string().nullable().optional(),cname:z58.string().nullable().optional(),cnameTarget:z58.string().nullable().optional()}),SSLValidationErrorSchema=z58.object({message:z58.string()}),OwnershipVerificationSchema=z58.object({type:z58.string(),name:z58.string(),value:z58.string()}),ProjectDomainSSLDTOSchema=z58.object({status:z58.string(),method:z58.string().nullable(),type:z58.string().nullable(),validationRecords:z58.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z58.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z58.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z58.enum(["subdomain","apex"]),RedirectConfigSchema=z58.object({type:z58.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z58.string()}).nullable().optional(),ProjectDomainDTOSchema=z58.object({id:z58.string(),hostname:z58.string(),status:z58.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z58.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z58.string(),scdCnameTarget:z58.string().optional(),apexTargets:z58.array(z58.string()),dnsAutoConfigured:z58.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z58.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z58.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z58.object({hostname:z58.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:z58.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z58.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z58.object({success:z58.boolean(),hostname:z58.string()}))}});import{z as z59}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=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z59.object({available:z59.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z59.object({slug:z59.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z59.object({subdomain:z59.string(),subdomainUpdatedAt:z59.coerce.date()})),SubdomainSuggestionsQuerySchema=z59.object({base:z59.string().max(100).optional(),max:z59.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z59.object({suggestions:z59.array(z59.string())}))}});import{z as z60}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=z60.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z60.object({code:ProjectTransferBlockerCodeSchema,message:z60.string(),count:z60.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z60.object({targetOrganizationId:z60.string().min(1)}),ProjectTransferResultDTO=createDTO(z60.object({projectId:z60.string(),sourceOrganizationId:z60.string(),targetOrganizationId:z60.string(),movedThreads:z60.number().int().nonnegative(),revokedInvites:z60.number().int().nonnegative(),revokedGrants:z60.number().int().nonnegative(),preservedGrants:z60.number().int().nonnegative(),warnings:z60.array(z60.string())}))}});import{z as z61}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=z61.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z61.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","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=z61.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z61.object({displayName:z61.string().trim().min(1).max(80),machineId:z61.string().trim().min(1).max(128).optional(),cliVersion:z61.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z61.object({ttlHours:z61.number().int().positive(),lockedFeatures:z61.array(UnclaimedLockedFeatureSchema),media:z61.object({totalBytes:z61.number().int().nonnegative(),fileBytes:z61.number().int().positive(),maxFiles:z61.number().int().nonnegative(),mimeTypes:z61.array(z61.string())}),database:z61.object({storageBytes:z61.number().int().positive(),computeSeconds:z61.number().int().positive(),maxComputeUnits:z61.number().positive()})}),UnclaimedProjectClaimSchema=z61.object({url:z61.string().url(),expiresAt:z61.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z61.object({project:ProjectDTOSchema,token:z61.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z61.object({state:UnclaimedClaimStateSchema,displayName:z61.string().nullable(),expiresAt:z61.coerce.date().nullable(),projectId:z61.string().nullable()})),UnclaimedClaimSecretSchema=z61.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z61.object({secrets:z61.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z61.object({claims:z61.array(z61.object({state:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema,organizationId:z61.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z61.object({projectId:z61.string(),organizationId:z61.string()})),ProjectTokenSelfDTO=createDTO(z61.object({kind:z61.literal("project_token"),projectId:z61.string(),projectName:z61.string(),displayName:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable(),tokenExpiresAt:z61.coerce.date().nullable()}))}});import{z as z62}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=z62.object({translated:z62.number().int().nonnegative(),total:z62.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z62.object({locale:z62.string(),isDefault:z62.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z62.object({defaultLocale:z62.string(),locales:z62.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z62.object({locale:z62.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z62.object({locale:z62.string().min(1).max(40)}),ProjectLocaleMutationSchema=z62.object({locale:z62.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z62.object({locale:z62.string(),entriesDeleted:z62.number().int().nonnegative(),labelsDeleted:z62.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z63}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=z63.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z63.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=z63.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z63.number(),credits:z63.number().optional(),billingMode:z63.enum(["fimo-credits","provider-account"]).optional(),confidence:z63.enum(["exact","estimated","metered"]),basis:z63.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z64}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=z64.object({options:z64.record(z64.string(),z64.unknown()),name:z64.string().optional(),parentId:z64.string().nullable().optional(),altText:z64.string().optional(),caption:z64.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z64.string().min(1).optional(),model:z64.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=z64.object({jobId:z64.string(),status:z64.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z64.string().nullable().optional(),credits:z64.number().optional(),costUsd:z64.number().optional(),billingMode:z64.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z64.object({error:z64.string(),code:z64.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:z64.array(GenerationTaskIdSchema).optional(),availableModels:z64.array(z64.string()).optional(),issues:z64.array(z64.unknown()).optional()})}});import{z as z65}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=z65.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z65.object({name:z65.string(),key:z65.string(),description:z65.string(),type:FlagTypeSchema,required:z65.boolean(),defaultValue:z65.unknown().optional(),enumValues:z65.array(z65.string()).optional(),isArray:z65.boolean()}),AssetModelPriceSchema=z65.object({unitPrice:z65.number(),unit:z65.string(),confidence:z65.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z65.object({id:z65.string(),shortName:z65.string(),provider:z65.string(),source:z65.string(),modality:z65.enum(["image","video","audio"]),tags:z65.array(z65.string()),displayName:z65.string(),description:z65.string(),flags:z65.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z65.object({model:z65.string(),costUsd:z65.number(),credits:z65.number(),billingMode:z65.enum(["fimo-credits","provider-account"]),confidence:z65.enum(["exact","estimated","metered"]),basis:z65.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z66}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=z66.object({tourId:z66.string(),version:z66.string(),status:z66.string(),completedAt:z66.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z66.array(UserTourDTOSchema))}});import{z as z67}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=z67.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z67.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z67.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z67.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z67.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z67.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z67.enum(["user","agent","system"]),SupportReportTagSchema=z67.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z67.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z67.object({organization:z67.object({id:z67.string().trim().min(1).max(255),name:z67.string().trim().max(240).optional()}),project:z67.object({id:z67.uuid(),name:z67.string().trim().max(240).optional(),createdAt:z67.coerce.date().optional()}).optional(),environment:z67.string().trim().max(255).optional(),clientVersion:z67.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z67.object({message:z67.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z67.string().trim().max(200).optional(),limit:z67.coerce.number().int().min(1).max(100).default(50),offset:z67.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z67.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z67.uuid().nullable().optional(),note:z67.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=z67.object({message:z67.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z67.object({kind:SupportReportLinkKindSchema,label:z67.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z67.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z67.object({kind:SupportReportActorKindSchema,id:z67.string().nullable(),name:z67.string().nullable()}),SupportReportLinkDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportLinkKindSchema,label:z67.string(),url:SupportReportHttpUrlSchema,externalId:z67.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportEventKindSchema,body:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()),actor:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z67.object({id:z67.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z67.array(z67.string()),source:SupportReportSourceSchema,message:z67.string(),reporter:z67.object({id:z67.string().nullable(),name:z67.string().nullable(),email:z67.string().nullable()}),organization:z67.object({id:z67.string().nullable(),name:z67.string()}),project:z67.object({id:z67.uuid().nullable(),name:z67.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z67.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z67.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}).nullable(),duplicateOfReportId:z67.uuid().nullable(),resolvedAt:z67.coerce.date().nullable(),createdAt:z67.coerce.date(),updatedAt:z67.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z67.string().nullable(),clientVersion:z67.string().nullable(),links:z67.array(SupportReportLinkDTOSchema),events:z67.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z67.object({reports:z67.array(SupportReportSummaryDTOSchema),total:z67.number().int().nonnegative(),statusCounts:z67.object({new:z67.number().int().nonnegative(),in_progress:z67.number().int().nonnegative(),waiting:z67.number().int().nonnegative(),resolved:z67.number().int().nonnegative(),duplicate:z67.number().int().nonnegative(),irrelevant:z67.number().int().nonnegative(),ignored:z67.number().int().nonnegative()}),limit:z67.number().int().positive(),offset:z67.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z67.object({id:z67.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z67.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z68}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=z68.iso.datetime({offset:!0}).pipe(z68.coerce.date()),OpsRecentChatInputSchema=z68.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z68.string().trim().min(1).max(255).optional(),limit:z68.coerce.number().int().min(1).max(200).default(100),cursor:z68.string().trim().min(1).max(2e3).optional(),slim:z68.boolean().default(!0),reason:z68.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=z68.object({id:z68.string(),threadId:z68.string(),providerMessageId:z68.string().nullable(),invocationId:z68.string().nullable(),env:z68.string().nullable(),role:z68.string(),parts:z68.array(z68.record(z68.string(),z68.unknown())),metadata:z68.object({status:z68.string().optional(),traceUrl:z68.string().optional(),externalFileChanges:z68.array(z68.unknown()).optional()}),stats:z68.object({toolCount:z68.number().int().nonnegative(),failedToolCount:z68.number().int().nonnegative()}),createdAt:z68.iso.datetime({offset:!0}),project:z68.object({id:z68.string(),name:z68.string(),displayName:z68.string().nullable(),organizationId:z68.string().nullable()})}),OpsRecentChatResponseSchema=z68.object({target:z68.object({backendProfile:OpsBackendProfileSchema,projectEnv:z68.string().nullable()}),window:z68.object({from:z68.iso.datetime({offset:!0}),to:z68.iso.datetime({offset:!0})}),messages:z68.object({items:z68.array(OpsRecentChatMessageSchema),nextCursor:z68.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z69}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=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z69.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z69.literal(!1),reason:z69.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z70}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=z70.object({packageManager:z70.string().trim().min(1).max(200).nullable(),trackedLockfiles:z70.array(z70.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z70.string().trim().min(1)}),OpsProjectPackageManagerSchema=z70.object({target:z70.object({backendProfile:OpsBackendProfileSchema,projectId:z70.uuid(),projectEnv:z70.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z71}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:z71.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z71.union([z71.object({name:z71.string().trim().min(1).max(120),description:z71.string().trim().min(1).max(2e3)}).strict(),z71.object({template:z71.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z71.object({agent:OpsAgentChatAgentSpecSchema,routines:z71.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:z71.string().trim().min(1).max(1e3),dryRun:z71.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z71.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z71.object({id:z71.string().uuid().nullable(),name:z71.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z71.string().nullable(),paused:z71.boolean(),outcome:z71.enum(["created","would_create"]),source:z71.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z71.object({target:z71.object({backendProfile:OpsBackendProfileSchema,projectId:z71.string().uuid()}),dryRun:z71.boolean(),applied:z71.boolean(),createdBy:z71.object({userId:z71.string()}),agent:z71.object({id:z71.string().uuid().nullable(),title:z71.string(),template:z71.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z71.array(OpsAgentChatRoutineResultSchema),skipped:z71.array(z71.object({name:z71.string(),reason:z71.literal("routine_exists")})),refused:z71.array(z71.object({name:z71.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z72}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=z72.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z72.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z72.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z72.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z72.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z72.object({reason:WebhookEntryChangeReasonSchema,operationId:z72.string().optional(),batch:z72.object({index:z72.number().int().positive(),total:z72.number().int().positive()}).optional(),changes:z72.array(z72.object({action:WebhookEntryChangeActionSchema,contentType:z72.string(),id:z72.string(),documentId:z72.string(),locale:z72.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z72.object({form:z72.object({id:z72.string(),label:z72.string()}),submission:z72.object({id:z72.string(),data:z72.record(z72.string(),z72.unknown()),submittedAt:z72.string()})}),PublishStartedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("publishing"),startedAt:z72.string()})}),PublishSucceededWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("published"),url:z72.string(),publishedAt:z72.string(),firstPublish:z72.boolean()})}),PublishFailedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("failed"),reason:z72.string()})}),PublishUnpublishedWebhookEventDataSchema=z72.object({publication:z72.object({previousUrl:z72.string(),unpublishedAt:z72.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z72.object({report:z72.object({weekStart:z72.string(),weekEnd:z72.string(),pageviews:z72.number(),visitors:z72.number(),previousPageviews:z72.number(),previousVisitors:z72.number()})}),MediaAssetWebhookEventDataSchema=z72.object({id:z72.string().nullable(),name:z72.string().nullable(),type:z72.string(),mimeType:z72.string().nullable(),fileSize:z72.number().nullable()}),MediaUploadedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("updated")}),MediaDeletedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string()})}),LabelChangedWebhookEventDataSchema=z72.object({changes:z72.array(z72.object({action:z72.enum(["created","updated","deleted"]),key:z72.string(),locale:z72.string(),value:z72.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),isDefault:z72.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),previousCode:z72.string()})}),LocaleDeletedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),entriesDeleted:z72.number().int().nonnegative(),labelsDeleted:z72.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z72.object({merge:z72.object({id:z72.string(),from:BranchSchema,to:BranchSchema,applied:z72.array(z72.object({surface:SurfaceNameSchema,count:z72.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z72.object({branch:z72.object({name:BranchSchema}),version:z72.object({versionId:z72.uuid(),name:z72.string()})}),WebhookEventFamilySchema=z72.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z72.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z72.discriminatedUnion("source",[z72.object({source:z72.literal("literal"),value:z72.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z72.object({source:z72.literal("secret"),key:z72.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z72.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z72.object({name:z72.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z72.object({name:z72.string(),source:z72.enum(["literal","secret"]),secretKey:z72.string().nullable(),secretPrefix:z72.string().nullable(),configured:z72.literal(!0)}),WebhookFilterSchema=z72.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z72.string().min(1).max(255).optional(),mediaType:z72.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z72.string().min(1).max(255).optional(),locale:z72.string().min(1).max(120).optional()}),JsonValueSchema=z72.lazy(()=>z72.union([z72.string(),z72.number(),z72.boolean(),z72.null(),z72.array(JsonValueSchema),z72.record(z72.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z72.url(),enabled:z72.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z72.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z72.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z72.url().optional(),enabled:z72.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z72.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z72.boolean().optional()}),TestProjectWebhookRequestSchema=z72.object({eventType:WebhookEventTypeSchema.optional(),data:z72.record(z72.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z72.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z72.uuid(),name:z72.string(),eventType:WebhookEventTypeSchema,enabled:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z72.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z72.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z72.coerce.date().nullable(),deliveryStats24h:z72.object({succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z72.uuid(),projectId:z72.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z72.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z72.number().int().positive(),test:z72.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z72.number().int().nonnegative(),responseStatus:z72.number().int().nullable(),lastErrorCode:z72.string().nullable(),lastErrorMessage:z72.string().nullable(),payloadAvailable:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z72.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z72.string().nullable(),qstashMessageId:z72.string().nullable(),deliveredAt:z72.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z72.object({items:z72.array(WebhookDeliveryDTOSchema),pagination:z72.object({page:z72.number().int().positive(),limit:z72.number().int().positive(),total:z72.number().int().nonnegative(),totalPages:z72.number().int().positive(),hasMore:z72.boolean()}),stats:z72.object({total:z72.number().int().nonnegative(),succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z72.object({id:z72.uuid(),deliveryId:z72.uuid(),attempt:z72.number().int().positive(),status:z72.enum(["delivering","succeeded","failed"]),responseStatus:z72.number().int().nullable(),durationMs:z72.number().int().nonnegative(),responseExcerpt:z72.string().nullable(),errorCode:z72.string().nullable(),errorMessage:z72.string().nullable(),createdAt:z72.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z72.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z72.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z73}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=z73.object({key:z73.literal("fimo-2"),enabled:z73.boolean(),dismissed:z73.boolean().default(!1),interacted:z73.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z74}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteReportSchema,SitePriceTierSchema,SiteTypeSchema,SiteTermsCategorySchema,SITE_QUESTION,SITE_QUESTIONS,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=z74.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z74.enum(["running","done","failed"]),SiteCloneStatusSchema=z74.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z74.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z74.object({code:SiteRefusalCodeSchema,suggestedUrl:z74.string().nullable()}),SiteCheckGroupSchema=z74.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z74.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=z74.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z74.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z74.record(z74.string(),z74.union([z74.string(),z74.number(),z74.boolean(),z74.array(z74.string())])),SiteCheckResultSchema=z74.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z74.object({id:SiteCheckGroupSchema,score:z74.number().int().min(0).max(100).nullable()}),SiteReportSchema=z74.object({siteUrl:z74.string(),scannedAt:z74.coerce.date(),seoScore:z74.number().int().min(0).max(100).nullable(),geoScore:z74.number().int().min(0).max(100).nullable(),groups:z74.array(SiteReportGroupSchema),checks:z74.array(SiteCheckResultSchema),blockers:z74.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z74.enum(["budget","standard","premium","luxury"]),SiteTypeSchema=z74.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z74.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SITE_QUESTION={id:"site",kind:"confirm"},SITE_QUESTIONS={business:[SITE_QUESTION,{id:"competitors",kind:"form",inputs:[{id:"names",kind:"choices",multiple:!0,allowOther:!0,options:"competitors"}]},{id:"positioning",kind:"form",inputs:[{id:"positioning",kind:"text",max:2e3}]},{id:"priceTier",kind:"form",inputs:[{id:"priceTier",kind:"choices",multiple:!1,allowOther:!1,options:SitePriceTierSchema.options}]}],non_profit:[SITE_QUESTION,{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["volunteer","donate","join","next_event"]}]},{id:"searches",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]}],portfolio:[SITE_QUESTION,{id:"work",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["book_call","request_quote","email","follow"]}]}],hobby:[SITE_QUESTION,{id:"return",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:["creations","tutorials","progress","tips"]}]},{id:"tone",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!1,options:["warm","expert","playful","calm"]}]}],personal:[SITE_QUESTION,{id:"remember",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["read","contact","hire","follow"]}]}]},SiteUnderstandingSchema=z74.object({name:z74.string(),summary:z74.string(),audience:z74.string(),positioning:z74.string(),priceTier:SitePriceTierSchema,homepage:z74.string()}),SiteSuggestionSchema=z74.object({label:z74.string(),url:z74.string().nullable()}),SiteInterviewSuggestionsSchema=z74.record(z74.string(),z74.record(z74.string(),z74.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z74.record(z74.string().max(50),z74.union([z74.string().trim().max(2e3),z74.array(z74.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z74.object({status:z74.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z74.record(z74.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z74.object({questionId:z74.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z74.object({fixes:z74.array(z74.object({checkId:SiteCheckIdSchema,status:z74.enum(["fixed","not_fixed","not_applicable"]),note:z74.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z74.object({fixes:SiteFixesReportSchema.nullable(),summary:z74.string().nullable()}),StartSiteOnboardingRequestSchema=z74.object({organizationId:z74.string().min(1),url:z74.string().trim().min(1).max(2048),locale:z74.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z74.object({projectId:z74.string()})),SiteOnboardingRefusedResponseSchema=z74.object({error:z74.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z74.object({projectId:z74.string(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z74.boolean(),budgetExhausted:z74.boolean(),sponsored:z74.boolean(),cloneOutOfCredits:z74.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z74.string().nullable(),welcomeThreadId:z74.string().nullable(),competitors:z74.array(z74.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable(),bannerDismissed:z74.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z74.object({task:z74.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z74.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z74.object({search:z74.string().trim().max(200).optional(),organizationId:z74.string().trim().min(1).max(200).optional(),startDate:z74.coerce.date().optional(),endDate:z74.coerce.date().optional(),outcomes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteTypeSchema).optional()),page:z74.coerce.number().int().min(1).default(1),pageSize:z74.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z74.object({projectId:z74.string(),projectName:z74.string(),organizationId:z74.string(),organizationName:z74.string().nullable(),ownerEmail:z74.string().nullable(),ownerName:z74.string().nullable(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z74.boolean(),cloneRetries:z74.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z74.number(),interviewQuestions:z74.number().nullable(),seoScore:z74.number().nullable(),geoScore:z74.number().nullable(),spentUsd:z74.number(),budgetCapUsd:z74.number(),capReached:z74.boolean(),cloneSeconds:z74.number().nullable(),createdAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z74.object({onboardings:z74.array(AdminSiteOnboardingDTOSchema),page:z74.number(),limit:z74.number(),total:z74.number(),totalPages:z74.number()})),AdminSiteOnboardingStatsSchema=z74.object({total:z74.number(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number()),funnel:z74.object({started:z74.number(),confirmed:z74.number(),finished:z74.number(),opened:z74.number()}),bySiteType:z74.array(z74.object({siteType:SiteTypeSchema,total:z74.number(),finished:z74.number(),opened:z74.number()})),granularity:z74.enum(["hour","day"]),series:z74.array(z74.object({at:z74.coerce.date(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number())})),spentUsd:z74.object({total:z74.number(),average:z74.number().nullable()}),sponsored:z74.number(),paidByOrganization:z74.object({usd:z74.number(),credits:z74.number()}),capReached:z74.number(),cloneSeconds:z74.object({median:z74.number().nullable(),average:z74.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z74.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z74.string(),cloneThreadId:z74.string().nullable(),paidByOrganizationUsd:z74.number()}),interview:SiteInterviewSchema.extend({invocationIds:z74.array(z74.string())}).nullable(),knowledgeWritten:z74.string().nullable(),knowledgeNow:z74.object({content:z74.string(),updatedAt:z74.coerce.date().nullable(),updatedBy:z74.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z75}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=z75.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z75.object({total:z75.number(),base:z75.number(),purchases:z75.number(),awards:z75.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z75.object({id:z75.string(),name:z75.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z75.object({type:z75.string(),brand:z75.string().nullable(),last4:z75.string().nullable(),expirationDate:z75.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z75.object({currency:z75.string(),nextPaymentAmount:z75.number().nullable(),nextPaymentAt:z75.string().nullable(),billingInterval:z75.string().nullable(),totalAmount:z75.number().nullable(),discountAmount:z75.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z75.object({id:z75.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z75.string().nullable(),currentPeriodEndsAt:z75.string().nullable(),renewsAt:z75.string().nullable(),cancelAt:z75.string().nullable(),renewAutomatically:z75.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z75.object({type:z75.enum(["low_balance","critical_balance","approaching_limit"]),message:z75.string(),estimatedPromptsRemaining:z75.number().nullable(),avgCostPerPrompt:z75.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z75.object({monthlyCredits:z75.number().nullable(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z75.object({organizationId:z75.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z75.string().nullable(),tenureDays:z75.number().int().nonnegative(),capturedAt:z75.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z75.object({hasSubscription:z75.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z75.number().nullable(),alerts:z75.array(CreditAlertDTOSchema),portalUrl:z75.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z75.object({creditCount:z75.number().int().positive(),expiresAt:z75.string().datetime().nullable().optional(),message:z75.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("free"),amountCents:z75.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("purchase"),amountCents:z75.number().int().positive()}),CreditTopupRequestDTOSchema=z75.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z75.object({success:z75.boolean(),transactionId:z75.string().nullable(),newBalance:z75.number(),creditCount:z75.number(),type:z75.enum(["free","purchase"]),invoiceId:z75.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z76}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=z76.object({totalCredits:z76.number(),totalCostUsd:z76.number(),totalMessages:z76.number(),avgCostPerMessage:z76.number(),periodStart:z76.string().nullable(),periodEnd:z76.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z76.object({date:z76.string(),credits:z76.number(),costUsd:z76.number(),messages:z76.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z76.array(UsageByUserForProjectDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z76.object({summary:UsageSummaryDTOSchema,byProject:z76.array(UsageByProjectDTOSchema),byUser:z76.array(UsageByUserDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z77}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=z77.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z77.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z77.object({startDate:z77.string().optional(),endDate:z77.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z77.coerce.number().int().positive().default(1),limit:z77.coerce.number().int().positive().max(100).default(20),sortBy:z77.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z77.string().optional(),activeOnly:z77.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z77.object({totalCredits:z77.number(),totalCostUsd:z77.number(),totalMessages:z77.number(),avgCostPerMessage:z77.number(),avgCreditsPerMessage:z77.number(),periodStart:z77.string(),periodEnd:z77.string(),creditsChange:z77.number().nullable(),costChange:z77.number().nullable(),messagesChange:z77.number().nullable(),unattributedCredits:z77.number(),unattributedCostUsd:z77.number(),unattributedMessages:z77.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z77.object({date:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z77.object({organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number(),projectCount:z77.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z77.object({userId:z77.string(),userName:z77.string().nullable(),userEmail:z77.string().nullable(),userImage:z77.string().nullable(),organizationId:z77.string().nullable(),organizationName:z77.string().nullable(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),projectCount:z77.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z77.object({projectId:z77.string(),projectName:z77.string(),projectDisplayName:z77.string().nullable(),organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z77.object({id:z77.string(),name:z77.string(),value:z77.number(),percentage:z77.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z77.object({day:z77.number(),hour:z77.number(),value:z77.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z77.object({summary:UsageOverviewSummaryDTOSchema,timeline:z77.array(UsageTimelinePointDTOSchema),topOrganizations:z77.array(OrganizationUsageRowDTOSchema),topUsers:z77.array(UserUsageRowDTOSchema),topProjects:z77.array(ProjectUsageRowDTOSchema),creditDistribution:z77.array(UsageDistributionItemDTOSchema),userDistribution:z77.array(UsageDistributionItemDTOSchema),heatmap:z77.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z77.object({page:z77.number(),limit:z77.number(),totalItems:z77.number(),totalPages:z77.number(),hasMore:z77.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z77.object({organizations:z77.array(OrganizationUsageRowDTOSchema),top:z77.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z77.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z77.object({users:z77.array(ExtendedUserUsageRowDTOSchema),top:z77.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z77.object({projects:z77.array(ExtendedProjectUsageRowDTOSchema),top:z77.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z77.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z77.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z77.object({credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),createdAt:z77.string(),memberCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z77.object({id:z77.string(),name:z77.string().nullable(),email:z77.string(),image:z77.string().nullable(),createdAt:z77.string(),organizationCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),displayName:z77.string().nullable(),createdAt:z77.string(),organizationId:z77.string(),organizationName:z77.string(),ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z78}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=z78.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z78.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z78.object({command:z78.string().min(1).max(1e4),cwd:z78.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z78.record(z78.string(),z78.string()).optional(),name:z78.string().optional(),waitForCompletion:z78.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=z78.object({identifier:z78.string(),status:SandboxProcessStatusSchema,command:z78.string().optional(),startedAt:z78.string().optional(),exitCode:z78.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z78.object({processes:z78.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z78.object({processId:z78.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z78.object({success:z78.boolean(),message:z78.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z79}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=z79.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z79.object({search:z79.string().trim().max(200).optional(),startDate:z79.coerce.date().optional(),endDate:z79.coerce.date().optional(),states:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(AdminUnclaimedStateSchema).optional()),cliVersions:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(z79.string().max(64)).optional()),page:z79.coerce.number().int().min(1).default(1),pageSize:z79.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z79.object({projectId:z79.string(),displayName:z79.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z79.string().nullable(),createdAt:z79.coerce.date(),expiresAt:z79.coerce.date(),claimedAt:z79.coerce.date().nullable(),claimedOrganizationId:z79.string().nullable(),claimedOrganizationName:z79.string().nullable(),claimedByEmail:z79.string().nullable(),projectExists:z79.boolean(),previewUrl:z79.string().nullable(),hostingCostUsd:z79.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z79.object({projects:z79.array(AdminUnclaimedProjectDTOSchema),page:z79.number(),limit:z79.number(),total:z79.number(),totalPages:z79.number()})),ClaimOutcomesSchema=z79.object({total:z79.number(),claimed:z79.number(),archived:z79.number(),claimRate:z79.number().nullable(),medianTimeToClaimSeconds:z79.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z79.record(AdminUnclaimedStateSchema,z79.number()),averageTimeToClaimSeconds:z79.number().nullable(),byCliVersion:z79.array(ClaimOutcomesSchema.extend({cliVersion:z79.string().nullable()})),granularity:z79.enum(["hour","day"]),series:z79.array(z79.object({at:z79.coerce.date(),states:z79.record(AdminUnclaimedStateSchema,z79.number()),alive:z79.number(),hostingCostUsd:z79.number()})),hostingCostUsd:z79.number(),costPerProjectUsd:z79.number().nullable(),leftovers:z79.object({overdue:z79.number(),claiming:z79.number(),archivedNotDeleted:z79.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z80}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z80.enum(["internal","user-visible"]),SessionSetRetentionSchema=z80.object({additionalDays:z80.number().int().min(1).max(30)}).strict()}});import{z as z81}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=z81.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=z81.object({content:ProjectKnowledgeContentSchema,updatedAt:z81.string().nullable(),updatedBy:z81.string().nullable()}),ProjectKnowledgeUpdateSchema=z81.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z81.object({id:z81.uuid(),status:z81.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z81.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z81.object({idempotencyKey:z81.uuid()})}});import{z as z82}from"zod";var ORGANIZATION_FEATURES,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=["agents"],OrganizationFeatureSchema=z82.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z82.object({features:z82.record(OrganizationFeatureSchema,z82.boolean())}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z82.object({feature:OrganizationFeatureSchema,enabled:z82.boolean(),default:z82.boolean(),override:z82.boolean().nullable(),reason:z82.string().nullable(),updatedBy:z82.string().nullable(),updatedAt:z82.string().datetime().nullable()}),OrganizationFeatureSetSchema=z82.object({state:z82.enum(["on","off","default"]),reason:z82.string().trim().min(1).max(500),apply:z82.boolean().default(!1),confirmProduction:z82.boolean().default(!1)})}});import{z as z83}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_chat_block();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_agent_question_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_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()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.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="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},"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_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,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)}
|
|
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:(a,b)=>(typeof require<"u"?require:a)[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","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 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 h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function 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(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${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,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_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"],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,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,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_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_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_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_agent_runtime_attach","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_agent_branch_discard","admin_resource_read","merge_force"],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";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_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,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,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,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,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_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z12.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"],OpsPermissionSchema=z12.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:organization:features:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops: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"],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=z12.object({permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),enabled:z12.boolean().default(!0)}),OpsServiceTokenInputSchema=z12.object({name:z12.string().trim().min(1).max(120),permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),expiresAt:z12.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=z12.object({importanceReason:z12.string().trim().min(1).max(1e3),ownerUserId:z12.string().trim().min(1).nullable().optional(),framework:z12.string().trim().max(120).nullable().optional(),packageManager:z12.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z12.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z12.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z12.object({projectId:z12.uuid(),title:z12.string().trim().min(1).max(240),userReport:z12.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z12.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z12.string().trim().max(1e4).nullable().optional(),outcome:z12.string().trim().max(1e4).nullable().optional(),evidence:z12.array(z12.record(z12.string(),z12.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=z12.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z12.object({fingerprint:z12.string().trim().min(1).max(240),title:z12.string().trim().min(1).max(240),description:z12.string().trim().min(1).max(1e4),affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z12.array(z12.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z12.string().trim().min(1).max(64).nullable().optional(),workaround:z12.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100),detectionQueries:z12.array(z12.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=z12.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z12.object({changeReference:z12.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z12.string().trim().min(1).max(1e4),evidence:z12.array(z12.record(z12.string(),z12.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z12.object({recipientEmail:z12.email().optional(),subject:z12.string().trim().min(1).max(200).default("An update from Fimo"),message:z12.string().trim().min(1).max(5e3),locale:z12.string().trim().min(2).max(20),reason:z12.string().trim().min(1).max(1e3),acknowledgePolicy:z12.literal(!0)}),OpsPylonIssueIdSchema=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z12.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z12.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z12.string().trim().min(1).max(255),OpsPylonEmailListSchema=z12.array(z12.email()).max(50).default([]),OpsPylonResolveInputSchema=z12.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z12.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z12.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z12.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=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z12.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z12.object({projectId:z12.uuid(),from:z12.coerce.date(),to:z12.coerce.date(),reason:z12.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=z12.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z12.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z12.object({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),agentKey:z12.string().trim().min(1).max(120).optional(),threadId:z12.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z12.coerce.date().optional(),minCostUsd:z12.coerce.number().min(0).optional(),tracedOnly:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z12.object({limit:z12.coerce.number().int().min(1).max(500).default(200),reason:z12.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z12.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z12.object({maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z12.object({messageIndex:z12.coerce.number().int().min(0).optional(),maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),reason:z12.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z12.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z12.strictObject({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z12.string().trim().min(1).max(120).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z12.strictObject({organizationId:z12.string().trim().min(1).max(255).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.object({projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),reason:z12.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=z12.object({projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(200),reason:z12.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:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),reason:z12.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z12.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,limit:z12.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,sample:z12.coerce.number().int().min(1).max(25).default(10)})),OpsChatHistoryJudgeCalibrationInputSchema=z12.strictObject({reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z12.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z12.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z12.object({since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z12.coerce.number().min(0).optional(),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.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=z12.object({since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),model:z12.string().trim().min(1).max(120).optional(),provider:z12.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z12.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z12.boolean().default(!1),correlationLimit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.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=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z12.object({reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1),cursor:z12.string().min(1).optional(),batchSize:z12.number().int().min(1).max(100).default(50),concurrency:z12.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z12.object({reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1),organizationIds:z12.array(z12.string().min(1)).min(1).max(100).optional(),cursor:z12.string().min(1).optional(),batchSize:z12.number().int().min(1).max(100).default(50)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z12.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z12.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z12.discriminatedUnion("kind",[z12.object({kind:z12.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z12.object({kind:z12.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z12.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z12.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z12.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z12.object({migrationId:OpsMigrationIdSchema,projectEnv:z12.string().trim().min(1).max(255).default("main"),reason:z12.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z12.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z12.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z12.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z12.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z12.object({pattern:z12.string().min(1).max(300).optional(),limit:z12.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z12.object({pattern:z12.string().min(1).max(200),include:z12.string().min(1).max(300).optional(),caseInsensitive:z12.boolean().default(!1),maxMatches:z12.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z12.object({path:OpsProjectFilePathSchema,content:z12.string().max(256*1024),overwrite:z12.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z12.string().trim().length(64),consentReference:z12.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z12.intersection(OpsProjectOperationPlanInputSchema,z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z12.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=z12.strictObject({projectId:z12.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z12.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=z12.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=z12.strictObject({completeAggregate:z12.boolean(),truncated:z12.boolean().nullable(),sampled:z12.boolean().nullable(),pagination:z12.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z12.literal(!1),providerAsOf:z12.null(),projectFilter:z12.literal("exact properties.projectId equality"),environmentFilterSupported:z12.literal(!1),excludesMissingProjectId:z12.literal(!0),transport:z12.literal("server"),consentCoverage:z12.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z12.literal(!1)}),OpsPosthogCountsSchema=z12.array(z12.strictObject({event:z12.enum(OPS_POSTHOG_EVENTS),captureCount:z12.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z12.strictObject({schemaVersion:z12.literal(1),questionId:z12.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z12.uuid().nullable(),projectEnvironment:z12.literal("mixed_or_unrecorded"),window:z12.strictObject({from:z12.iso.datetime(),to:z12.iso.datetime(),bounds:z12.literal("[from,to)")}).nullable(),source:z12.literal("posthog"),sourceStatus:z12.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z12.iso.datetime(),auditId:z12.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=z12.object({reason:z12.string().trim().min(1).max(1e3),limit:z12.number().int().min(1).max(100).default(25),checkProvider:z12.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z12.object({branch:z12.string().trim().min(1).max(255),canaryPath:z12.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:z12.iso.datetime({offset:!0}),until:z12.iso.datetime({offset:!0}),reason:z12.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 z13}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z13.object({kind:z13.literal("say"),label:z13.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z13.string().min(1).max(240).optional(),message:z13.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z13.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z13.discriminatedUnion("command",[z13.object({kind:z13.literal("app"),command:z13.literal("publish")}).strict(),z13.object({kind:z13.literal("app"),command:z13.literal("connect"),integrationKey:z13.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z13.object({fallback:z13.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z13.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z13.literal("choices"),text:z13.string().max(500).optional(),actions:z13.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("entry"),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("asset"),assetId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("url"),url:z13.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z13.literal("table"),columns:z13.array(z13.object({label:z13.string().min(1).max(24)})).min(2).max(4),rows:z13.array(z13.object({cells:z13.array(z13.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:z13.literal("cards"),layout:z13.enum(["rail","stack"]).optional(),items:z13.array(z13.object({title:z13.string().min(1).max(60),subtitle:z13.string().min(1).max(120).optional(),imageUrl:z13.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z13.literal("entry"),label:z13.string().min(1).max(80),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120),path:z13.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z13.literal("assets"),items:z13.array(z13.object({url:z13.url({protocol:/^https$/}).max(2e3),alt:z13.string().min(1).max(120),label:z13.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z13.literal("callout"),title:z13.string().min(1).max(80),text:z13.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z13.literal("stat"),items:z13.array(z13.object({label:z13.string().min(1).max(24),value:z13.string().min(1).max(16),delta:z13.string().min(1).max(12).optional(),tone:z13.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z13.literal("chart"),unit:z13.string().min(1).max(12).optional(),points:z13.array(z13.object({label:z13.string().min(1).max(12),value:z13.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z13.literal("text"),placeholder:z13.string().min(1).max(120).optional(),multiline:z13.boolean().optional()}).strict(),ChatFormStepIdSchema=z13.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z13.object({id:ChatFormStepIdSchema,token:z13.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z13.string().trim().min(1).max(60),reason:z13.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z13.literal("capabilities"),items:z13.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z13.object({id:ChatFormStepIdSchema.optional(),question:z13.string().min(1).max(500),header:z13.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z13.boolean().optional(),recommended:z13.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"})),FormBlockSchema=BlockBaseSchema.extend({type:z13.literal("form"),steps:z13.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z13.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z13.object({stepId:ChatFormStepIdSchema.optional(),header:z13.string().min(1).max(25),question:z13.string().min(1).max(500),answer:z13.string().min(1),selectedLabels:z13.array(z13.string().min(1).max(120)).max(8),freeText:z13.string(),skipped:z13.boolean()}),ChatFormAnswerMetadataSchema=z13.object({toolCallId:z13.string().max(255).optional(),shortTitle:z13.string().max(80).optional(),questions:z13.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z13.string().min(1).max(255),partial:z13.boolean().optional()})}});import{z as z14}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=z14.object({shape:z14.enum(CHAT_PORTRAIT_SHAPES),eyes:z14.enum(CHAT_PORTRAIT_EYES),mouth:z14.enum(CHAT_PORTRAIT_MOUTHS),color:z14.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z15}from"zod";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}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(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
|
|
5
|
+
`)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.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=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z15.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z15.object({type:z15.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.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=z15.object({type:z15.literal("list"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema.optional(),label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("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=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z15.object({type:z15.literal("media"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z15.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z15.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49,params){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param)&¶ms?.[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 z17}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","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=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z17.object({name:z17.string().optional(),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z17.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z17.object({code:z17.literal("PUBLISH_UPGRADE_REQUIRED"),message:z17.string(),currentVersion:z17.number().int().positive(),targetVersion:z17.literal(4)}),ProjectLatestPublicationAttemptSchema=z17.object({publicationId:z17.uuid(),status:z17.enum(["queued","building","published","failed","canceled"]),failureCode:z17.string().nullable(),sourceBranch:z17.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z17.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional(),url:z17.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}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=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z18.object({sessionId:z18.uuid(),name:z18.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.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=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.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=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:BranchSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}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=z23.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative(),assets:z23.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200),assets:z23.array(z23.object({key:z23.string().min(1).max(512),name:z23.string().min(1).max(512),verb:z23.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z24}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=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z24.object({sessionId:z24.uuid(),branch:z24.string().min(1),targetBranch:z24.string().min(1),revision:z24.string().min(1),fingerprint:z24.string().min(1),source:z24.enum(["studio","slack","mcp"]),threadId:z24.uuid().nullable(),invocationId:z24.uuid().nullable(),conversationBranch:z24.string().nullable(),capturedAt:z24.string(),surfaces:z24.array(PerSurfaceDeltaSchema).optional(),counts:z24.record(z24.string(),z24.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z24.strictObject({sessionId:z24.uuid(),summary:z24.string().trim().min(1).max(240),targetBranch:z24.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z24.object({requested:z24.literal(!0),alreadyRequested:z24.boolean(),reviewId:z24.uuid(),reviewUrl:z24.url(),status:z24.literal("pending"),sessionId:z24.uuid(),branch:z24.string(),targetBranch:z24.string(),revision:z24.string(),savedRevision:z24.string(),fingerprint:z24.string(),visibility:z24.literal("user-visible"),retention:z24.literal("durable"),expiresAt:z24.null(),merged:z24.literal(!1),published:z24.literal(!1),links:z24.object({preview:z24.url(),changes:z24.url(),conversation:z24.url().nullable()})}),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}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=z25.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z25.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=z25.object({description:z25.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z25.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z25.array(z25.uuid()).optional()}),AgentQuestionSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),threadId:z25.uuid(),invocationId:z25.uuid(),agentKey:z25.string().min(1).max(120),anchorEnv:z25.string().min(1).max(64),retainedEnv:z25.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z25.string().min(1).nullable(),continuationInvocationId:z25.uuid().nullable(),askedAt:z25.coerce.date(),expiresAt:z25.coerce.date(),closedAt:z25.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z25.object({questionId:z25.uuid(),invocationId:z25.uuid(),askedAt:z25.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z25.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z25.object({question:AgentQuestionSchema,continuationInvocationId:z25.uuid(),deduped:z25.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z26}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=z26.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z26.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z26.enum(["secret_text"]),IntegrationCredentialUsageSchema=z26.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z26.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z26.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z26.object({mode:IntegrationAuthModeSchema,label:z26.string().min(1),description:z26.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z26.object({id:z26.string().min(1),label:z26.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z26.boolean()}),IntegrationToolDefinitionDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),description:z26.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z26.object({title:z26.string().min(1),description:z26.string().min(1),command:z26.string().min(1).optional()}),IntegrationInfoDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),type:z26.enum(["native","mcp"]).optional(),url:z26.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z26.array(IntegrationAuthModeDTOSchema),credentials:z26.array(IntegrationCredentialDefinitionDTOSchema),tools:z26.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z26.enum(["available","unavailable"]).optional(),connectionCapabilities:z26.object({customIdentityCreation:z26.boolean()}).optional(),recipes:z26.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),installed:z26.boolean(),enabled:z26.boolean(),setupState:z26.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z26.string().nullable(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),connectionStatus:z26.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),installedAt:z26.coerce.date().nullable(),updatedAt:z26.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),enabled:z26.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z26.string(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z26.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z26.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z26.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z26.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z26.object({id:z26.uuid(),organizationId:z26.string().min(1),integrationKey:z26.string().min(1),registrationId:z26.uuid().nullable(),alias:z26.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z26.string().min(1),externalAccountName:z26.string().nullable(),externalBotUserId:z26.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z26.array(z26.string()),connectedAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z26.boolean(),isDefault:z26.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z26.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z26.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z26.record(McpHeaderNameSchema,z26.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z26.object({alias:z26.string().min(1).max(120).optional(),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.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=z26.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z26.object({displayName:z26.string().trim().min(1).max(35),backgroundColor:z26.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z26.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),alias:z26.string().min(1).max(120),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}),z26.object({mode:z26.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z26.boolean().optional(),registrationId:z26.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=z26.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z26.union([z26.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z26.object({type:z26.literal("mcp"),name:z26.string().trim().min(1).max(120),url:z26.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z26.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z26.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z26.object({integrationKey:z26.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z26.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("oauth"),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),ReusableMcpServerAuthKindSchema=z26.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z26.object({id:z26.uuid(),name:z26.string().min(1),host:z26.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z26.string().min(1),availability:z26.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z26.object({query:z26.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z26.object({serverId:z26.uuid()}),LinearOAuthApplicationDistributionSchema=z26.enum(["private","public"]),OrganizationLinearAppDTOSchema=z26.object({id:z26.uuid(),displayName:z26.string().min(1),description:z26.string().nullable(),iconUrl:z26.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z26.enum(["active","revoked"]),connectionIds:z26.array(z26.uuid()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z26.object({appName:z26.string().trim().min(2).max(80),description:z26.string().trim().max(1e3).optional(),iconUrl:z26.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z26.object({projectId:z26.uuid(),registrationId:z26.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z26.object({integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),integrationKey:z26.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z26.object({mode:z26.literal("oauth"),integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),BindProjectChannelRequestSchema=z26.object({ref:z26.string().min(1),connectionAlias:z26.string().min(1).optional(),agentName:z26.string().min(1).max(160).nullable().optional(),force:z26.boolean().optional()}),ListProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1)}),SearchProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1),connectionAlias:z26.string().min(1),query:z26.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),connectionId:z26.uuid(),externalWorkspaceId:z26.string().min(1),externalChannelId:z26.string().min(1),externalChannelName:z26.string().nullable(),agentName:z26.string().nullable(),enabled:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z26.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z26.object({id:z26.string().min(1),name:z26.string().min(1),visibility:z26.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z26.string().min(1).nullable(),canMove:z26.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z26.object({markdown:z26.boolean().optional(),summary:z26.boolean().optional(),links:z26.boolean().optional(),branding:z26.boolean().optional(),images:z26.boolean().optional(),html:z26.union([z26.literal("cleaned"),z26.literal("raw"),z26.boolean()]).optional(),json:z26.union([z26.boolean(),z26.object({prompt:z26.string().min(1).max(1e4),schema:z26.record(z26.string(),z26.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z26.object({url:z26.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z26.object({query:z26.string().min(1),maxResults:z26.number().int().positive().max(20).optional(),sources:z26.array(z26.enum(["web","news","images"])).min(1).max(3).optional(),categories:z26.array(z26.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z26.enum(["hour","day","week","month","year"]).optional(),location:z26.string().min(1).max(160).optional(),country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(100).optional(),types:z26.array(z26.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),sources:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),passages:z26.number().int().min(1).max(5).optional(),skills:z26.literal("only").optional(),language:z26.string().min(1).optional(),topic:z26.string().min(1).optional(),license:z26.string().min(1).optional(),minStars:z26.number().int().min(0).optional(),maxStars:z26.number().int().min(0).optional(),archived:z26.boolean().optional(),fork:z26.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(500).optional(),authors:z26.array(z26.string().min(1)).min(1).optional(),categories:z26.array(z26.string().min(1)).min(1).optional(),from:z26.iso.date().optional(),to:z26.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),query:z26.string().min(1).max(500).optional(),maxPassages:z26.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),intent:z26.string().min(1).max(500),mode:z26.enum(["similar","citers","references"]).optional(),maxResults:z26.number().int().min(1).max(500).optional(),rerank:z26.boolean().optional(),anchors:z26.array(z26.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z26.object({url:z26.string().url(),search:z26.string().min(1).optional(),limit:z26.number().int().positive().max(200).optional(),includeSubdomains:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z26.object({url:z26.string().url(),limit:z26.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z26.object({text:z26.string().min(1).max(200).optional(),cron:z26.string().min(1).max(120).optional(),timezone:z26.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z26.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z26.union([z26.object({type:z26.enum(["scrape","crawl"]).default("scrape"),urls:z26.array(z26.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z26.object({type:z26.literal("search"),queries:z26.array(z26.string().min(1).max(256)).min(1).max(12),searchWindow:z26.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z26.number().int().min(1).max(50).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z26.object({name:z26.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),notification:z26.object({email:z26.object({enabled:z26.boolean().default(!0),recipients:z26.array(z26.string().email()).min(1).max(20),includeDiffs:z26.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=z26.object({monitorId:z26.string().uuid(),name:z26.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),status:z26.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z26.object({monitorId:z26.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z26.string().uuid()}),RunProjectIntegrationToolRequestSchema=z26.object({tool:z26.string().min(1),input:z26.record(z26.string(),z26.unknown()),connectionAlias:z26.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z26.object({provider:z26.string().min(1),providerCredits:z26.number().nonnegative().optional(),providerCostUsd:z26.number().nonnegative().optional(),requests:z26.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z26.object({credits:z26.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),json:z26.unknown().optional(),branding:z26.record(z26.string(),z26.unknown()).optional(),warning:z26.string().optional()}),FirecrawlSearchToolOutputSchema=z26.object({query:z26.string(),provider:z26.literal("firecrawl"),warning:z26.string().optional(),results:z26.array(z26.object({title:z26.string(),url:z26.string(),snippet:z26.string().optional(),content:z26.string().optional(),score:z26.number().optional(),publishedAt:z26.string().optional()}))}),FirecrawlResearchPaperSchema=z26.object({paperId:z26.string(),primaryId:z26.string().optional(),ids:z26.record(z26.string(),z26.array(z26.string())).optional(),title:z26.string().optional(),abstract:z26.string().optional(),score:z26.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z26.object({text:z26.string(),score:z26.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(z26.object({id:z26.string(),type:z26.string().min(1).optional(),url:z26.string(),title:z26.string().optional(),passages:z26.array(z26.object({text:z26.string()}).passthrough())}).passthrough()),coverage:z26.record(z26.string(),z26.string()).optional(),reranked:z26.boolean().optional(),repos:z26.array(z26.record(z26.string(),z26.unknown())).optional(),sources:z26.array(z26.record(z26.string(),z26.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),paper:z26.record(z26.string(),z26.unknown()),paperId:z26.string().optional(),query:z26.string().optional(),passages:z26.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema),poolSize:z26.number().int().nonnegative(),truncated:z26.boolean(),note:z26.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),count:z26.number(),links:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),description:z26.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),total:z26.number(),pages:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),warning:z26.string().optional()})),warning:z26.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z26.object({cron:z26.string().optional(),text:z26.string().optional(),timezone:z26.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z26.object({id:z26.string().optional(),type:z26.enum(["scrape","crawl","search"]).optional(),urls:z26.array(z26.string()).optional(),queries:z26.array(z26.string()).optional(),searchWindow:z26.string().optional(),maxResults:z26.number().optional(),includeDomains:z26.array(z26.string()).optional(),excludeDomains:z26.array(z26.string()).optional(),scrapeOptions:z26.record(z26.string(),z26.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z26.object({id:z26.string(),name:z26.string(),status:z26.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z26.string().nullable().optional(),lastRunAt:z26.string().nullable().optional(),currentCheckId:z26.string().nullable().optional(),targets:z26.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z26.string().nullable().optional(),judgeEnabled:z26.boolean().optional(),estimatedCreditsPerMonth:z26.number().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z26.object({id:z26.string(),monitorId:z26.string(),scheduledFor:z26.string().nullable().optional(),startedAt:z26.string().nullable().optional(),finishedAt:z26.string().nullable().optional(),estimatedCredits:z26.number().nullable().optional(),reservedCredits:z26.number().nullable().optional(),actualCredits:z26.number().nullable().optional(),billingStatus:z26.string().nullable().optional(),summary:z26.object({totalPages:z26.number().optional(),same:z26.number().optional(),changed:z26.number().optional(),new:z26.number().optional(),removed:z26.number().optional(),error:z26.number().optional()}).passthrough().optional(),error:z26.string().nullable().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitors:z26.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),deleted:z26.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),checks:z26.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),check:FirecrawlMonitorCheckOutputSchema,next:z26.string().optional()}),FirecrawlToolKeySchema=z26.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=z26.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),tool:z26.string().min(1),connectionAlias:z26.string().min(1).nullable().optional(),output:z26.record(z26.string(),z26.unknown()),executedAt:z26.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z26.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z26.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z26.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z26.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z26.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z26.array(ProjectChannelCandidateDTOSchema))}});import{z as z27}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=z27.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z27.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z27.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z27.object({userId:z27.string().min(1),name:z27.string(),email:z27.string().min(1),subscribed:z27.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z27.object({maxSubscribers:z27.number().int().positive(),subscriberCount:z27.number().int().nonnegative(),effectiveRecipientCount:z27.number().int().nonnegative(),currentUserSubscribed:z27.boolean(),candidates:z27.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z27.object({userIds:z27.array(z27.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z27.object({topic:UserManagedNotificationTopicSchema,enabled:z27.boolean(),source:z27.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z27.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z27.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z27.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z27.string().nullable(),maskedEmail:z27.string().min(1),applied:z27.boolean(),expiresAt:z27.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z27.object({scheduleId:z27.string().min(1),scheduleName:z27.string(),projectId:z27.string().min(1),projectName:z27.string(),env:z27.string().min(1)}),FollowedSchedulesSchema=z27.object({schedules:z27.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z28}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=z28.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=z28.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z28.uuid(),env:z28.string().min(1),name:z28.string().min(1),cron:z28.string().min(1),command:z28.string().min(1),secretKeys:z28.array(z28.string().min(1)),enabled:z28.boolean(),lastRunAt:z28.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z28.string().nullable(),suspendedAt:z28.coerce.date().nullable().optional(),suspensionReason:z28.string().nullable().optional(),overPolicyReasons:z28.array(z28.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120),cron:z28.string().min(1).max(120),command:z28.string().min(1).max(500),secretKeys:z28.array(ProjectSecretKeySchema).default([]),enabled:z28.boolean().optional()}),UpdateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120).optional(),cron:z28.string().min(1).max(120).optional(),command:z28.string().min(1).max(500).optional(),secretKeys:z28.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z28.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z28.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z28.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z28.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z28.object({maxRuns:z28.number().int().positive(),retentionDays:z28.number().int().positive().nullable(),outputRetentionDays:z28.number().int().positive(),maxOutputBytes:z28.number().int().positive()}),SchedulePolicyStateSchema=z28.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z28.object({code:z28.enum(["Free","PAYG","Premium","Pro"]),source:z28.enum(["cached_subscription","free_fallback"]),activeSchedules:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().nonnegative()}),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),concurrency:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().positive()}),compute:z28.object({settledMs:z28.number().int().nonnegative(),activeMs:z28.number().int().nonnegative(),reservedMs:z28.number().int().nonnegative().optional(),includedMs:z28.number().int().nonnegative(),remainingMs:z28.number().int().nonnegative(),resetsAt:z28.coerce.date()}),upgrade:z28.object({code:z28.literal("Pro"),activeSchedulesLimit:z28.number().int().positive(),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),maxConcurrentRuns:z28.number().int().positive(),computeIncludedMs:z28.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z28.array(z28.string())}),ProjectScheduleUsageSchema=z28.object({runCount:z28.number().int().nonnegative(),runsWithOutput:z28.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z28.object({id:z28.uuid(),scheduleId:z28.uuid(),projectId:z28.uuid(),env:z28.string().min(1),scheduleName:z28.string().min(1),command:z28.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z28.object({id:z28.string().min(1),name:z28.string().min(1)}).nullable(),queuedAt:z28.coerce.date(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),exitCode:z28.number().int().nullable(),errorCode:z28.string().nullable(),error:z28.string().nullable(),outputBytes:z28.number().int().nonnegative(),outputTruncated:z28.boolean(),outputExpiresAt:z28.coerce.date().nullable(),metadataExpiresAt:z28.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z28.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z28.coerce.date().nullable(),items:z28.array(z28.object({key:z28.string().min(1),updatedAt:z28.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z28.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z28.object({trigger:z28.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z28.object({limit:z28.coerce.number().int().min(1).max(100).default(25),cursor:z28.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z28.object({items:z28.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z28.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z28.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z28.object({items:z28.array(ProjectScheduleRunDTOSchema),nextCursor:z28.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z29}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=z29.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z29.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z29.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z29.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z29.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z29.discriminatedUnion("kind",[z29.object({kind:z29.literal("user"),userId:z29.string().min(1)}).strict(),z29.object({kind:z29.literal("agent"),agentKey:z29.string().min(1).max(120),agentId:z29.uuid().optional()}).strict(),z29.object({kind:z29.literal("system")}).strict()]),NotificationSummarySchema=z29.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z29.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z29.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z29.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z29.object({sessionId:z29.uuid(),branch:z29.string().min(1),targetBranch:z29.string().min(1),revision:z29.string().min(1),fingerprint:z29.string().min(1)}),NotificationPayloadSchema=z29.discriminatedUnion("topic",[z29.object({topic:z29.literal("agent_run_outcome"),threadId:z29.uuid(),invocationId:z29.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_retained_review"),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),proposalId:z29.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_conflict"),mergeId:z29.uuid(),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("publication_failed"),publicationId:z29.uuid(),sourceBranch:z29.string().trim().min(1).max(120),failureCode:z29.string().trim().min(1).max(64),failedAt:z29.iso.datetime(),firstPublication:z29.boolean()}).strict()]),NotificationEnvelopeSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),sourceKey:z29.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z29.literal(1),payload:NotificationPayloadSchema,createdAt:z29.coerce.date()}),NotificationDeliveryStateSchema=z29.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z29.object({id:z29.uuid(),notificationRecipientId:z29.uuid(),projectId:z29.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z29.number().int().nonnegative(),nextAttemptAt:z29.coerce.date().nullable(),lastAttemptAt:z29.coerce.date().nullable(),sentAt:z29.coerce.date().nullable(),failureCode:z29.string().max(80).nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),NotificationPreferenceSchema=z29.object({topic:WorkNotificationTopicSchema,channel:z29.literal("email"),enabled:z29.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z29.enum(["default","explicit"])})}});import{z as z30}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=z30.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=z30.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z30.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z30.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z30.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z30.object({enabled:z30.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z30.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z30.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z30.enum(["work_review","publishing","schedule"]),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z30.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),id:z30.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z30.literal("marketing"),name:z30.string(),description:z30.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z30.object({email:EmailNotificationPreferenceSchema,entries:z30.array(NotificationPreferenceEntrySchema),unavailableGroups:z30.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),enabled:z30.boolean()}).strict(),z30.object({kind:z30.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),enabled:z30.boolean()}).strict()])}});import{z as z31}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=z31.object({surface:SurfaceNameSchema,key:z31.string(),label:z31.string()}),InlineSchema=z31.object({text:z31.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z31.discriminatedUnion("type",[z31.object({type:z31.literal("paragraph"),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("preview"),ref:DiffRefSchema,caption:z31.string().optional()}),z31.object({type:z31.literal("code"),code:z31.string(),lang:z31.string().optional(),caption:z31.string().optional()}),z31.object({type:z31.literal("risk"),level:z31.enum(["warning","error"]),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("list"),items:z31.array(z31.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z31.object({headline:z31.string(),blocks:z31.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z31.object({summary:EnvDiffSummarySchema,fingerprint:z31.string(),generatedAt:z31.coerce.date(),cached:z31.boolean().optional(),credits:z31.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z32}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=z32.object({date:z32.string(),visitors:z32.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z32.object({key:z32.string(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z32.object({path:z32.string(),pageName:z32.string().nullable().optional(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z32.object({preset:z32.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z32.string(),requestedTo:z32.string(),effectiveFrom:z32.string(),effectiveTo:z32.string(),isRetentionLimited:z32.boolean(),groupBy:z32.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z32.object({date:z32.string(),content:z32.string(),updatedAt:z32.string(),updatedByUserId:z32.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z32.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z32.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative(),botPageviews:z32.number().int().nonnegative(),botVisitors:z32.number().int().nonnegative(),bounceRate:z32.number().min(0).max(100),viewsPerVisit:z32.number().nonnegative(),averageVisitDurationSeconds:z32.number().nonnegative(),visitorsSeries:z32.array(ProjectDailyVisitorsDTOSchema),topPages:z32.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z32.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z32.object({state:z32.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z32.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z33}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=z33.object({id:z33.string(),email:z33.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z33.coerce.date(),createdAt:z33.coerce.date(),inviterUserId:z33.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z33.object({id:z33.string(),token:z33.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z33.object({success:z33.boolean(),projectId:z33.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z34}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=z34.object({id:z34.string(),name:z34.string(),image:z34.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z34.object({count:z34.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z34.object({counts:z34.object({signed_up:z34.int(),activated:z34.int()}),credits:z34.object({total:z34.int(),earned:z34.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z34.email(),emailVerified:z34.boolean(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z35}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=z35.object({id:z35.string(),principalType:ProjectPrincipalTypeSchema,principalId:z35.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z35.coerce.date(),expiresAt:z35.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","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=z35.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z35.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z35.record(z35.string(),z35.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z35.object({access:z35.array(ProjectAccessItemDTOSchema),invites:z35.array(ProjectInviteDTOSchema),organization:z35.object({name:z35.string().nullable(),logo:z35.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z35.object({success:z35.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z35.object({success:z35.boolean(),projectId:z35.uuid()}))}});import{z as z36}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=z36.object({publicationStatus:PublicationStatusSchema,appUrl:z36.string().nullable(),lastPublishedAt:z36.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z37}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=z37.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z37.object({branch:BranchSchema,revision:z37.string().min(1).max(64).nullable(),generation:z37.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z37.url().nullable()})}});import{z as z38}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,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=z38.object({code:z38.literal("PREVIEW_UPGRADE_REQUIRED"),message:z38.string(),currentVersion:z38.number().int().positive(),targetVersion:z38.literal(4)}),PreviewBridgePackageSchema=z38.object({name:z38.string().min(1),version:z38.string().min(1)}),PreviewBridgeCapabilitySchema=z38.object({integrated:z38.boolean(),packages:z38.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z38.object({url:z38.url(),expiresAt:z38.iso.datetime().nullable(),source:z38.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z38.object({name:z38.string().min(1),locator:z38.string().min(1).optional(),source:z38.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z38.object({kind:z38.literal("dependency_build_scripts_blocked"),packageManager:z38.enum(["pnpm","yarn","bun"]),packages:z38.array(z38.string()),targets:z38.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z38.string(),approvalKey:z38.string(),command:z38.string().optional(),approval:z38.object({id:z38.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z38.object({code:z38.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z38.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z38.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z38.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z38.object({message:z38.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z38.number().int().optional().catch(void 0),logTail:z38.array(z38.string()).optional().catch(void 0),logTailTruncated:z38.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z38.object({approvalId:z38.uuid()}),PreviewInstallPolicyApprovalEventSchema=z38.discriminatedUnion("type",[z38.object({type:z38.literal("progress"),step:z38.enum(["approval","install","restart","readiness"]),message:z38.string()}),z38.object({type:z38.literal("approved")}),z38.object({type:z38.literal("complete")}),z38.object({type:z38.literal("error"),code:z38.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z38.string()})])}});import{z as z39}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z39.string(),slug:z39.string().nullable(),logo:z39.string().nullable(),metadata:z39.record(z39.string(),z39.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z39.object({id:z39.string(),name:z39.string(),email:z39.email(),image:z39.string().nullable()}),OrganizationMemberDTOSchema=z39.object({id:z39.string(),userId:z39.string(),organizationId:z39.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z39.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z40}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=z40.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z40.object({reason:CancellationReasonCodeSchema,details:z40.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z40.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z40.object({offerVersion:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),renewsOn:z40.string()}),PlanMigrationPreviewDTOSchema=z40.object({currency:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),startsAt:z40.string(),renewsAt:z40.string(),nextRenewalAmount:z40.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z40.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z40.object({id:z40.string(),organizationId:z40.string(),legacySubscriptionId:z40.string(),offeredPlanCode:z40.string(),offeredPlanName:z40.string(),offeredPriceAmount:z40.number(),offeredCurrency:z40.string(),offerVersion:z40.string(),state:PlanMigrationStateSchema,checkoutToken:z40.string().nullable(),deadlineAt:z40.string(),transitions:z40.array(z40.object({event:z40.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z40.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z40.object({included:z40.number().optional(),unitPrice:z40.number().optional(),dailyCap:z40.number().nullable().optional()}),EntitlementsDTOSchema=z40.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z40.object({retentionDays:z40.number().int().positive(),canUseExtendedDateRanges:z40.boolean()}).optional(),history:z40.object({retentionDays:z40.number().int().positive()}).optional(),members:z40.object({canInvite:z40.boolean(),maxMembers:z40.number().int().positive().nullable()}).optional(),projects:z40.object({maxProjects:z40.number().int().positive().nullable()}).optional(),domains:z40.object({canUseCustomDomains:z40.boolean(),maxDomains:z40.number().int().nonnegative().nullable()}).optional(),media_storage:z40.object({limitBytes:z40.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z40.object({usedBytes:z40.number().int().nonnegative().nullable(),limitBytes:z40.number().int().nonnegative().nullable(),state:z40.enum(["ready","unavailable"]),measuredAt:z40.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z40.object({toPlanCode:TemplateCodeSchema,effectiveAt:z40.string(),scheduledAt:z40.string().nullable()}),AutomaticSpendStopDTOSchema=z40.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z40.string(),spendStopped:z40.boolean(),settlementEndsAt:z40.string()}),HostingOverageStatusDTOSchema=z40.object({state:z40.enum(["ready","unavailable"]),planCode:z40.string(),overageAvailable:z40.boolean(),overageEnabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().nullable(),periodStart:z40.iso.datetime().nullable(),periodEnd:z40.iso.datetime().nullable(),usedBytes:z40.number().nonnegative().nullable(),includedBytes:z40.number().nonnegative().nullable(),overageBytes:z40.number().nonnegative(),currentOverageAmountMicros:z40.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z40.number().nonnegative().nullable(),currency:z40.string().nullable(),status:z40.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z40.object({enabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z40.object({id:z40.string(),external_id:z40.string(),customerId:z40.string(),planId:z40.string(),planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]),currentPeriod:z40.object({start:z40.string(),end:z40.string().nullable()}),cancelAt:z40.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z40.string(),nextPaymentAt:z40.string().nullable(),baseAmount:z40.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z40.object({totalCap:z40.number(),dailyCap:z40.number(),usedTotal:z40.number()}),CreditBalanceDTOSchema=z40.object({total:z40.number(),base:z40.number(),dailyBase:z40.number(),purchases:z40.number(),awards:z40.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z40.object({total:z40.number(),nearLimit:z40.boolean(),canChat:z40.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z40.object({dailyFreeAvailable:z40.number(),monthlyAvailable:z40.number(),purchasedAvailable:z40.number(),awardedAvailable:z40.number()}),ProjectDailyCreditAllowanceDTOSchema=z40.object({periodCap:z40.number(),dailyGrant:z40.number(),usedThisPeriod:z40.number(),remainingThisPeriod:z40.number()}),ProjectCreditBalanceDTOSchema=z40.object({projectId:z40.uuid(),organizationId:z40.string(),balance:z40.object({totalAvailable:z40.number(),nearLimit:z40.boolean(),canUseAi:z40.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z40.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().nonnegative(),refillAmountUsd:z40.number().nonnegative()}),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().nonnegative().nullable(),refillAmountUsd:z40.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().min(.01).multipleOf(.01),refillAmountUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z40.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z40.object({planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]).nullable(),canPurchase:z40.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z40.number().int().positive(),minAmountUsd:z40.number().positive(),maxAmountUsd:z40.number().positive(),rateToken:z40.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z40.object({amountUsd:z40.number(),idempotencyKey:z40.string().trim().min(8).max(120),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z40.object({invoiceId:z40.string(),newBalance:z40.int(),creditCount:z40.int(),amountUsd:z40.number(),creditsPerDollar:z40.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z40.object({url:z40.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z40.object({id:z40.string(),number:z40.string().nullable(),status:z40.string(),amountDue:z40.int(),currency:z40.string(),issuedAt:z40.string().nullable(),hostedInvoiceUrl:z40.string().nullable()}),PaymentRecoveryDTOSchema=z40.discriminatedUnion("status",[z40.object({status:z40.literal("eligible"),checkedAt:z40.string()}),z40.object({status:z40.literal("recovery_required"),checkedAt:z40.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z40.int().min(1)}),z40.object({status:z40.literal("unavailable"),checkedAt:z40.string(),reason:z40.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 z41}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=z41.object({brand:z41.string(),last4:z41.string(),exp:z41.string(),isDefault:z41.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z42}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=z42.string().superRefine((path49,ctx)=>{let segments=path49.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=z42.object({type:z42.literal("renameField"),contentType:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z42.object({enabled:z42.boolean()}).strict(),ContentFieldGroupSchema=z42.object({id:z42.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z42.string().min(1).max(255),default:z42.boolean().optional()}).strict(),ContentTypeDTOSchema=z42.object({id:z42.string(),name:z42.string(),label:z42.string(),isSingleton:z42.boolean(),i18n:ContentTypeI18nSchema,groups:z42.array(ContentFieldGroupSchema).default([]),fields:z42.record(z42.string(),FieldDefinitionSchema),createdAt:z42.string(),updatedAt:z42.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z42.object({contentTypes:z42.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z42.object({id:z42.string(),entryId:z42.string(),documentId:z42.string(),slug:z42.string(),locale:z42.string().optional(),createdAt:z42.string(),updatedAt:z42.string(),__fimo:z42.object({contentType:z42.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({limit:z42.number(),offset:z42.number(),total:z42.number(),hasMore:z42.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z42.object({contentType:z42.string(),count:z42.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z42.object({counts:z42.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z42.object({count:z42.number().int().nonnegative(),sourceLocale:z42.string(),targetLocale:z42.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z42.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z42.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z42.union([z42.string(),z42.number(),z42.boolean(),z42.null()]),entryWhereOperatorSchema=z42.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z42.array(entryWhereScalarSchema).optional(),$nin:z42.array(entryWhereScalarSchema).optional(),$contains:z42.string().optional(),$startsWith:z42.string().optional(),$null:z42.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z42.object({data:z42.record(z42.string(),z42.unknown()),locale:z42.string().min(1).optional(),documentId:z42.uuid().optional()}),entryIdsSchema=z42.array(z42.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z42.object({sql:z42.string().min(1)}),BulkCreateEntriesRequestSchema=z42.object({entries:z42.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z42.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z42.object({updates:z42.array(z42.object({id:z42.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,locale:z42.string().min(1).optional()}),z42.object({where:EntryWhereSchema,locale:z42.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z42.object({data:z42.array(z42.record(z42.string(),z42.unknown())),meta:z42.object({rowCount:z42.number().int().nonnegative(),truncated:z42.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({created:z42.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({updated:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({deleted:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z43}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z43.object({index:z43.number().int().nonnegative(),contentType:z43.string(),field:z43.string(),value:z43.string(),against:z43.enum(["stored","batch"]),ownerDocumentId:z43.uuid().optional(),ownerIndex:z43.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z43.object({code:z43.literal("unique_conflict"),message:z43.string(),conflicts:z43.array(UniqueConflictSchema),truncated:z43.boolean().optional()})}});import{z as z44}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=z44.object({kind:z44.literal("unique_conflict"),contentType:z44.string(),field:z44.string(),value:z44.string(),documentCount:z44.number().int().positive(),documentIds:z44.array(z44.uuid()),documentIdsTruncated:z44.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z44.object({code:z44.literal("schema_transition_rejected"),message:z44.string(),issues:z44.array(SchemaTransitionIssueSchema),truncated:z44.boolean().optional()})}});import{z as z45}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=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z45.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z45.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z45.object({field:CmsFieldNameSchema,direction:z45.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z45.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z45.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z45.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z45.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z45.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z46}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=z46.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z47}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=z47.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z47.object({event:ClientTrackedEventSchema,properties:z47.record(z47.string(),z47.unknown()).default({})})}});import{z as z48}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=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z48.object({error:z48.string(),code:z48.literal("media_storage_limit_exceeded"),usedBytes:z48.number().int().nonnegative(),limitBytes:z48.number().int().positive(),incomingBytes:z48.number().int().nonnegative()}),AssetReferenceScopeSchema=z48.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z48.object({assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z48.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z48.object({totalFiles:z48.number().int().nonnegative(),checkedFiles:z48.number().int().nonnegative(),limit:z48.number().int().positive()}),AssetReferenceFindingDTOSchema=z48.object({assetId:z48.uuid(),entryId:z48.string(),documentId:z48.string(),contentType:z48.string(),locale:z48.string().nullable(),slug:z48.string(),fieldPath:z48.string()}),AssetReferenceScopeResultDTOSchema=z48.object({scope:AssetReferenceScopeSchema,label:z48.string(),state:z48.enum(["available","not-published","failed"]),coverage:z48.enum(["complete","partial","failed"]),referenceCount:z48.number().int().nonnegative().optional(),codeReferenceCount:z48.number().int().nonnegative().optional(),referencedAssetIds:z48.array(z48.uuid()).optional(),references:z48.array(AssetReferenceFindingDTOSchema),reason:z48.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z48.discriminatedUnion("type",[z48.object({type:z48.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z48.object({type:z48.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z48.object({type:z48.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z48.object({replacementAssetId:z48.uuid()}),AssetReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),entriesChanged:z48.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),filesChanged:z48.number().int().nonnegative(),commitSha:z48.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z48.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=z48.object({error:z48.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z48.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=z48.object({intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z48.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=z48.object({id:z48.uuid(),intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()),replacementAssetId:z48.uuid().nullable(),expiresAt:z48.iso.datetime(),undoable:z48.boolean(),requestedByMe:z48.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z48.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z48.object({error:z48.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z51.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z51.object({minLength:z51.number().optional(),maxLength:z51.number().optional(),min:z51.number().optional(),max:z51.number().optional(),pattern:z51.string().optional(),maxFileSize:z51.number().optional(),accept:z51.array(z51.string()).optional()}),FormFieldSchema=z51.object({type:FormFieldTypeSchema,label:z51.string(),placeholder:z51.string().optional(),required:z51.boolean().optional(),defaultValue:z51.string().optional(),options:z51.array(z51.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z51.record(z51.string(),FormFieldSchema),FormContentSchema=z51.object({name:z51.string().min(1).max(255),label:z51.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 z52}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineModelSchema,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=z52.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z52.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z52.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z52.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z52.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z52.string().trim().min(1).max(120),ChatRoutineEventTriggerDTOSchema=z52.object({text:z52.string(),title:z52.string(),explanation:z52.string()}),ChatRoutineEventTriggerInputSchema=z52.object({text:z52.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z52.object({manual:z52.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z52.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z52.object({message:z52.string().trim().min(1).max(2e4),decision:z52.boolean().optional(),incomplete:z52.boolean().optional()}).refine(report=>!(report.decision===!0&&report.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z52.object({id:z52.string().uuid(),threadId:z52.string().uuid(),runThreadId:z52.string().uuid(),name:z52.string(),instructions:z52.string(),triggers:ChatRoutineTriggersDTOSchema,model:z52.string(),modelIsDefault:z52.boolean(),paused:z52.boolean(),nextRunAt:z52.string().nullable(),lastRunAt:z52.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z52.string().nullable(),createdAt:z52.string(),updatedAt:z52.string()}),ChatRoutineListDTOSchema=z52.object({routines:z52.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z52.object({usedMs:z52.number().int().min(0),includedMs:z52.number().int().min(0),periodStart:z52.string(),periodEnd:z52.string(),stopsAtIncluded:z52.boolean(),canStart:z52.boolean(),canPayOverage:z52.boolean(),overageRateMicrosPerHour:z52.number().int().nullable(),billedMs:z52.number().int().min(0),billedMicros:z52.number().int().min(0)}),ChatRoutineCreateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional()}),ChatRoutineUpdateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),paused:z52.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z52.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown"]),ChatRoutineRefusalDTOSchema=z52.object({message:z52.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z52.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z52.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z52.object({kind:z52.enum(["person","agent"]),name:z52.string().nullable()}),ChatRoutineRunDTOSchema=z52.object({messageId:z52.string().uuid(),invocationId:z52.string().uuid().nullable(),startedAt:z52.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z52.string().nullable(),events:z52.number().int().min(1),durationMs:z52.number().int().min(0).nullable(),credits:z52.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z52.object({runs:z52.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z52.object({message:z52.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z52.object({kind:z52.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z52.string().uuid().nullable()})}});import{z as z53}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,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_project_dto();ChatMessageListDTOSchema=z53.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z53.object({items:z53.array(ProjectMessagePublicDTOSchema),nextCursor:z53.string().nullable()}),ChatLiveTurnDTOSchema=z53.object({invocationId:z53.string(),step:z53.enum(["preparing","working","compacting","merging"]),startedAt:z53.string(),continuesInvocationId:z53.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z53.object({threadId:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z53.object({kind:z53.enum(["person","agent","routine","system"]),id:z53.string().nullable()}),ChatThreadMessageDTOSchema=z53.object({id:z53.string(),role:z53.enum(["user","assistant"]),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),versionId:z53.string().nullable().optional(),createdAt:z53.date().transform(value=>value.toISOString()),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z53.string().nullable().optional(),invocationStatus:z53.string().nullable().optional(),invocationTerminalReason:z53.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z53.object({id:z53.string(),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z53.boolean(),queuedAt:z53.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z53.object({type:z53.literal("merge_conflict"),merge:z53.object({mergeId:z53.string().uuid(),projectId:z53.string(),fromBranch:z53.string(),toBranch:z53.string()}),publishAfterMerge:z53.boolean()}),ChatThreadMessagesPageDTOSchema=z53.object({threadId:z53.string().nullable(),title:z53.string().nullable(),messages:z53.array(ChatThreadMessageDTOSchema),nextCursor:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z53.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z53.boolean().optional(),queueWaitUntil:z53.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z53.object({kind:z53.literal("replay"),threadId:z53.string(),userMessageId:z53.string()}),ChatQueuedOutcomeDTOSchema=z53.object({kind:z53.literal("queued"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatBusyOutcomeDTOSchema=z53.object({kind:z53.literal("busy"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatRefusedOutcomeDTOSchema=z53.object({kind:z53.literal("refused"),threadId:z53.string(),userMessageId:z53.string(),refusedInvocationId:z53.string(),terminalReason:z53.string()}),ChatNonStreamingOutcomeDTOSchema=z53.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z53.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z53.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z53.object({quietRuns:z53.number().int().nonnegative(),since:z53.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z53.string().nullable(),nextRunAt:z53.string().nullable()}),ProjectChatDescriptionSchema=z53.string().trim().max(2e3),ProjectChatDTOSchema=z53.object({id:z53.string().uuid(),kind:ProjectChatKindSchema,title:z53.string().nullable(),description:z53.string().nullable(),template:z53.string().nullable(),parentThreadId:z53.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z53.string(),lastMessageAt:z53.string().nullable(),preview:z53.string().nullable(),running:z53.boolean(),awaitingAnswer:z53.boolean(),unread:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z53.object({chats:z53.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z53.object({id:z53.string().uuid()}),ProjectChatTitleSchema=z53.string().trim().min(1).max(120),ProjectChatCreateSchema=z53.object({id:z53.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z53.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema}).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"),ProjectChatUpdateSchema=z53.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.portrait!==void 0,"Set a title, a description or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z53.object({cron:z53.string()}),ChatTemplateRoutineDTOSchema=z53.object({name:z53.string(),instructions:z53.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable()}),ChatTemplateDTOSchema=z53.object({id:z53.string(),name:z53.string(),summary:z53.string(),description:z53.string(),portrait:ChatPortraitSchema,routines:z53.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z53.object({templates:z53.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z53.object({read:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.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 z54}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=z54.object({url:z54.string().url(),key:z54.string(),size:z54.number(),contentType:z54.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z55}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=z55.object({canAccess:z55.boolean(),permissions:z55.record(z55.string(),z55.boolean()),role:z55.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z56}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:z56.string().trim().default(""),sort:z56.enum(["recent","name","relevance"]).default("recent"),category:z56.string().optional()})}});import{z as z57}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=z57.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z57.enum(["fimo","external"]),PaymentStatusSchema=z57.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z57.object({id:z57.string().uuid(),domain:z57.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z57.boolean(),price:z57.number().int().nullable(),renewalPrice:z57.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z57.string().nullable(),failureReason:z57.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z57.object({domain:z57.string(),available:z57.boolean(),premium:z57.boolean(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),purchaseType:z57.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z57.object({domain:z57.string(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),premium:z57.boolean(),allowedYears:z57.array(z57.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z57.object({firstName:z57.string().max(100),lastName:z57.string().max(100),companyName:z57.string().max(100).optional(),address1:z57.string().max(255),address2:z57.string().max(255).optional(),city:z57.string().max(100),state:z57.string().max(100),zip:z57.string().max(20),country:z57.string().max(2),phone:z57.string().max(30),email:z57.union([z57.string().email().max(255),z57.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z57.object({firstName:z57.string().min(1).max(100),lastName:z57.string().min(1).max(100),companyName:z57.string().max(100).optional(),address1:z57.string().min(1).max(255),address2:z57.string().max(255).optional(),city:z57.string().min(1).max(100),state:z57.string().min(1).max(100),zip:z57.string().min(1).max(20),country:z57.string().min(1).max(2),phone:z57.string().min(1).max(30),email:z57.string().email().max(255)}),SearchDomainsRequestSchema=z57.object({keyword:z57.string().min(1).max(100),tldFilter:z57.array(z57.string()).optional()}),CheckAvailabilityRequestSchema=z57.object({domains:z57.array(z57.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=z57.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z57.object({domain:DomainNameSchema,years:z57.number().int().min(1).max(10).optional().default(3),autoRenew:z57.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z57.object({autoRenew:z57.boolean().optional()}),RenewDomainRequestSchema=z57.object({years:z57.number().int().min(1).max(10).optional().default(1),autoRenew:z57.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z57.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z57.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z57.object({verified:z57.boolean(),email:z57.string().nullable(),verifyBy:z57.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z58}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z58.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=z58.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=z58.object({txtName:z58.string().nullable().optional(),txtValue:z58.string().nullable().optional(),httpUrl:z58.string().nullable().optional(),httpBody:z58.string().nullable().optional(),cname:z58.string().nullable().optional(),cnameTarget:z58.string().nullable().optional()}),SSLValidationErrorSchema=z58.object({message:z58.string()}),OwnershipVerificationSchema=z58.object({type:z58.string(),name:z58.string(),value:z58.string()}),ProjectDomainSSLDTOSchema=z58.object({status:z58.string(),method:z58.string().nullable(),type:z58.string().nullable(),validationRecords:z58.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z58.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z58.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z58.enum(["subdomain","apex"]),RedirectConfigSchema=z58.object({type:z58.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z58.string()}).nullable().optional(),ProjectDomainDTOSchema=z58.object({id:z58.string(),hostname:z58.string(),status:z58.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z58.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z58.string(),scdCnameTarget:z58.string().optional(),apexTargets:z58.array(z58.string()),dnsAutoConfigured:z58.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z58.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z58.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z58.object({hostname:z58.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:z58.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z58.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z58.object({success:z58.boolean(),hostname:z58.string()}))}});import{z as z59}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=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z59.object({available:z59.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z59.object({slug:z59.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z59.object({subdomain:z59.string(),subdomainUpdatedAt:z59.coerce.date()})),SubdomainSuggestionsQuerySchema=z59.object({base:z59.string().max(100).optional(),max:z59.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z59.object({suggestions:z59.array(z59.string())}))}});import{z as z60}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=z60.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z60.object({code:ProjectTransferBlockerCodeSchema,message:z60.string(),count:z60.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z60.object({targetOrganizationId:z60.string().min(1)}),ProjectTransferResultDTO=createDTO(z60.object({projectId:z60.string(),sourceOrganizationId:z60.string(),targetOrganizationId:z60.string(),movedThreads:z60.number().int().nonnegative(),revokedInvites:z60.number().int().nonnegative(),revokedGrants:z60.number().int().nonnegative(),preservedGrants:z60.number().int().nonnegative(),warnings:z60.array(z60.string())}))}});import{z as z61}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=z61.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z61.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=z61.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z61.object({displayName:z61.string().trim().min(1).max(80),machineId:z61.string().trim().min(1).max(128).optional(),cliVersion:z61.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z61.object({ttlHours:z61.number().int().positive(),lockedFeatures:z61.array(UnclaimedLockedFeatureSchema),media:z61.object({totalBytes:z61.number().int().nonnegative(),fileBytes:z61.number().int().positive(),maxFiles:z61.number().int().nonnegative(),mimeTypes:z61.array(z61.string())}),database:z61.object({storageBytes:z61.number().int().positive(),computeSeconds:z61.number().int().positive(),maxComputeUnits:z61.number().positive()})}),UnclaimedProjectClaimSchema=z61.object({url:z61.string().url(),expiresAt:z61.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z61.object({project:ProjectDTOSchema,token:z61.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z61.object({state:UnclaimedClaimStateSchema,displayName:z61.string().nullable(),expiresAt:z61.coerce.date().nullable(),projectId:z61.string().nullable()})),UnclaimedClaimSecretSchema=z61.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z61.object({secrets:z61.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z61.object({claims:z61.array(z61.object({state:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema,organizationId:z61.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z61.object({projectId:z61.string(),organizationId:z61.string()})),ProjectTokenSelfDTO=createDTO(z61.object({kind:z61.literal("project_token"),projectId:z61.string(),projectName:z61.string(),displayName:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable(),tokenExpiresAt:z61.coerce.date().nullable()}))}});import{z as z62}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=z62.object({translated:z62.number().int().nonnegative(),total:z62.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z62.object({locale:z62.string(),isDefault:z62.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z62.object({defaultLocale:z62.string(),locales:z62.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z62.object({locale:z62.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z62.object({locale:z62.string().min(1).max(40)}),ProjectLocaleMutationSchema=z62.object({locale:z62.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z62.object({locale:z62.string(),entriesDeleted:z62.number().int().nonnegative(),labelsDeleted:z62.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z63}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=z63.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z63.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=z63.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z63.number(),credits:z63.number().optional(),billingMode:z63.enum(["fimo-credits","provider-account"]).optional(),confidence:z63.enum(["exact","estimated","metered"]),basis:z63.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z64}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=z64.object({options:z64.record(z64.string(),z64.unknown()),name:z64.string().optional(),parentId:z64.string().nullable().optional(),altText:z64.string().optional(),caption:z64.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z64.string().min(1).optional(),model:z64.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=z64.object({jobId:z64.string(),status:z64.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z64.string().nullable().optional(),credits:z64.number().optional(),costUsd:z64.number().optional(),billingMode:z64.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z64.object({error:z64.string(),code:z64.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:z64.array(GenerationTaskIdSchema).optional(),availableModels:z64.array(z64.string()).optional(),issues:z64.array(z64.unknown()).optional()})}});import{z as z65}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=z65.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z65.object({name:z65.string(),key:z65.string(),description:z65.string(),type:FlagTypeSchema,required:z65.boolean(),defaultValue:z65.unknown().optional(),enumValues:z65.array(z65.string()).optional(),isArray:z65.boolean()}),AssetModelPriceSchema=z65.object({unitPrice:z65.number(),unit:z65.string(),confidence:z65.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z65.object({id:z65.string(),shortName:z65.string(),provider:z65.string(),source:z65.string(),modality:z65.enum(["image","video","audio"]),tags:z65.array(z65.string()),displayName:z65.string(),description:z65.string(),flags:z65.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z65.object({model:z65.string(),costUsd:z65.number(),credits:z65.number(),billingMode:z65.enum(["fimo-credits","provider-account"]),confidence:z65.enum(["exact","estimated","metered"]),basis:z65.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z66}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=z66.object({tourId:z66.string(),version:z66.string(),status:z66.string(),completedAt:z66.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z66.array(UserTourDTOSchema))}});import{z as z67}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=z67.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z67.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z67.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z67.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z67.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z67.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z67.enum(["user","agent","system"]),SupportReportTagSchema=z67.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z67.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z67.object({organization:z67.object({id:z67.string().trim().min(1).max(255),name:z67.string().trim().max(240).optional()}),project:z67.object({id:z67.uuid(),name:z67.string().trim().max(240).optional(),createdAt:z67.coerce.date().optional()}).optional(),environment:z67.string().trim().max(255).optional(),clientVersion:z67.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z67.object({message:z67.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z67.string().trim().max(200).optional(),limit:z67.coerce.number().int().min(1).max(100).default(50),offset:z67.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z67.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z67.uuid().nullable().optional(),note:z67.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=z67.object({message:z67.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z67.object({kind:SupportReportLinkKindSchema,label:z67.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z67.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z67.object({kind:SupportReportActorKindSchema,id:z67.string().nullable(),name:z67.string().nullable()}),SupportReportLinkDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportLinkKindSchema,label:z67.string(),url:SupportReportHttpUrlSchema,externalId:z67.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportEventKindSchema,body:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()),actor:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z67.object({id:z67.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z67.array(z67.string()),source:SupportReportSourceSchema,message:z67.string(),reporter:z67.object({id:z67.string().nullable(),name:z67.string().nullable(),email:z67.string().nullable()}),organization:z67.object({id:z67.string().nullable(),name:z67.string()}),project:z67.object({id:z67.uuid().nullable(),name:z67.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z67.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z67.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}).nullable(),duplicateOfReportId:z67.uuid().nullable(),resolvedAt:z67.coerce.date().nullable(),createdAt:z67.coerce.date(),updatedAt:z67.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z67.string().nullable(),clientVersion:z67.string().nullable(),links:z67.array(SupportReportLinkDTOSchema),events:z67.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z67.object({reports:z67.array(SupportReportSummaryDTOSchema),total:z67.number().int().nonnegative(),statusCounts:z67.object({new:z67.number().int().nonnegative(),in_progress:z67.number().int().nonnegative(),waiting:z67.number().int().nonnegative(),resolved:z67.number().int().nonnegative(),duplicate:z67.number().int().nonnegative(),irrelevant:z67.number().int().nonnegative(),ignored:z67.number().int().nonnegative()}),limit:z67.number().int().positive(),offset:z67.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z67.object({id:z67.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z67.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z68}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=z68.iso.datetime({offset:!0}).pipe(z68.coerce.date()),OpsRecentChatInputSchema=z68.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z68.string().trim().min(1).max(255).optional(),limit:z68.coerce.number().int().min(1).max(200).default(100),cursor:z68.string().trim().min(1).max(2e3).optional(),slim:z68.boolean().default(!0),reason:z68.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=z68.object({id:z68.string(),threadId:z68.string(),providerMessageId:z68.string().nullable(),invocationId:z68.string().nullable(),env:z68.string().nullable(),role:z68.string(),parts:z68.array(z68.record(z68.string(),z68.unknown())),metadata:z68.object({status:z68.string().optional(),traceUrl:z68.string().optional(),externalFileChanges:z68.array(z68.unknown()).optional()}),stats:z68.object({toolCount:z68.number().int().nonnegative(),failedToolCount:z68.number().int().nonnegative()}),createdAt:z68.iso.datetime({offset:!0}),project:z68.object({id:z68.string(),name:z68.string(),displayName:z68.string().nullable(),organizationId:z68.string().nullable()})}),OpsRecentChatResponseSchema=z68.object({target:z68.object({backendProfile:OpsBackendProfileSchema,projectEnv:z68.string().nullable()}),window:z68.object({from:z68.iso.datetime({offset:!0}),to:z68.iso.datetime({offset:!0})}),messages:z68.object({items:z68.array(OpsRecentChatMessageSchema),nextCursor:z68.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z69}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=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z69.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z69.literal(!1),reason:z69.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z70}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=z70.object({packageManager:z70.string().trim().min(1).max(200).nullable(),trackedLockfiles:z70.array(z70.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z70.string().trim().min(1)}),OpsProjectPackageManagerSchema=z70.object({target:z70.object({backendProfile:OpsBackendProfileSchema,projectId:z70.uuid(),projectEnv:z70.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z71}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:z71.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z71.union([z71.object({name:z71.string().trim().min(1).max(120),description:z71.string().trim().min(1).max(2e3)}).strict(),z71.object({template:z71.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z71.object({agent:OpsAgentChatAgentSpecSchema,routines:z71.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:z71.string().trim().min(1).max(1e3),dryRun:z71.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z71.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z71.object({id:z71.string().uuid().nullable(),name:z71.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z71.string().nullable(),paused:z71.boolean(),outcome:z71.enum(["created","would_create"]),source:z71.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z71.object({target:z71.object({backendProfile:OpsBackendProfileSchema,projectId:z71.string().uuid()}),dryRun:z71.boolean(),applied:z71.boolean(),createdBy:z71.object({userId:z71.string()}),agent:z71.object({id:z71.string().uuid().nullable(),title:z71.string(),template:z71.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z71.array(OpsAgentChatRoutineResultSchema),skipped:z71.array(z71.object({name:z71.string(),reason:z71.literal("routine_exists")})),refused:z71.array(z71.object({name:z71.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z72}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=z72.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z72.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z72.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z72.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z72.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z72.object({reason:WebhookEntryChangeReasonSchema,operationId:z72.string().optional(),batch:z72.object({index:z72.number().int().positive(),total:z72.number().int().positive()}).optional(),changes:z72.array(z72.object({action:WebhookEntryChangeActionSchema,contentType:z72.string(),id:z72.string(),documentId:z72.string(),locale:z72.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z72.object({form:z72.object({id:z72.string(),label:z72.string()}),submission:z72.object({id:z72.string(),data:z72.record(z72.string(),z72.unknown()),submittedAt:z72.string()})}),PublishStartedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("publishing"),startedAt:z72.string()})}),PublishSucceededWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("published"),url:z72.string(),publishedAt:z72.string(),firstPublish:z72.boolean()})}),PublishFailedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("failed"),reason:z72.string()})}),PublishUnpublishedWebhookEventDataSchema=z72.object({publication:z72.object({previousUrl:z72.string(),unpublishedAt:z72.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z72.object({report:z72.object({weekStart:z72.string(),weekEnd:z72.string(),pageviews:z72.number(),visitors:z72.number(),previousPageviews:z72.number(),previousVisitors:z72.number()})}),MediaAssetWebhookEventDataSchema=z72.object({id:z72.string().nullable(),name:z72.string().nullable(),type:z72.string(),mimeType:z72.string().nullable(),fileSize:z72.number().nullable()}),MediaUploadedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("updated")}),MediaDeletedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string()})}),LabelChangedWebhookEventDataSchema=z72.object({changes:z72.array(z72.object({action:z72.enum(["created","updated","deleted"]),key:z72.string(),locale:z72.string(),value:z72.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),isDefault:z72.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),previousCode:z72.string()})}),LocaleDeletedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),entriesDeleted:z72.number().int().nonnegative(),labelsDeleted:z72.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z72.object({merge:z72.object({id:z72.string(),from:BranchSchema,to:BranchSchema,applied:z72.array(z72.object({surface:SurfaceNameSchema,count:z72.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z72.object({branch:z72.object({name:BranchSchema}),version:z72.object({versionId:z72.uuid(),name:z72.string()})}),WebhookEventFamilySchema=z72.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z72.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z72.discriminatedUnion("source",[z72.object({source:z72.literal("literal"),value:z72.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z72.object({source:z72.literal("secret"),key:z72.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z72.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z72.object({name:z72.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z72.object({name:z72.string(),source:z72.enum(["literal","secret"]),secretKey:z72.string().nullable(),secretPrefix:z72.string().nullable(),configured:z72.literal(!0)}),WebhookFilterSchema=z72.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z72.string().min(1).max(255).optional(),mediaType:z72.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z72.string().min(1).max(255).optional(),locale:z72.string().min(1).max(120).optional()}),JsonValueSchema=z72.lazy(()=>z72.union([z72.string(),z72.number(),z72.boolean(),z72.null(),z72.array(JsonValueSchema),z72.record(z72.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z72.url(),enabled:z72.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z72.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z72.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z72.url().optional(),enabled:z72.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z72.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z72.boolean().optional()}),TestProjectWebhookRequestSchema=z72.object({eventType:WebhookEventTypeSchema.optional(),data:z72.record(z72.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z72.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z72.uuid(),name:z72.string(),eventType:WebhookEventTypeSchema,enabled:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z72.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z72.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z72.coerce.date().nullable(),deliveryStats24h:z72.object({succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z72.uuid(),projectId:z72.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z72.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z72.number().int().positive(),test:z72.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z72.number().int().nonnegative(),responseStatus:z72.number().int().nullable(),lastErrorCode:z72.string().nullable(),lastErrorMessage:z72.string().nullable(),payloadAvailable:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z72.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z72.string().nullable(),qstashMessageId:z72.string().nullable(),deliveredAt:z72.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z72.object({items:z72.array(WebhookDeliveryDTOSchema),pagination:z72.object({page:z72.number().int().positive(),limit:z72.number().int().positive(),total:z72.number().int().nonnegative(),totalPages:z72.number().int().positive(),hasMore:z72.boolean()}),stats:z72.object({total:z72.number().int().nonnegative(),succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z72.object({id:z72.uuid(),deliveryId:z72.uuid(),attempt:z72.number().int().positive(),status:z72.enum(["delivering","succeeded","failed"]),responseStatus:z72.number().int().nullable(),durationMs:z72.number().int().nonnegative(),responseExcerpt:z72.string().nullable(),errorCode:z72.string().nullable(),errorMessage:z72.string().nullable(),createdAt:z72.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z72.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z72.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z73}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=z73.object({key:z73.literal("fimo-2"),enabled:z73.boolean(),dismissed:z73.boolean().default(!1),interacted:z73.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z74}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteReportSchema,SitePriceTierSchema,SiteTypeSchema,SiteTermsCategorySchema,SITE_QUESTION,SITE_QUESTIONS,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=z74.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z74.enum(["running","done","failed"]),SiteCloneStatusSchema=z74.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z74.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z74.object({code:SiteRefusalCodeSchema,suggestedUrl:z74.string().nullable()}),SiteCheckGroupSchema=z74.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z74.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=z74.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z74.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z74.record(z74.string(),z74.union([z74.string(),z74.number(),z74.boolean(),z74.array(z74.string())])),SiteCheckResultSchema=z74.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z74.object({id:SiteCheckGroupSchema,score:z74.number().int().min(0).max(100).nullable()}),SiteReportSchema=z74.object({siteUrl:z74.string(),scannedAt:z74.coerce.date(),seoScore:z74.number().int().min(0).max(100).nullable(),geoScore:z74.number().int().min(0).max(100).nullable(),groups:z74.array(SiteReportGroupSchema),checks:z74.array(SiteCheckResultSchema),blockers:z74.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z74.enum(["budget","standard","premium","luxury"]),SiteTypeSchema=z74.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z74.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SITE_QUESTION={id:"site",kind:"confirm"},SITE_QUESTIONS={business:[SITE_QUESTION,{id:"competitors",kind:"form",inputs:[{id:"names",kind:"choices",multiple:!0,allowOther:!0,options:"competitors"}]},{id:"positioning",kind:"form",inputs:[{id:"positioning",kind:"text",max:2e3}]},{id:"priceTier",kind:"form",inputs:[{id:"priceTier",kind:"choices",multiple:!1,allowOther:!1,options:SitePriceTierSchema.options}]}],non_profit:[SITE_QUESTION,{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["volunteer","donate","join","next_event"]}]},{id:"searches",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]}],portfolio:[SITE_QUESTION,{id:"work",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["book_call","request_quote","email","follow"]}]}],hobby:[SITE_QUESTION,{id:"return",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:["creations","tutorials","progress","tips"]}]},{id:"tone",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!1,options:["warm","expert","playful","calm"]}]}],personal:[SITE_QUESTION,{id:"remember",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["read","contact","hire","follow"]}]}]},SiteUnderstandingSchema=z74.object({name:z74.string(),summary:z74.string(),audience:z74.string(),positioning:z74.string(),priceTier:SitePriceTierSchema,homepage:z74.string()}),SiteSuggestionSchema=z74.object({label:z74.string(),url:z74.string().nullable()}),SiteInterviewSuggestionsSchema=z74.record(z74.string(),z74.record(z74.string(),z74.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z74.record(z74.string().max(50),z74.union([z74.string().trim().max(2e3),z74.array(z74.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z74.object({status:z74.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z74.record(z74.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z74.object({questionId:z74.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z74.object({fixes:z74.array(z74.object({checkId:SiteCheckIdSchema,status:z74.enum(["fixed","not_fixed","not_applicable"]),note:z74.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z74.object({fixes:SiteFixesReportSchema.nullable(),summary:z74.string().nullable()}),StartSiteOnboardingRequestSchema=z74.object({organizationId:z74.string().min(1),url:z74.string().trim().min(1).max(2048),locale:z74.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z74.object({projectId:z74.string()})),SiteOnboardingRefusedResponseSchema=z74.object({error:z74.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z74.object({projectId:z74.string(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z74.boolean(),budgetExhausted:z74.boolean(),sponsored:z74.boolean(),cloneOutOfCredits:z74.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z74.string().nullable(),welcomeThreadId:z74.string().nullable(),competitors:z74.array(z74.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable(),bannerDismissed:z74.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z74.object({task:z74.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z74.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z74.object({search:z74.string().trim().max(200).optional(),organizationId:z74.string().trim().min(1).max(200).optional(),startDate:z74.coerce.date().optional(),endDate:z74.coerce.date().optional(),outcomes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteTypeSchema).optional()),page:z74.coerce.number().int().min(1).default(1),pageSize:z74.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z74.object({projectId:z74.string(),projectName:z74.string(),organizationId:z74.string(),organizationName:z74.string().nullable(),ownerEmail:z74.string().nullable(),ownerName:z74.string().nullable(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z74.boolean(),cloneRetries:z74.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z74.number(),interviewQuestions:z74.number().nullable(),seoScore:z74.number().nullable(),geoScore:z74.number().nullable(),spentUsd:z74.number(),budgetCapUsd:z74.number(),capReached:z74.boolean(),cloneSeconds:z74.number().nullable(),createdAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z74.object({onboardings:z74.array(AdminSiteOnboardingDTOSchema),page:z74.number(),limit:z74.number(),total:z74.number(),totalPages:z74.number()})),AdminSiteOnboardingStatsSchema=z74.object({total:z74.number(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number()),funnel:z74.object({started:z74.number(),confirmed:z74.number(),finished:z74.number(),opened:z74.number()}),bySiteType:z74.array(z74.object({siteType:SiteTypeSchema,total:z74.number(),finished:z74.number(),opened:z74.number()})),granularity:z74.enum(["hour","day"]),series:z74.array(z74.object({at:z74.coerce.date(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number())})),spentUsd:z74.object({total:z74.number(),average:z74.number().nullable()}),sponsored:z74.number(),paidByOrganization:z74.object({usd:z74.number(),credits:z74.number()}),capReached:z74.number(),cloneSeconds:z74.object({median:z74.number().nullable(),average:z74.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z74.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z74.string(),cloneThreadId:z74.string().nullable(),paidByOrganizationUsd:z74.number()}),interview:SiteInterviewSchema.extend({invocationIds:z74.array(z74.string())}).nullable(),knowledgeWritten:z74.string().nullable(),knowledgeNow:z74.object({content:z74.string(),updatedAt:z74.coerce.date().nullable(),updatedBy:z74.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z75}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=z75.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z75.object({total:z75.number(),base:z75.number(),purchases:z75.number(),awards:z75.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z75.object({id:z75.string(),name:z75.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z75.object({type:z75.string(),brand:z75.string().nullable(),last4:z75.string().nullable(),expirationDate:z75.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z75.object({currency:z75.string(),nextPaymentAmount:z75.number().nullable(),nextPaymentAt:z75.string().nullable(),billingInterval:z75.string().nullable(),totalAmount:z75.number().nullable(),discountAmount:z75.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z75.object({id:z75.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z75.string().nullable(),currentPeriodEndsAt:z75.string().nullable(),renewsAt:z75.string().nullable(),cancelAt:z75.string().nullable(),renewAutomatically:z75.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z75.object({type:z75.enum(["low_balance","critical_balance","approaching_limit"]),message:z75.string(),estimatedPromptsRemaining:z75.number().nullable(),avgCostPerPrompt:z75.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z75.object({monthlyCredits:z75.number().nullable(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z75.object({organizationId:z75.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z75.string().nullable(),tenureDays:z75.number().int().nonnegative(),capturedAt:z75.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z75.object({hasSubscription:z75.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z75.number().nullable(),alerts:z75.array(CreditAlertDTOSchema),portalUrl:z75.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z75.object({creditCount:z75.number().int().positive(),expiresAt:z75.string().datetime().nullable().optional(),message:z75.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("free"),amountCents:z75.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("purchase"),amountCents:z75.number().int().positive()}),CreditTopupRequestDTOSchema=z75.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z75.object({success:z75.boolean(),transactionId:z75.string().nullable(),newBalance:z75.number(),creditCount:z75.number(),type:z75.enum(["free","purchase"]),invoiceId:z75.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z76}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=z76.object({totalCredits:z76.number(),totalCostUsd:z76.number(),totalMessages:z76.number(),avgCostPerMessage:z76.number(),periodStart:z76.string().nullable(),periodEnd:z76.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z76.object({date:z76.string(),credits:z76.number(),costUsd:z76.number(),messages:z76.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z76.array(UsageByUserForProjectDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z76.object({summary:UsageSummaryDTOSchema,byProject:z76.array(UsageByProjectDTOSchema),byUser:z76.array(UsageByUserDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z77}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=z77.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z77.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z77.object({startDate:z77.string().optional(),endDate:z77.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z77.coerce.number().int().positive().default(1),limit:z77.coerce.number().int().positive().max(100).default(20),sortBy:z77.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z77.string().optional(),activeOnly:z77.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z77.object({totalCredits:z77.number(),totalCostUsd:z77.number(),totalMessages:z77.number(),avgCostPerMessage:z77.number(),avgCreditsPerMessage:z77.number(),periodStart:z77.string(),periodEnd:z77.string(),creditsChange:z77.number().nullable(),costChange:z77.number().nullable(),messagesChange:z77.number().nullable(),unattributedCredits:z77.number(),unattributedCostUsd:z77.number(),unattributedMessages:z77.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z77.object({date:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z77.object({organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number(),projectCount:z77.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z77.object({userId:z77.string(),userName:z77.string().nullable(),userEmail:z77.string().nullable(),userImage:z77.string().nullable(),organizationId:z77.string().nullable(),organizationName:z77.string().nullable(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),projectCount:z77.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z77.object({projectId:z77.string(),projectName:z77.string(),projectDisplayName:z77.string().nullable(),organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z77.object({id:z77.string(),name:z77.string(),value:z77.number(),percentage:z77.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z77.object({day:z77.number(),hour:z77.number(),value:z77.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z77.object({summary:UsageOverviewSummaryDTOSchema,timeline:z77.array(UsageTimelinePointDTOSchema),topOrganizations:z77.array(OrganizationUsageRowDTOSchema),topUsers:z77.array(UserUsageRowDTOSchema),topProjects:z77.array(ProjectUsageRowDTOSchema),creditDistribution:z77.array(UsageDistributionItemDTOSchema),userDistribution:z77.array(UsageDistributionItemDTOSchema),heatmap:z77.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z77.object({page:z77.number(),limit:z77.number(),totalItems:z77.number(),totalPages:z77.number(),hasMore:z77.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z77.object({organizations:z77.array(OrganizationUsageRowDTOSchema),top:z77.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z77.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z77.object({users:z77.array(ExtendedUserUsageRowDTOSchema),top:z77.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z77.object({projects:z77.array(ExtendedProjectUsageRowDTOSchema),top:z77.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z77.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z77.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z77.object({credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),createdAt:z77.string(),memberCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z77.object({id:z77.string(),name:z77.string().nullable(),email:z77.string(),image:z77.string().nullable(),createdAt:z77.string(),organizationCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),displayName:z77.string().nullable(),createdAt:z77.string(),organizationId:z77.string(),organizationName:z77.string(),ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z78}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=z78.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z78.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z78.object({command:z78.string().min(1).max(1e4),cwd:z78.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z78.record(z78.string(),z78.string()).optional(),name:z78.string().optional(),waitForCompletion:z78.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=z78.object({identifier:z78.string(),status:SandboxProcessStatusSchema,command:z78.string().optional(),startedAt:z78.string().optional(),exitCode:z78.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z78.object({processes:z78.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z78.object({processId:z78.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z78.object({success:z78.boolean(),message:z78.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z79}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=z79.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z79.object({search:z79.string().trim().max(200).optional(),startDate:z79.coerce.date().optional(),endDate:z79.coerce.date().optional(),states:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(AdminUnclaimedStateSchema).optional()),cliVersions:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(z79.string().max(64)).optional()),page:z79.coerce.number().int().min(1).default(1),pageSize:z79.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z79.object({projectId:z79.string(),displayName:z79.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z79.string().nullable(),createdAt:z79.coerce.date(),expiresAt:z79.coerce.date(),claimedAt:z79.coerce.date().nullable(),claimedOrganizationId:z79.string().nullable(),claimedOrganizationName:z79.string().nullable(),claimedByEmail:z79.string().nullable(),projectExists:z79.boolean(),previewUrl:z79.string().nullable(),hostingCostUsd:z79.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z79.object({projects:z79.array(AdminUnclaimedProjectDTOSchema),page:z79.number(),limit:z79.number(),total:z79.number(),totalPages:z79.number()})),ClaimOutcomesSchema=z79.object({total:z79.number(),claimed:z79.number(),archived:z79.number(),claimRate:z79.number().nullable(),medianTimeToClaimSeconds:z79.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z79.record(AdminUnclaimedStateSchema,z79.number()),averageTimeToClaimSeconds:z79.number().nullable(),byCliVersion:z79.array(ClaimOutcomesSchema.extend({cliVersion:z79.string().nullable()})),granularity:z79.enum(["hour","day"]),series:z79.array(z79.object({at:z79.coerce.date(),states:z79.record(AdminUnclaimedStateSchema,z79.number()),alive:z79.number(),hostingCostUsd:z79.number()})),hostingCostUsd:z79.number(),costPerProjectUsd:z79.number().nullable(),leftovers:z79.object({overdue:z79.number(),claiming:z79.number(),archivedNotDeleted:z79.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z80}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z80.enum(["internal","user-visible"]),SessionSetRetentionSchema=z80.object({additionalDays:z80.number().int().min(1).max(30)}).strict()}});import{z as z81}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=z81.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=z81.object({content:ProjectKnowledgeContentSchema,updatedAt:z81.string().nullable(),updatedBy:z81.string().nullable()}),ProjectKnowledgeUpdateSchema=z81.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z81.object({id:z81.uuid(),status:z81.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z81.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z81.object({idempotencyKey:z81.uuid()})}});import{z as z82}from"zod";var ORGANIZATION_FEATURES,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=["agents"],OrganizationFeatureSchema=z82.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z82.object({features:z82.record(OrganizationFeatureSchema,z82.boolean())}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z82.object({feature:OrganizationFeatureSchema,enabled:z82.boolean(),default:z82.boolean(),override:z82.boolean().nullable(),reason:z82.string().nullable(),updatedBy:z82.string().nullable(),updatedAt:z82.string().datetime().nullable()}),OrganizationFeatureSetSchema=z82.object({state:z82.enum(["on","off","default"]),reason:z82.string().trim().min(1).max(500),apply:z82.boolean().default(!1),confirmProduction:z82.boolean().default(!1)})}});import{z as z83}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_chat_block();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_agent_question_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_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()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.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="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},"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_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,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
6
|
`)}__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(stdout,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(stdout,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,stderr}=opts;function write(stream,line){stream.write(`${line}
|
|
7
7
|
`)}__name(write,"write");function renderMessage(event){if(write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);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(stdout,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r=>displayWidth(String(r[c2.key]??""))))),header=columns.map((c2,i)=>padToWidth(c2.label,widths[i])).join(" ");write(stdout,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout,`${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(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout.write(event.script.endsWith(`
|
|
8
8
|
`)?event.script:`${event.script}
|
|
@@ -894,7 +894,7 @@ Run \`fimo mcp <command> --help\` for command-specific help.
|
|
|
894
894
|
`)}
|
|
895
895
|
`;return{content:content3,changed:content3!==existing,created:!1}}return{content:`${[...lines,"",...block].join(`
|
|
896
896
|
`)}
|
|
897
|
-
`,changed:!0,created:!0}}__name(mergeManagedEnvBlock,"mergeManagedEnvBlock");function renderBlock(entries2,spec){return[spec.start,...spec.header,...Object.entries(entries2).map(([key,value])=>`${key}=${quoteEnvValue(value)}`),spec.end]}__name(renderBlock,"renderBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_project_context();init_project();function registerProjectSecretsCommands(program2){let vars=program2.command("vars").description("Manage site variables");vars.command("list").description("List site variables").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((opts,command)=>listCommand3("variable",opts,command)),vars.command("add <key> [value]").description("Add a site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","add",key,opts.value??value,opts,command)),vars.command("update <key> [value]").description("Update an existing site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","update",key,opts.value??value,opts,command)),vars.command("unset <key>").alias("remove").description("Delete a site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((key,opts,command)=>unsetCommand("variable",key,opts,command)),vars.command("pull [file]").description("Write public site variables to a local env file").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((file,opts,command)=>pullVarsCommand(file,opts,command));let secrets=program2.command("secrets").description("Manage site secrets");secrets.command("list").description("List site secrets without revealing values").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((opts,command)=>listCommand3("secret",opts,command)),secrets.command("add <key> [value]").description("Add a site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","add",key,opts.value??value,opts,command)),secrets.command("update <key> [value]").description("Update an existing site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","update",key,opts.value??value,opts,command)),secrets.command("unset <key>").alias("remove").description("Delete a site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((key,opts,command)=>unsetCommand("secret",key,opts,command))}__name(registerProjectSecretsCommands,"registerProjectSecretsCommands");function commandName(kind,verb){return`${kind==="secret"?"secrets":"vars"} ${verb}`}__name(commandName,"commandName");async function listCommand3(kind,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command),rows=await fimo.execute("secrets.list",{projectId,kind,environment});if(rows.length===0){ui.info({command:commandName(kind,"list"),message:kind==="secret"?"No site secrets set.":"No site variables set."});return}ui.table({command:commandName(kind,"list"),columns:[{key:"key",label:"KEY"},{key:"value",label:kind==="secret"?"VALUE (masked)":"VALUE"}],rows:rows.map(row2=>({key:row2.key,value:row2.value??row2.maskedValue??""}))})}__name(listCommand3,"listCommand");async function writeCommand(kind,operation,key,valueArg,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command),value=opts.stdin||valueArg===void 0?await readStdinValue4(kind):valueArg,input={projectId,key,kind,value,environment};operation==="add"?await fimo.execute("secrets.create",input):await fimo.execute("secrets.update",input);let envLocal=kind==="variable"?await syncDefaultLocalVars(fimo,projectId,environment,opts):null,action=operation==="add"?"Added":"Updated";ui.ok({command:commandName(kind,operation),headline:`${action} site ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(writeCommand,"writeCommand");async function unsetCommand(kind,key,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command);await fimo.execute("secrets.delete",{projectId,key,kind,environment});let envLocal=kind==="variable"?await syncDefaultLocalVars(fimo,projectId,environment,opts):null;ui.ok({command:commandName(kind,"unset"),headline:`Removed site ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(unsetCommand,"unsetCommand");async function pullVarsCommand(file,opts,command){let projectRoot=resolveProjectCwd(opts.cwd),{fimo,environment,projectId}=await resolveScope2(opts,command),result=await writePulledVars(fimo,projectRoot,projectId,environment,file??".env.local");ui.ok({command:"vars pull",headline:`Wrote ${result.written} variable${result.written===1?"":"s"} to ${result.path}`,details:{project_id:projectId,file:result.path,written:result.written}})}__name(pullVarsCommand,"pullVarsCommand");async function syncDefaultLocalVars(fimo,projectId,environment,opts){let projectRoot=resolveProjectCwd(opts.cwd);try{if(loadProjectSettings(projectRoot).projectId!==projectId)return null}catch{return null}return writePulledVars(fimo,projectRoot,projectId,environment,".env.local")}__name(syncDefaultLocalVars,"syncDefaultLocalVars");async function writePulledVars(fimo,projectRoot,projectId,environment,file){let rows=(await fimo.execute("secrets.list",{projectId,kind:"variable",environment})).filter(row2=>row2.exposure==="public"),target=path42.resolve(projectRoot,file),existing=fs42.existsSync(target)?fs42.readFileSync(target,"utf8"):"",body=mergeEnvFile(existing,rows);return fs42.writeFileSync(target,body),{path:target,written:rows.length}}__name(writePulledVars,"writePulledVars");function resolveProjectId7(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId7,"resolveProjectId");async function resolveScope2(opts,command){let fimo=createCliFimoClient(loadConfig()),projectId=resolveProjectId7(opts),branch=DEFAULT_BRANCH;try{branch=(await getProjectContext({cwd:opts.cwd,branchOverride:branchOverrideFromCommand(command)})).branch}catch(error){if(!opts.project)throw error}let environment=branch==="prod"?PRODUCTION_ENVIRONMENT_KEY:(await fimo.execute("environments.resolve",{projectId,branch})).environment;return{fimo,environment,projectId}}__name(resolveScope2,"resolveScope");async function readStdinValue4(kind){if(process.stdin.isTTY)throw new Error(`Pass a ${kind} value or pipe one with --stdin.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue4,"readStdinValue");var VARS_BLOCK={start:"# fimo:vars:start",end:"# fimo:vars:end",header:["# Generated by fimo vars pull. Do not put secrets in this block."]};function mergeEnvFile(existing,rows){let entries2=Object.fromEntries(rows.map(row2=>[row2.key,row2.value??""]));return mergeManagedEnvBlock(existing,entries2,VARS_BLOCK).content}__name(mergeEnvFile,"mergeEnvFile");import fs43 from"node:fs";init_dist();init_auth();init_config();init_sdk_transport();init_project_services();init_project();function resolveCwd2(options){return resolveProjectCwd(options.cwd)}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options);try{return loadProjectSettings(cwd)}catch{return null}}__name(readLocalConfig,"readLocalConfig");function resolveProjectId8(argv,options,command){if(argv)return argv;let local=readLocalConfig(options);return local?local.projectId:(ui.error({command,code:"NOT_IN_PROJECT",message:"No site ID and no Fimo site link found in the current directory.",hint:"Pass a site ID explicitly, or cd into a linked site."}),null)}__name(resolveProjectId8,"resolveProjectId");async function projectsListCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),creds=requireAccountCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"projects list",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let{data:projects2}=await fimo.execute("projects.list",{organizationId});if(projects2.length===0){ui.info({command:"projects list",message:"No sites in this organization yet."});return}ui.table({command:"projects list",columns:[{key:"published",label:"PUB"},{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"displayName",label:"DISPLAY NAME"}],rows:projects2.map(p2=>({published:p2.appUrl?"\u{1F7E2}":"\u26AA",id:p2.id,name:p2.name,displayName:p2.displayName??""}))})}__name(projectsListCommand,"projectsListCommand");async function projectsUnclaimedCommand(){let cfg=loadConfig(),entries2=readUnclaimedIndex(cfg);if(entries2.length===0){ui.info({command:"projects unclaimed",message:"No projects were created without an account on this machine.",jsonData:{projects:[]}});return}let claims=await createUnclaimedProjectsService(cfg).claimStates(entries2.map(entry=>claimSecretFromUrl(entry.claimUrl))),projects2=entries2.map((entry,index)=>{let claim=claims[index];return{project_id:entry.projectId,name:entry.name,dir:entry.dir,state:claim?.state??"expired",expires_at:new Date(claim?.expiresAt??entry.expiresAt).toISOString(),claim_url:entry.claimUrl}});ui.result({command:"projects unclaimed",data:{projects:projects2},render:__name(()=>projects2.map(project=>[`${project.name} ${project.state} claim by ${formatClaimDeadline(project.expires_at)}`,` ${project.dir}`,` ${project.claim_url}`].join(`
|
|
897
|
+
`,changed:!0,created:!0}}__name(mergeManagedEnvBlock,"mergeManagedEnvBlock");function renderBlock(entries2,spec){return[spec.start,...spec.header,...Object.entries(entries2).map(([key,value])=>`${key}=${quoteEnvValue(value)}`),spec.end]}__name(renderBlock,"renderBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_project_context();init_project();function registerProjectSecretsCommands(program2){let vars=program2.command("vars").description("Manage site variables");vars.command("list").description("List site variables").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((opts,command)=>listCommand3("variable",opts,command)),vars.command("add <key> [value]").description("Add a site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","add",key,opts.value??value,opts,command)),vars.command("update <key> [value]").description("Update an existing site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","update",key,opts.value??value,opts,command)),vars.command("unset <key>").alias("remove").description("Delete a site variable").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((key,opts,command)=>unsetCommand("variable",key,opts,command)),vars.command("pull [file]").description("Write public site variables to a local env file").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((file,opts,command)=>pullVarsCommand(file,opts,command));let secrets=program2.command("secrets").description("Manage site secrets");secrets.command("list").description("List site secrets without revealing values").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((opts,command)=>listCommand3("secret",opts,command)),secrets.command("add <key> [value]").description("Add a site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","add",key,opts.value??value,opts,command)),secrets.command("update <key> [value]").description("Update an existing site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","update",key,opts.value??value,opts,command)),secrets.command("unset <key>").alias("remove").description("Delete a site secret").option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory").action((key,opts,command)=>unsetCommand("secret",key,opts,command))}__name(registerProjectSecretsCommands,"registerProjectSecretsCommands");function commandName(kind,verb){return`${kind==="secret"?"secrets":"vars"} ${verb}`}__name(commandName,"commandName");async function listCommand3(kind,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command),rows=await fimo.execute("secrets.list",{projectId,kind,environment});if(rows.length===0){ui.info({command:commandName(kind,"list"),message:kind==="secret"?"No site secrets set.":"No site variables set."});return}ui.table({command:commandName(kind,"list"),columns:[{key:"key",label:"KEY"},{key:"value",label:kind==="secret"?"VALUE (masked)":"VALUE"}],rows:rows.map(row2=>({key:row2.key,value:row2.value??row2.maskedValue??""}))})}__name(listCommand3,"listCommand");async function writeCommand(kind,operation,key,valueArg,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command),value=opts.stdin||valueArg===void 0?await readStdinValue4(kind):valueArg,input={projectId,key,kind,value,environment};operation==="add"?await fimo.execute("secrets.create",input):await fimo.execute("secrets.update",input);let envLocal=kind==="variable"?await syncDefaultLocalVars(fimo,projectId,environment,opts):null,action=operation==="add"?"Added":"Updated";ui.ok({command:commandName(kind,operation),headline:`${action} site ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(writeCommand,"writeCommand");async function unsetCommand(kind,key,opts,command){let{fimo,environment,projectId}=await resolveScope2(opts,command);await fimo.execute("secrets.delete",{projectId,key,kind,environment});let envLocal=kind==="variable"?await syncDefaultLocalVars(fimo,projectId,environment,opts):null;ui.ok({command:commandName(kind,"unset"),headline:`Removed site ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(unsetCommand,"unsetCommand");async function pullVarsCommand(file,opts,command){let projectRoot=resolveProjectCwd(opts.cwd),{fimo,environment,projectId}=await resolveScope2(opts,command),result=await writePulledVars(fimo,projectRoot,projectId,environment,file??".env.local");ui.ok({command:"vars pull",headline:`Wrote ${result.written} variable${result.written===1?"":"s"} to ${result.path}`,details:{project_id:projectId,file:result.path,written:result.written}})}__name(pullVarsCommand,"pullVarsCommand");async function syncDefaultLocalVars(fimo,projectId,environment,opts){let projectRoot=resolveProjectCwd(opts.cwd);try{if(loadProjectSettings(projectRoot).projectId!==projectId)return null}catch{return null}return writePulledVars(fimo,projectRoot,projectId,environment,".env.local")}__name(syncDefaultLocalVars,"syncDefaultLocalVars");async function writePulledVars(fimo,projectRoot,projectId,environment,file){let rows=(await fimo.execute("secrets.list",{projectId,kind:"variable",environment})).filter(row2=>row2.exposure==="public"),target=path42.resolve(projectRoot,file),existing=fs42.existsSync(target)?fs42.readFileSync(target,"utf8"):"",body=mergeEnvFile(existing,rows);return fs42.writeFileSync(target,body),{path:target,written:rows.length}}__name(writePulledVars,"writePulledVars");function resolveProjectId7(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId7,"resolveProjectId");async function resolveScope2(opts,command){let fimo=createCliFimoClient(loadConfig()),projectId=resolveProjectId7(opts),branch=DEFAULT_BRANCH;try{branch=(await getProjectContext({cwd:opts.cwd,branchOverride:branchOverrideFromCommand(command)})).branch}catch(error){if(!opts.project)throw error}let environment=branch==="prod"?PRODUCTION_ENVIRONMENT_KEY:(await fimo.execute("environments.resolve",{projectId,branch})).environment;return{fimo,environment,projectId}}__name(resolveScope2,"resolveScope");async function readStdinValue4(kind){if(process.stdin.isTTY)throw new Error(`Pass a ${kind} value or pipe one with --stdin.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue4,"readStdinValue");var VARS_BLOCK={start:"# fimo:vars:start",end:"# fimo:vars:end",header:["# Generated by fimo vars pull. Do not put secrets in this block."]};function mergeEnvFile(existing,rows){let entries2=Object.fromEntries(rows.map(row2=>[row2.key,row2.value??""]));return mergeManagedEnvBlock(existing,entries2,VARS_BLOCK).content}__name(mergeEnvFile,"mergeEnvFile");import fs43 from"node:fs";init_dist();init_auth();init_config();init_sdk_transport();init_project_services();init_project();function resolveCwd2(options){return resolveProjectCwd(options.cwd)}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options);try{return loadProjectSettings(cwd)}catch{return null}}__name(readLocalConfig,"readLocalConfig");function resolveProjectId8(argv,options,command){if(argv)return argv;let local=readLocalConfig(options);return local?local.projectId:(ui.error({command,code:"NOT_IN_PROJECT",message:"No site ID and no Fimo site link found in the current directory.",hint:"Pass a site ID explicitly, or cd into a linked site."}),null)}__name(resolveProjectId8,"resolveProjectId");async function projectsListCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),creds=requireAccountCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"projects list",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let{data:projects2}=await fimo.execute("projects.list",{organizationId});if(projects2.length===0){ui.info({command:"projects list",message:"No sites in this organization yet."});return}ui.table({command:"projects list",columns:[{key:"published",label:"PUB"},{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"displayName",label:"DISPLAY NAME"}],rows:projects2.map(p2=>({published:p2.appUrl?"\u{1F7E2}":"\u26AA",id:p2.id,name:p2.name,displayName:p2.displayName??""}))})}__name(projectsListCommand,"projectsListCommand");async function projectsUnclaimedCommand(){let cfg=loadConfig(),entries2=readUnclaimedIndex(cfg);if(entries2.length===0){ui.info({command:"projects unclaimed",message:"No projects were created without an account on this machine.",jsonData:{projects:[]}});return}let claims=await createUnclaimedProjectsService(cfg).claimStates(entries2.map(entry=>claimSecretFromUrl(entry.claimUrl))),projects2=entries2.flatMap((entry,index)=>{let claim=claims[index];return claim?.state!=="claimable"?[]:[{project_id:entry.projectId,name:entry.name,dir:entry.dir,state:claim.state,expires_at:new Date(claim.expiresAt??entry.expiresAt).toISOString(),claim_url:entry.claimUrl}]});if(projects2.length===0){ui.info({command:"projects unclaimed",message:"No site created on this machine is waiting for a claim.",jsonData:{projects:[]}});return}ui.result({command:"projects unclaimed",data:{projects:projects2},render:__name(()=>projects2.map(project=>[`${project.name} claim by ${formatClaimDeadline(project.expires_at)}`,` ${project.dir}`,` ${project.claim_url}`].join(`
|
|
898
898
|
`)).join(`
|
|
899
899
|
|
|
900
900
|
`),"render")})}__name(projectsUnclaimedCommand,"projectsUnclaimedCommand");async function projectsDeleteCommand(projectIdArg,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),projectId=resolveProjectId8(projectIdArg,options,"projects delete");if(projectId){if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","projects delete");let confirmed=await ot2({message:`Delete site ${projectId}? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"projects delete",message:"Cancelled."});return}}await fimo.execute("projects.delete",{projectId}),ui.ok({command:"projects delete",headline:`Deleted site ${projectId}.`,details:{project_id:projectId}})}}__name(projectsDeleteCommand,"projectsDeleteCommand");async function projectsRenameCommand(nameArg,projectIdArg,options){let cwd=resolveCwd2(options),local=readLocalConfig(options);if(!local){ui.error({command:"projects rename",code:"NOT_IN_PROJECT",message:"No Fimo site link found in the current directory.",hint:"`fimo rename` only operates on a local site. cd into the site root."});return}if(projectIdArg&&projectIdArg!==local.projectId){ui.error({command:"projects rename",code:"PROJECT_ID_MISMATCH",message:`Site ID ${projectIdArg} does not match this directory's site (${local.projectId}).`,hint:"cd into the site you want to rename."});return}let name=nameArg.trim();if(!name){ui.error({command:"projects rename",code:"EMPTY_DISPLAY_NAME",message:"Display name cannot be empty."});return}let configPath=resolveProjectConfigPath(cwd),config={};if(fs43.existsSync(configPath))try{config=JSON.parse(fs43.readFileSync(configPath,"utf-8"))}catch(error){ui.error({command:"projects rename",code:"CONFIG_PARSE_FAILED",message:`Could not parse ${configPath}: ${error instanceof Error?error.message:String(error)}`});return}let seo=config.seo??{};config.seo={...seo,siteName:name},fs43.writeFileSync(configPath,JSON.stringify(config,null,2)+`
|