fimo 2.9.0-staging.6 → 2.9.0
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-cli/SKILL.md +1 -1
- package/assets/skills/fimo-cli/references/site-checks.md +0 -36
- package/assets/skills/fimo-studio/references/ai-chat.md +1 -1
- package/dist/cli/bundle.json +2 -2
- package/dist/cli/index.js +13 -24
- package/package.json +8 -8
- package/release.json +2 -2
- 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/dist/cli/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 isProcessControlEnvKey(key){return PROCESS_CONTROL_ENV_KEYS.has(key)||PROCESS_CONTROL_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let 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,PROCESS_CONTROL_ENV_KEYS,PROCESS_CONTROL_ENV_PREFIXES,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],PROCESS_CONTROL_ENV_KEYS=new Set(["PATH","HOME","SHELL","BASH_ENV","ENV","PROMPT_COMMAND","USER","TMPDIR","HOST","HOSTNAME","PORT","NODE_ENV","NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_TLS_REJECT_UNAUTHORIZED","SSL_CERT_FILE","CURL_CA_BUNDLE","PYTHONPATH","LD_PRELOAD","LD_LIBRARY_PATH","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","FIMO_VALIDATION_BUILD","FIMO_SKIP_VERSION_CHECK","FIMO_EDITING_METADATA","FIMO_AGENT_TMP_DIR"]),PROCESS_CONTROL_ENV_PREFIXES=["GIT_","NPM_CONFIG_","PNPM_","YARN_","COREPACK_","BUN_","DENO_"];__name(isProcessControlEnvKey,"isProcessControlEnvKey");BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as z8}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z9}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z9.preprocess(referenceValuePreprocess,z9.object({documentId:z9.uuid()})),ReferenceInputValueSchema=z9.preprocess(referenceValuePreprocess,z9.union([z9.object({documentId:z9.uuid()}),z9.object({slug:z9.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.object({contentType:z9.string().min(1),documentId:z9.uuid()})),PolymorphicReferenceInputValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.union([z9.object({contentType:z9.string().min(1),documentId:z9.uuid()}),z9.object({contentType:z9.string().min(1),slug:z9.string().min(1)})]))}});import{z as z10}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path50){let conditionPath=[...path50,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,path50)=>{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,path50));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path50,fieldName,variant.uid]);else walk(field.schema.fields,[...path50,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path50,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path50,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z10.union([z10.object({field:z10.string().min(1),equals:z10.union([z10.string(),z10.number(),z10.boolean()])}).strict(),z10.object({field:z10.string().min(1),in:z10.array(z10.union([z10.string(),z10.number(),z10.boolean()])).min(1)}).strict()]),commonFieldShape={label:z10.string().min(1).optional(),description:z10.string().optional(),group:z10.union([z10.string().min(1),z10.array(z10.string().min(1)).min(1)]).optional(),editable:z10.boolean().optional(),required:z10.boolean().optional(),default:z10.unknown().optional(),showIf:z10.union([showIfClauseSchema,z10.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z10.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z10.object({...commonFieldShape,type:z10.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z10.number().optional(),max:z10.number().optional(),minLength:z10.number().int().nonnegative().optional(),maxLength:z10.number().int().nonnegative().optional(),regex:z10.string().optional(),multiple:z10.boolean().optional(),allowedMimeTypes:z10.array(z10.string()).optional(),options:z10.array(z10.string().min(1)).min(1).optional(),unique:z10.boolean().optional(),i18n:z10.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z10.object({...commonFieldShape,type:z10.literal("reference"),target:z10.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z10.array(z10.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z10.boolean().optional(),i18n:z10.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z10.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z10.record(z10.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z10.object({uid:z10.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z10.string().min(1),description:z10.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z10.object({fields:blockFieldsSchema}).strict(),blocksSchema=z10.object({oneOf:z10.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z10.object({...commonFieldShape,type:z10.literal("blocks"),min:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z10.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z10.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z11}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","site_onboarding_refusal_lift","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_trace_budget_wrap_up_read","ops_context_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_memory_health_read","ops_routine_metrics_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_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_billing_legacy_premium_comp","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_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","ops_operation_plan","project_sync","project_thumbnail_regenerate","project_delete","project_import","organization_delete","credits_topup","credits_burn","user_session_revoke","user_ban","user_unban","user_impersonate","user_role_change","user_sessions_revoke","user_delete","platform_pool_change","platform_maintenance_change","platform_sync","platform_tenant_schema_sync","integration_event_replay","ops_billing_dispatch_retry","ops_billing_plan_projection_reconcile","ops_agent_chat_create","ops_pylon_issue_change","ops_pylon_note_create","ops_pylon_reply_preview","ops_pylon_reply_approve","ops_pylon_reply_send","admin_playground_run","ops_find","ops_project_health_read","ops_migrations_read","ops_operational_read","ops_billing_report_read","ops_users_read","ops_organizations_read","ops_merges_read","ops_platform_read","ops_watch_read","ops_notification_read","ops_audit_read"],AuditActionSchema=z11.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z11.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z11.enum(AUDIT_ACTOR_KINDS)}});import{z as z12}from"zod";var ORGANIZATION_FEATURES,AGENT_PLANS,AgentPlanSchema,OrganizationFeatureSchema,OrganizationFeaturesDTOSchema,OrganizationFeaturesDTO,OrganizationFeatureStateDTOSchema,OrganizationFeatureSetSchema,init_organization_features_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization-features.dto.js"(){"use strict";init_create_dto();ORGANIZATION_FEATURES=["agents","routine_planner","pro_agents"],AGENT_PLANS=["free","starter","pro"],AgentPlanSchema=z12.enum(AGENT_PLANS),OrganizationFeatureSchema=z12.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z12.object({features:z12.record(OrganizationFeatureSchema,z12.boolean()),lockedByPlan:z12.array(OrganizationFeatureSchema),agentPlan:AgentPlanSchema}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z12.object({feature:OrganizationFeatureSchema,enabled:z12.boolean(),default:z12.boolean(),lockedByPlan:z12.boolean(),override:z12.boolean().nullable(),reason:z12.string().nullable(),updatedBy:z12.string().nullable(),updatedAt:z12.string().datetime().nullable()}),OrganizationFeatureSetSchema=z12.object({state:z12.enum(["on","off","default"]),reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1)})}});import{z as z13}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_SUPPORT_PRESET,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OPS_MEMORY_HEALTH_MAX_WINDOW_MS,OpsMemoryHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OPS_ROUTINE_METRICS_MAX_WINDOW_MS,OpsRoutineMetricsGroupBySchema,OpsRoutineMetricsSortBySchema,OpsRoutineMetricsInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OpsBillingAgentRuntimeAttachInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_organization_features_dto();init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:project:agents:write","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:organization:features:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send","ops:users:read","ops:users:write","ops:organizations:read","ops:organizations:write","ops:merges:read","ops:merges:write","ops:platform:read","ops:platform:write","ops:project:admin","ops:credits:write"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_SUPPORT_PRESET=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:users:read","ops:organizations:read","ops:merges:read","ops:platform:read","ops:billing:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:audit:read","ops:notification:preview"],OPS_PERMISSION_PRESETS={support:OPS_SUPPORT_PRESET,engineer:[...OPS_SUPPORT_PRESET,"ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:customers:write","ops:billing:write","ops:organization:features:write","ops:known-issues:write","ops:validations:write","ops:merges:write","ops:platform:write","ops:users:write"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z13.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z13.strictObject({organizationId:z13.string().trim().min(1).max(255).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),OPS_MEMORY_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsMemoryHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_MEMORY_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"memory health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z13.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,limit:z13.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,sample:z13.coerce.number().int().min(1).max(25).default(10)})),OPS_ROUTINE_METRICS_MAX_WINDOW_MS=2160*60*60*1e3,OpsRoutineMetricsGroupBySchema=z13.enum(["routine","plan","day","project"]),OpsRoutineMetricsSortBySchema=z13.enum(["total","jev","runs"]),OpsRoutineMetricsInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),plan:AgentPlanSchema.optional(),routine:z13.string().trim().min(1).max(64).optional(),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total"),burstMinutes:z13.coerce.number().int().min(1).max(120).default(10),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_ROUTINE_METRICS_MAX_WINDOW_MS,{path:["since"],message:"routine metrics windows cannot exceed 90 days"}),OpsChatHistoryJudgeCalibrationInputSchema=z13.strictObject({reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z13.boolean().default(!1),correlationLimit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),organizationIds:z13.array(z13.string().min(1)).min(1).max(100).optional(),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z13.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z13.strictObject({projectId:z13.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z13.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z13.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z13.strictObject({completeAggregate:z13.boolean(),truncated:z13.boolean().nullable(),sampled:z13.boolean().nullable(),pagination:z13.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z13.literal(!1),providerAsOf:z13.null(),projectFilter:z13.literal("exact properties.projectId equality"),environmentFilterSupported:z13.literal(!1),excludesMissingProjectId:z13.literal(!0),transport:z13.literal("server"),consentCoverage:z13.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z13.literal(!1)}),OpsPosthogCountsSchema=z13.array(z13.strictObject({event:z13.enum(OPS_POSTHOG_EVENTS),captureCount:z13.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z13.strictObject({schemaVersion:z13.literal(1),questionId:z13.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z13.uuid().nullable(),projectEnvironment:z13.literal("mixed_or_unrecorded"),window:z13.strictObject({from:z13.iso.datetime(),to:z13.iso.datetime(),bounds:z13.literal("[from,to)")}).nullable(),source:z13.literal("posthog"),sourceStatus:z13.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z13.iso.datetime(),auditId:z13.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3),limit:z13.number().int().min(1).max(100).default(25),checkProvider:z13.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z13.object({branch:z13.string().trim().min(1).max(255),canaryPath:z13.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z13.iso.datetime({offset:!0}),until:z13.iso.datetime({offset:!0}),reason:z13.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z14}from"zod";function resolveOpsTime(value,now=new Date){let relative3=RELATIVE_WINDOW.exec(value.trim());if(relative3){let amount=Number(relative3[1]),unit=relative3[2];return new Date(now.getTime()-amount*UNIT_MS[unit]).toISOString()}return new Date(value).toISOString()}function opsHoursSince(value,now=new Date){let start=Date.parse(resolveOpsTime(value,now));return Math.max(1,Math.ceil((now.getTime()-start)/UNIT_MS.h))}var RELATIVE_WINDOW,time,opsArgs,OPS_STANDARD_ARG_KEYS,UNIT_MS,init_args=__esm({"../../packages/api-contracts/dist/esm/ops/args.js"(){"use strict";RELATIVE_WINDOW=/^(\d+)(m|h|d|w)$/,time=z14.string().trim().min(1).max(64).refine(value=>RELATIVE_WINDOW.test(value)||!Number.isNaN(Date.parse(value)),{message:"Expected an ISO timestamp or a relative window such as 30m, 24h, 7d or 2w"}),opsArgs={project:z14.uuid().describe("Fimo project id"),org:z14.string().trim().min(1).max(255).describe("Organization id"),user:z14.string().trim().min(1).max(255).describe("User id"),env:z14.string().trim().min(1).max(255).describe("Project environment (branch), e.g. main or prod"),since:time.describe("Start of the window: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:time.describe("End of the window: ISO timestamp or relative (defaults to now)"),limit:z14.coerce.number().int().min(1).max(1e3).describe("Maximum results"),cursor:z14.string().trim().min(1).max(2e3).describe("Continue from a previous page"),query:z14.string().trim().min(1).max(200).describe("Free-text search"),reason:z14.string().trim().min(1).max(1e3).describe("Why this is being read or changed; stored in the audit log"),output:z14.string().trim().min(1).max(4096).describe("Write the result to this local file")},OPS_STANDARD_ARG_KEYS=Object.keys(opsArgs),UNIT_MS={m:6e4,h:36e5,d:864e5,w:6048e5};__name(resolveOpsTime,"resolveOpsTime");__name(opsHoursSince,"opsHoursSince")}});var init_types=__esm({"../../packages/api-contracts/dist/esm/ops/types.js"(){"use strict"}});function compact(value){return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0))}function time2(value){return value===void 0?void 0:resolveOpsTime(value)}function seg(value){return encodeURIComponent(value)}var init_shared=__esm({"../../packages/api-contracts/dist/esm/ops/commands/shared.js"(){"use strict";init_args();__name(compact,"compact");__name(time2,"time");__name(seg,"seg")}});import{z as z15}from"zod";var invocation,span,agentCommands,init_agent=__esm({"../../packages/api-contracts/dist/esm/ops/commands/agent.js"(){"use strict";init_ops();init_args();init_types();init_shared();invocation=z15.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z15.string().trim().min(1).max(255).describe("Braintrust span id"),agentCommands=[{id:"agent.chats.recent",summary:"Read recent chat messages across every project in a time window",permission:"ops:project:chat:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional().describe("Only messages from this environment"),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z15.boolean().default(!1).describe("Include complete message parts instead of the slim transcript"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat/messages/recent",body:compact({from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"agent.chats.create",summary:"Create an agent chat with routines in a customer project, as the organization owner. Validate the spec and confirm intent first: routines run and spend credits",permission:"ops:project:agents:write",effect:"write",risk:"low",input:z15.object({project:opsArgs.project,spec:z15.record(z15.string(),z15.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{id:"agent.traces.list",summary:"List agent runs for a project, organization or thread, with cost and status",permission:"ops:project:read",effect:"read",input:z15.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z15.uuid().optional().describe("Chat thread id"),agent:z15.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z15.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z15.boolean().default(!1).describe("Only runs that recorded a Braintrust root span"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/list",body:compact({projectId:input.project,organizationId:input.org,threadId:input.thread,agentKey:input.agent,status:input.status,since:time2(input.since),minCostUsd:input.minCost,tracedOnly:input.tracedOnly,limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.budget",summary:"List chats whose runs crossed the context budget and had to wrap up (content-free)",permission:"ops:braintrust:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),limit:opsArgs.limit.max(25).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/budget-wrap-up",body:compact({since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.spans",summary:"List the spans of one agent run",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,limit:opsArgs.limit.max(500).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans`,body:{limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.span",summary:"Read one span body (input and output) of an agent run",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,span,maxChars:z15.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z15.boolean().default(!1).describe("Return the end of an over-long body instead of the start"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}`,body:{maxChars:input.maxChars,edge:input.tail?"end":"start",reason:input.reason}}),"request")},{id:"agent.traces.messages",summary:"Read the conversation the model saw in one LLM span",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,span,message:z15.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z15.coerce.number().int().min(500).max(2e5).default(2e4),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}/messages`,body:compact({messageIndex:input.message,maxChars:input.maxChars,reason:input.reason})}),"request")},{id:"agent.traces.stats",summary:"Aggregate agent step latency, tokens and cost by model, provider, span or type",permission:"ops:braintrust:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z15.coerce.number().positive().optional().describe("Only steps at least this many seconds slow"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/stats",body:compact({since:time2(input.since),until:time2(input.until),groupBy:input.groupBy,spanType:input.spanType,slowerThanSeconds:input.slowerThan,limit:input.limit,reason:input.reason})}),"request")}]}});import{z as z16}from"zod";var assistantCommands,init_assistant=__esm({"../../packages/api-contracts/dist/esm/ops/commands/assistant.js"(){"use strict";init_args();init_types();init_shared();assistantCommands=[{id:"assistant.threads.list",summary:"List your admin assistant threads, newest activity first",permission:"ops:platform:read",effect:"read",input:z16.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z16.coerce.number().int().min(1).max(100).optional().describe("Maximum results"),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/assistant/threads",query:{q:input.query,limit:input.limit,cursor:input.cursor}}),"request")},{id:"assistant.threads.get",summary:"Read one admin assistant thread with every message",permission:"ops:platform:read",effect:"read",input:z16.object({thread:z16.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z17}from"zod";var day,billingCommands,init_billing=__esm({"../../packages/api-contracts/dist/esm/ops/commands/billing.js"(){"use strict";init_args();init_types();init_shared();day=z17.iso.date().describe("UTC day, YYYY-MM-DD"),billingCommands=[{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z17.object({customer:z17.string().trim().min(1).max(255).describe("Hyperline customer id"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/customers/${seg(input.customer)}`,query:{reason:input.reason}}),"request")},{id:"billing.org",summary:"Read an organization's billing state: subscription, plan projection, credits and wallet",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"billing.bandwidth-contract",summary:"Read an organization's hosting bandwidth contract and current usage",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}/bandwidth-contract`,query:{reason:input.reason}}),"request")},{id:"billing.ledger",summary:"Read an organization's credit ledger: holds, settlements, grants or usage events",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,kind:z17.enum(["holds","settlements","grants","usage-events"]),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/ledger",query:compact({organizationId:input.org,kind:input.kind,since:time2(input.since),limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z17.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z17.iso.datetime({offset:!0}).optional().describe("Reuse evaluatedAt when resuming a scan"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/plan-projections/report",query:compact({reason:input.reason,at:input.at??new Date().toISOString(),cursor:input.cursor})}),"request")},{id:"billing.plans.reconcile",summary:"Repair organizations' local plan projections from Hyperline",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({orgs:z17.array(opsArgs.org).min(1).max(100).describe("Organization ids")})},{id:"billing.legacy-premium.report",summary:"Report legacy Premium organizations and where each stands in the Pro transition",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org.optional(),limit:opsArgs.limit.max(200).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/legacy-premium-report",query:compact({reason:input.reason,org:input.org,limit:input.limit})}),"request")},{id:"billing.legacy-premium.enroll",summary:"Record the approved Pro offer for one legacy Premium organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({org:opsArgs.org,deadline:z17.string().trim().min(1).max(64).describe("Decision date exactly 90 calendar days from today")})},{id:"billing.legacy-premium.comp",summary:"Accept an internal organization's Pro offer on its behalf, free through a 100% coupon",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({org:opsArgs.org,coupon:z17.string().trim().min(1).max(64).describe("Hyperline coupon id: 100% off every product")})},{id:"billing.legacy-premium.notify",summary:"Send the due legacy Premium transition notices for one organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({org:opsArgs.org})},{id:"billing.entitlements.sync",summary:"Reconcile subscription entitlement properties in Hyperline with Fimo's plans (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({batchSize:z17.coerce.number().int().min(1).max(100).default(50),concurrency:z17.coerce.number().int().min(1).max(10).default(2),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.agent-runtime.attach",summary:"Attach the Agent runtime product to PAYG and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({orgs:z17.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z17.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.dispatches.list",summary:"List billing usage dispatches to Hyperline by state",permission:"ops:billing:read",effect:"read",input:z17.object({state:z17.enum(["pending","dispatched","dead-lettered","discarded"]),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/billing/dispatches",body:{state:input.state,reason:input.reason}}),"request")},{id:"billing.dispatches.discard",summary:"Discard dead-lettered billing dispatches so they are never sent",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({dispatches:z17.array(z17.uuid()).min(1).max(100).describe("Dispatch ids")})},{id:"billing.dispatches.retry",summary:"Retry a dead-lettered billing dispatch",permission:"ops:billing:write",effect:"write",risk:"low",input:z17.object({dispatch:z17.uuid().describe("Dispatch id")})},{id:"billing.cache.invalidate",summary:"Clear an organization's cached billing state so the next read goes to Hyperline",permission:"ops:billing:write",effect:"write",risk:"low",input:z17.object({org:opsArgs.org})},{id:"billing.hosting-usage.day",summary:"Read hosting usage recorded for one source, meter and day",permission:"ops:billing:read",effect:"read",input:z17.object({source:z17.string().trim().min(1).max(100),meter:z17.string().trim().min(1).max(100),day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage",query:{source:input.source,meter:input.meter,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.reconciliation",summary:"Compare a project's served traffic with the hosting usage billed for one day",permission:"ops:billing:read",effect:"read",input:z17.object({project:opsArgs.project,day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/reconciliation",query:{projectId:input.project,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.periods",summary:"List an organization's hosting billing periods",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/customer-periods",query:{organizationId:input.org,reason:input.reason}}),"request")}]}});import{z as z18}from"zod";var coreCommands,init_core=__esm({"../../packages/api-contracts/dist/esm/ops/commands/core.js"(){"use strict";init_args();init_types();init_shared();coreCommands=[{id:"find",summary:"Find projects, organizations or users by name, slug, domain, email or id",permission:"ops:project:read",effect:"read",input:z18.object({query:opsArgs.query,kind:z18.enum(["project","org","user"]).optional().describe("Only this kind of record"),limit:opsArgs.limit.max(100).default(20),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/find",query:compact({q:input.query,kind:input.kind,limit:input.limit,cursor:input.cursor})}),"request"),cli:{positional:"query"}},{id:"audit.list",summary:"List audit log entries, newest first",permission:"ops:audit:read",effect:"read",input:z18.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z18.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z18.string().trim().min(1).max(64).optional().describe("Audit action, e.g. project_takedown"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"GET",path:"/audit",query:compact({projectId:input.project,organizationId:input.org,actor:input.actor,action:input.action,since:time2(input.since),limit:input.limit})}),"request")}]}});import{z as z19}from"zod";var window2,healthCommands,init_health=__esm({"../../packages/api-contracts/dist/esm/ops/commands/health.js"(){"use strict";init_organization_features_dto();init_ops();init_args();init_types();init_shared();window2={since:opsArgs.since,until:opsArgs.until.optional()},healthCommands=[{id:"health.overview",summary:"Platform health brief: Sentry, logs, agents, publishing and support in one window",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional().describe("Narrow every source that can be narrowed to one project"),limit:opsArgs.limit.max(100).default(25).describe("Maximum findings per source"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.agents",summary:"Agent run outcomes, cost and duration grouped by agent, status, branch, project or day",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z19.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z19.boolean().default(!1).describe("Count sub-steps too"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,branch:input.env,agentKey:input.agent,groupBy:input.groupBy,includeChildren:input.includeChildren,limit:input.limit,reason:input.reason})}),"request")},{id:"health.context",summary:"Context-window pressure and compaction facts for agent turns",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(500),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/context-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.memory",summary:"Agent memory health: threads and routines with missing or stale memory",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/memory-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.providers",summary:"Model provider errors grouped by signature, optionally correlated to agent runs",permission:"ops:braintrust:read",effect:"read",input:z19.object({...window2,model:z19.string().trim().min(1).max(200).optional(),provider:z19.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z19.string().trim().min(1).max(64).optional().describe("Page boundary: nextBefore from the previous page"),limit:opsArgs.limit.max(1e3).default(500).describe("Error spans to scan per page"),correlate:z19.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z19.coerce.number().int().min(1).max(100).default(25),sampleChars:z19.coerce.number().int().min(200).max(2e4).default(1200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-provider-errors",body:compact({since:time2(input.since),until:time2(input.until),model:input.model,provider:input.provider,spanType:input.spanType,before:input.before,limit:input.limit,sampleChars:input.sampleChars,correlateInvocations:input.correlate||void 0,correlationLimit:input.correlate?input.correlationLimit:void 0,reason:input.reason})}),"request")},{id:"health.chat-history.summary",summary:"How often agents call the chatHistory tool and whether it finds what they need",permission:"ops:project:read",effect:"read",input:z19.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat-history/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,reason:input.reason})}),"request")},{id:"health.chat-history.calls",summary:"List chatHistory tool calls; --with-content adds the surrounding messages (needs chat read)",permission:"ops:project:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z19.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:input.withContent?"/chat-history/calls/content":"/chat-history/calls",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.chat-history.judge",summary:"Have a model judge a sample of chatHistory calls; --calibrate runs the labelled benchmark",permission:"ops:project:chat:read",effect:"read",input:z19.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z19.coerce.number().int().min(1).max(25).default(10),calibrate:z19.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>input.calibrate?{method:"POST",path:"/chat-history/judge/calibration",body:{reason:input.reason}}:{method:"POST",path:"/chat-history/judge",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,sample:input.sample,reason:input.reason})},"request")},{id:"health.data-usage",summary:"Data-provider usage (search, scraping, enrichment) grouped by operation, provider, day, org or agent",permission:"ops:project:read",effect:"read",input:z19.object({...window2,org:opsArgs.org.optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/data-usage",body:compact({since:time2(input.since),until:time2(input.until),organizationId:input.org,groupBy:input.groupBy,limit:input.limit,reason:input.reason})}),"request")},{id:"health.routines",summary:"Routine runs, event bursts, Jev trigger calls and cost, by routine, plan, day or project",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z19.string().trim().min(1).max(64).optional().describe("Template routine key, or custom"),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total").describe("Rank buckets by total cost, Jev's trigger cost, or runs"),burstMinutes:z19.coerce.number().int().min(1).max(120).default(10).describe("An event this many minutes or less after the routine's previous one is a burst"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/routine-metrics",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,plan:input.plan,routine:input.routine,groupBy:input.groupBy,sortBy:input.sortBy,burstMinutes:input.burstMinutes,reason:input.reason})}),"request")},{id:"health.analytics",summary:"Whether a project's website analytics are arriving (content-free counts, max 7 days)",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z19.string().max(300).optional().describe("Exact test path ending in ?fimo_monitor=<UUID>"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/analytics-health`,body:compact({branch:input.env,canaryPath:input.canaryPath,since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason})}),"request")},{id:"health.session",summary:"A project's work-session and database-branch health: cleanup due, unresolved allocations, capacity",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,checkProvider:z19.boolean().default(!1).describe("Include one bounded read-only Neon inventory page"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/session-health`,body:{reason:input.reason,limit:input.limit,checkProvider:input.checkProvider}}),"request")},{id:"health.sandbox",summary:"A project environment's sandbox and preview status",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,env:opsArgs.env.default("main"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/sandbox/status`,body:{projectEnv:input.env,reason:input.reason}}),"request")},{id:"health.schedules",summary:"Failed scheduled runs and webhook deliveries",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z19.uuid().optional().describe("Schedule id"),run:z19.uuid().optional().describe("Schedule run id (needs --project)"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/schedules/failures",body:compact({projectId:input.project,projectEnv:input.env,scheduleId:input.schedule,runId:input.run,since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"health.integrations",summary:"Failing integration connections and inbound events",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/integrations/failures",body:compact({projectId:input.project,reason:input.reason})}),"request")},{id:"health.domains",summary:"Custom domains with DNS, SSL or provider problems",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/domains/problems",body:compact({projectId:input.project,organizationId:input.org,reason:input.reason})}),"request")}]}});import{z as z20}from"zod";var mergeCommands,init_merge=__esm({"../../packages/api-contracts/dist/esm/ops/commands/merge.js"(){"use strict";init_args();init_types();init_shared();mergeCommands=[{id:"merge.list",summary:"List merges, newest first; --stuck lists only merges that stopped progressing",permission:"ops:merges:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),stuck:z20.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z20.string().trim().min(1).max(64).optional().describe("Only merges in this status"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/merges",query:compact({projectId:input.project,stuck:input.stuck||void 0,status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"merge.get",summary:"Show one merge with its steps, conflicts and release",permission:"ops:merges:read",effect:"read",input:z20.object({merge:z20.uuid().describe("Merge id")}),request:__name(input=>({method:"GET",path:`/merges/${seg(input.merge)}`}),"request")},{id:"merge.unwind",summary:"Force-unwind a stuck merge: reset the target branch to its pre-merge head and reopen the merge",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z20.object({merge:z20.uuid().describe("Merge id")})},{id:"merge.fail",summary:"Force-fail a stuck merge without touching the target branch",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z20.object({merge:z20.uuid().describe("Merge id")})}]}});import{z as z21}from"zod";var channel,draft,notifyCommands,init_notify=__esm({"../../packages/api-contracts/dist/esm/ops/commands/notify.js"(){"use strict";init_ops();init_args();init_types();init_shared();channel=z21.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z21.uuid().describe("Draft id"),notifyCommands=[{id:"notify.draft",summary:"Draft a customer-visible message: an email to a project owner or a reply on a Pylon ticket",permission:"ops:notification:preview",effect:"write",risk:"low",input:z21.object({channel,message:z21.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z21.email().optional().describe("email: override the recipient"),subject:z21.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z21.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z21.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z21.array(z21.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z21.array(z21.email()).max(50).optional(),bccEmails:z21.array(z21.email()).max(50).optional()}),cli:{fileArgs:["message"]}},{id:"notify.show",summary:"Show a drafted customer message and its approval state",permission:"ops:notification:preview",effect:"read",input:z21.object({channel,draft}),request:__name(input=>({method:"GET",path:input.channel==="pylon"?`/support/pylon/replies/${seg(input.draft)}`:`/notifications/${seg(input.draft)}`}),"request")},{id:"notify.approve",summary:"Approve a drafted customer message (a person must approve before it can be sent)",permission:"ops:notification:approve",effect:"write",risk:"low",humanOnly:!0,input:z21.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z21.object({channel,draft})}]}});function normalizeSentryIssueReference(reference){let trimmed=reference.trim();if(SENTRY_ISSUE_ID_PATTERN.test(trimmed))return trimmed;let url;try{url=new URL(trimmed)}catch{throw new Error("Expected a Sentry issue id or /issues/<id>/ URL")}let segments=url.pathname.split("/").filter(Boolean),issuesIndex=segments.lastIndexOf("issues"),issueId=issuesIndex>=0&&issuesIndex===segments.length-2?segments[issuesIndex+1]:void 0;if(!issueId||!SENTRY_ISSUE_ID_PATTERN.test(issueId))throw new Error("Expected a Sentry issue id or /issues/<id>/ URL");return issueId}function collectTraceIds(value,candidates,depth=0){if(!(depth>32)){if(typeof value=="string"){TRACE_ID_PATTERN.test(value.trim())&&candidates.add(value.trim().toLowerCase());return}if(Array.isArray(value)){for(let item of value)collectTraceIds(item,candidates,depth+1);return}if(typeof value=="object"&&value!==null)for(let item of Object.values(value))collectTraceIds(item,candidates,depth+1)}}function normalizeTempoTraceReference(reference){let trimmed=reference.trim();if(TRACE_ID_PATTERN.test(trimmed))return trimmed.toLowerCase();let url;try{url=new URL(trimmed)}catch{throw new Error("Expected an exact 32-character trace id or a Grafana trace URL")}let candidates=new Set;for(let segment of url.pathname.split("/"))collectTraceIds(segment,candidates);for(let value of url.searchParams.values()){collectTraceIds(value,candidates);try{collectTraceIds(JSON.parse(value),candidates)}catch{continue}}if(candidates.size!==1)throw new Error(candidates.size===0?"Grafana URL did not contain a trace id":"Grafana URL contained multiple trace ids");return[...candidates][0]}var SENTRY_ISSUE_ID_PATTERN,TRACE_ID_PATTERN,init_references2=__esm({"../../packages/api-contracts/dist/esm/ops/references.js"(){"use strict";SENTRY_ISSUE_ID_PATTERN=/^[a-zA-Z0-9-]{1,100}$/,TRACE_ID_PATTERN=/^[a-fA-F0-9]{32}$/;__name(normalizeSentryIssueReference,"normalizeSentryIssueReference");__name(collectTraceIds,"collectTraceIds");__name(normalizeTempoTraceReference,"normalizeTempoTraceReference")}});import{z as z22}from"zod";function parseWhere(values){if(!(!values||values.length===0))return Object.fromEntries(values.map(value=>{let separator=value.indexOf("=");if(separator<1)throw new Error("--where expects key=value");return[value.slice(0,separator),value.slice(separator+1)]}))}var issue,logFilters,observeCommands,init_observe=__esm({"../../packages/api-contracts/dist/esm/ops/commands/observe.js"(){"use strict";init_args();init_references2();init_types();init_shared();issue=z22.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z22.array(z22.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z22.string().min(1).max(500).optional().describe("Plain-text line filter"),limit:opsArgs.limit.max(1e3).default(100),reason:opsArgs.reason,output:opsArgs.output.optional()},observeCommands=[{id:"observe.logs.query",summary:"Query a project's production logs in a time window",permission:"ops:logs:read",effect:"read",input:z22.object({...logFilters,since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}),"request")},{id:"observe.logs.around",summary:"Read a project's production logs a few minutes either side of a moment",permission:"ops:logs:read",effect:"read",input:z22.object({...logFilters,at:z22.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z22.coerce.number().int().min(1).max(120).default(5).describe("Minutes before and after")}),request:__name(input=>{let at2=Date.parse(input.at);return{method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:new Date(at2-input.minutes*6e4).toISOString(),to:new Date(at2+input.minutes*6e4).toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}},"request")},{id:"observe.traces.get",summary:"Read one Grafana Tempo trace (id or Grafana URL) for a project",permission:"ops:traces:read",effect:"read",input:z22.object({trace:z22.string().trim().min(1).max(4e3).describe("32-character trace id or Grafana trace URL"),project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/traces/${normalizeTempoTraceReference(input.trace)}`,body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"observe.sentry.issues",summary:"Search Sentry issues, for one project or every project",permission:"ops:sentry:read",effect:"read",input:z22.object({project:opsArgs.project.optional(),search:z22.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z22.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z22.enum(["date","new","freq","user","trends"]).optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/sentry/issues",body:compact({projectId:input.project,query:input.search,statsPeriod:input.period,sort:input.sort,limit:input.limit,reason:input.reason})}),"request")},{id:"observe.sentry.issue",summary:"Read one Sentry issue",permission:"ops:sentry:read",effect:"read",input:z22.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.event",summary:"Read one full Sentry event",permission:"ops:sentry:read",effect:"read",input:z22.object({event:z22.string().trim().min(1).max(100).describe("Sentry event id"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/events/${seg(input.event)}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.latest-event",summary:"Read the latest full event of a Sentry issue",permission:"ops:sentry:read",effect:"read",input:z22.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}/events/latest`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.resolve",summary:"Mark a Sentry issue resolved",permission:"ops:sentry:write",effect:"write",risk:"low",input:z22.object({issue})},{id:"observe.posthog.milestones",summary:"Count a project's PostHog lifecycle milestones (create, deploy, first publish) in a window",permission:"ops:posthog:read",effect:"read",input:z22.object({project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/posthog/milestones",body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")}]}});import{z as z23}from"zod";var orgCommands,init_org=__esm({"../../packages/api-contracts/dist/esm/ops/commands/org.js"(){"use strict";init_organization_features_dto();init_args();init_types();init_shared();orgCommands=[{id:"org.get",summary:"Show an organization: plan, members, projects and subscription summary",permission:"ops:organizations:read",effect:"read",input:z23.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"org.features.list",summary:"List an organization's features and any staff overrides",permission:"ops:customers:read",effect:"read",input:z23.object({org:opsArgs.org}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}/features`}),"request")},{id:"org.features.set",summary:"Force an organization feature on or off, or clear the override",permission:"ops:organization:features:write",effect:"write",risk:"low",humanOnly:!0,input:z23.object({org:opsArgs.org,feature:z23.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z23.enum(["on","off","default"]).describe("on, off, or default to clear the override")})},{id:"org.takedown",summary:"Take every project of an organization off Fimo domains and block publishing",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.delete",summary:"Delete an organization and everything it owns permanently",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.credits.topup",summary:"Grant credits to an organization, free or as a recorded purchase",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org,credits:z23.coerce.number().int().positive().describe("Number of credits"),type:z23.enum(["free","purchase"]).default("free"),amountCents:z23.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z23.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z23.string().trim().optional().describe("Note shown with the grant")})},{id:"org.credits.burn-zombies",summary:"Burn credits held by abandoned (zombie) holds of one organization since a date",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z24}from"zod";var OPS_PLATFORM_DASHBOARDS,platformCommands,init_platform=__esm({"../../packages/api-contracts/dist/esm/ops/commands/platform.js"(){"use strict";init_args();init_types();init_shared();OPS_PLATFORM_DASHBOARDS=["agents","money","projects","automation","growth","platform","usage","stats"],platformCommands=[{id:"platform.metrics",summary:"Read an admin dashboard as data: agents, money, projects, automation, growth, platform, usage or stats",permission:"ops:platform:read",effect:"read",input:z24.object({dashboard:z24.enum(OPS_PLATFORM_DASHBOARDS),since:opsArgs.since.default("7d"),until:opsArgs.until.optional()}),request:__name(input=>({method:"GET",path:"/platform/metrics",query:compact({dashboard:input.dashboard,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"platform.pool.status",summary:"Show the warm sandbox pool: size, target, and projects waiting in it",permission:"ops:platform:read",effect:"read",input:z24.object({}),request:__name(()=>({method:"GET",path:"/platform/pool"}),"request")},{id:"platform.pool.refill",summary:"Top the warm sandbox pool up to its target size",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.pool.flush",summary:"Delete warm sandboxes from the pool, all of them or only the listed ones (new projects start cold until it refills)",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({pooled:z24.array(z24.uuid()).min(1).max(500).optional().describe("Only these pooled project ids; omit to flush all")})},{id:"platform.maintenance.status",summary:"Show whether maintenance mode is on and its message",permission:"ops:platform:read",effect:"read",input:z24.object({}),request:__name(()=>({method:"GET",path:"/platform/maintenance"}),"request")},{id:"platform.maintenance.enable",summary:"Turn maintenance mode on: Studio shows the message and refuses work",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({message:z24.string().max(500).optional().describe("Message shown to users")})},{id:"platform.maintenance.disable",summary:"Turn maintenance mode off",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.maintenance.message",summary:"Change the maintenance message without toggling maintenance mode",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({message:z24.string().max(500).describe("Message shown to users")})},{id:"platform.sync-all",summary:"Re-sync every project's database records from its repository",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.sync-tenant-schemas",summary:"Apply pending tenant schema migrations to every project database",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z24.object({event:z24.string().trim().min(1).max(255).describe("Inbound event id")})},{id:"platform.onboardings.list",summary:"List site onboardings (start from an existing website) with their status",permission:"ops:platform:read",effect:"read",input:z24.object({status:z24.string().trim().min(1).max(64).optional(),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/onboardings",query:compact({status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.onboardings.get",summary:"Show one project's site onboarding: questions, answers, refusal and timeline",permission:"ops:platform:read",effect:"read",input:z24.object({project:opsArgs.project,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/platform/onboardings/${seg(input.project)}`,query:{reason:input.reason}}),"request")},{id:"platform.onboardings.lift-refusal",summary:"Lift a site onboarding's Terms refusal so the project can continue",permission:"ops:platform:write",effect:"write",risk:"low",input:z24.object({project:opsArgs.project})},{id:"platform.unclaimed.list",summary:"List unclaimed projects (created without an account) and their claim state",permission:"ops:platform:read",effect:"read",input:z24.object({since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/unclaimed",query:compact({since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.resources.resolve",summary:"Resolve any id, URL, email or domain to the Fimo record it names",permission:"ops:platform:read",effect:"read",input:z24.object({query:z24.string().trim().min(1).max(512).describe("Id, URL, email or domain")}),request:__name(input=>({method:"GET",path:"/platform/resources/resolve",query:{q:input.query}}),"request"),cli:{positional:"query"}}]}});import{z as z25}from"zod";function files(project,action,env){return`/projects/${seg(project)}/files/${action}?projectEnv=${seg(env)}`}var envMain,projectCommands,init_project=__esm({"../../packages/api-contracts/dist/esm/ops/commands/project.js"(){"use strict";init_args();init_types();init_shared();envMain=opsArgs.env.default("main");__name(files,"files");projectCommands=[{id:"project.get",summary:"Inspect a project: owner, environments, domains, publications, recent runs and logs",permission:"ops:project:read",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,since:opsArgs.since.default("24h"),limit:opsArgs.limit.max(500).default(100).describe("Maximum log entries")}),request:__name(input=>({method:"GET",path:`/projects/${seg(input.project)}/inspect`,query:{projectEnv:input.env,hours:Math.min(168,opsHoursSince(input.since)),logLimit:input.limit}}),"request")},{id:"project.snapshot",summary:"Download a zip snapshot of a project's source and content",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/snapshot`,body:{reason:input.reason}}),"request")},{id:"project.chat",summary:"Read a project's agent chat transcript (the most recently active chat unless --thread is set)",permission:"ops:project:chat:read",effect:"read",input:z25.object({project:opsArgs.project,thread:z25.uuid().optional().describe("One chat thread id"),env:opsArgs.env.optional().describe("Only turns that targeted this environment"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z25.boolean().default(!1).describe("Include tool inputs, outputs and other message parts"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/chat/messages`,body:compact({projectEnv:input.env,threadId:input.thread,from:time2(input.since),to:time2(input.until),limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"project.files.read",summary:"Read one source file from a project environment",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,path:z25.string().trim().min(1).max(1024).describe("File path relative to the project root"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:files(input.project,"read",input.env),body:{path:input.path,reason:input.reason}}),"request")},{id:"project.files.glob",summary:"List source file paths in a project environment",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,pattern:z25.string().min(1).max(300).optional().describe("Glob pattern, e.g. src/**/*.tsx"),limit:opsArgs.limit.max(2e3).default(2e3),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"glob",input.env),body:compact({pattern:input.pattern,limit:input.limit,reason:input.reason})}),"request")},{id:"project.files.grep",summary:"Search source files in a project environment with a regular expression",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,pattern:z25.string().min(1).max(200).describe("Regular expression"),include:z25.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z25.boolean().default(!1),limit:opsArgs.limit.max(200).default(100).describe("Maximum matches"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"grep",input.env),body:compact({pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.limit,reason:input.reason})}),"request")},{id:"project.files.package-manager",summary:"Report which package manager a project declares and which lockfiles it has",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"package-manager",input.env),body:{reason:input.reason}}),"request")},{id:"project.files.write",summary:"Create or replace one source file in a project environment (commits to its branch)",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,path:z25.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z25.string().max(256*1024).describe("The exact desired file contents"),overwrite:z25.boolean().default(!1).describe("Allow replacing an existing file")}),cli:{fileArgs:["content"]}},{id:"project.runtime.bump",summary:"Pin the project's fimo runtime packages to an exact version, install, and restart the dev server",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,version:z25.string().trim().min(1).max(64).describe("Exact target version, e.g. 0.11.0")})},{id:"project.preview.restart",summary:"Restart the project's preview dev server",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain})},{id:"project.publish",summary:"Publish the customer's site on their behalf. Only when a Fimo admin explicitly asks for it; never on an agent's own initiative",permission:"ops:project:publish",effect:"write",risk:"high",humanOnly:!0,consent:!0,input:z25.object({project:opsArgs.project,env:opsArgs.env.optional().describe("Source environment; defaults to the project's publish source")})},{id:"project.domain.refresh",summary:"Refresh a custom domain's provider and SSL state",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z25.object({project:opsArgs.project,domain:z25.uuid().describe("Project domain id")})},{id:"project.migrations.dry-run",summary:"Plan a source migration for one project without changing it",permission:"ops:project:read",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,migration:z25.string().trim().min(1).max(120).optional().describe("Migration id (default: the current one)"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/migrations/projects/${seg(input.project)}/dry-run`,body:compact({migrationId:input.migration,projectEnv:input.env,reason:input.reason})}),"request")},{id:"project.sync",summary:"Re-sync a project's database records from its repository",permission:"ops:project:operate",effect:"write",risk:"low",input:z25.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z25.object({project:opsArgs.project,type:z25.enum(["dev","published"]).default("dev").describe("dev (the preview) or published (the live site)")})},{id:"project.version.restore",summary:"Restore a project environment to an earlier version (overwrites the current state)",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,version:z25.string().trim().min(1).max(255).describe("Version id to restore")})},{id:"project.takedown",summary:"Take a project off Fimo domains and block it from publishing",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})},{id:"project.restore",summary:"Lift a project takedown so it can serve and publish again",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})},{id:"project.transfer",summary:"Move a project to another organization",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,toOrg:opsArgs.org.describe("Destination organization id")})},{id:"project.delete",summary:"Delete a project and its resources permanently",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})}]}});import{z as z26}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=z26.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z26.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z26.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z26.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z26.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z26.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z26.enum(["user","agent","system"]),SupportReportTagSchema=z26.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z26.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z26.object({organization:z26.object({id:z26.string().trim().min(1).max(255),name:z26.string().trim().max(240).optional()}),project:z26.object({id:z26.uuid(),name:z26.string().trim().max(240).optional(),createdAt:z26.coerce.date().optional()}).optional(),environment:z26.string().trim().max(255).optional(),clientVersion:z26.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z26.object({message:z26.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z26.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z26.string().trim().max(200).optional(),limit:z26.coerce.number().int().min(1).max(100).default(50),offset:z26.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z26.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z26.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z26.uuid().nullable().optional(),note:z26.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=z26.object({message:z26.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z26.object({kind:SupportReportLinkKindSchema,label:z26.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z26.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z26.object({kind:SupportReportActorKindSchema,id:z26.string().nullable(),name:z26.string().nullable()}),SupportReportLinkDTOSchema=z26.object({id:z26.uuid(),kind:SupportReportLinkKindSchema,label:z26.string(),url:SupportReportHttpUrlSchema,externalId:z26.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z26.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z26.object({id:z26.uuid(),kind:SupportReportEventKindSchema,body:z26.string().nullable(),metadata:z26.record(z26.string(),z26.unknown()),actor:SupportReportActorDTOSchema,createdAt:z26.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z26.object({id:z26.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z26.array(z26.string()),source:SupportReportSourceSchema,message:z26.string(),reporter:z26.object({id:z26.string().nullable(),name:z26.string().nullable(),email:z26.string().nullable()}),organization:z26.object({id:z26.string().nullable(),name:z26.string()}),project:z26.object({id:z26.uuid().nullable(),name:z26.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z26.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z26.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z26.string().nullable(),deliveredAt:z26.coerce.date().nullable()}).nullable(),duplicateOfReportId:z26.uuid().nullable(),resolvedAt:z26.coerce.date().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z26.string().nullable(),clientVersion:z26.string().nullable(),links:z26.array(SupportReportLinkDTOSchema),events:z26.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z26.object({reports:z26.array(SupportReportSummaryDTOSchema),total:z26.number().int().nonnegative(),statusCounts:z26.object({new:z26.number().int().nonnegative(),in_progress:z26.number().int().nonnegative(),waiting:z26.number().int().nonnegative(),resolved:z26.number().int().nonnegative(),duplicate:z26.number().int().nonnegative(),irrelevant:z26.number().int().nonnegative(),ignored:z26.number().int().nonnegative()}),limit:z26.number().int().positive(),offset:z26.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z26.object({id:z26.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z26.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z27}from"zod";var report,pylonIssue,supportCommands,init_support=__esm({"../../packages/api-contracts/dist/esm/ops/commands/support.js"(){"use strict";init_support_report_dto();init_ops();init_args();init_types();init_shared();report=z27.uuid().describe("Support report id"),pylonIssue=OpsPylonIssueIdSchema.describe("Pylon issue id"),supportCommands=[{id:"support.reports.list",summary:"List Fimo support reports, newest first",permission:"ops:support:read",effect:"read",input:z27.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z27.string().trim().min(1).max(50).optional(),search:z27.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z27.coerce.number().int().min(0).default(0),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/reports",query:compact({reason:input.reason,status:input.status,category:input.category,source:input.source,tag:input.tag,query:input.search,limit:input.limit,offset:input.offset})}),"request")},{id:"support.reports.get",summary:"Read one support report with its messages, links and context",permission:"ops:support:read",effect:"read",input:z27.object({report,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:`/support/reports/${seg(input.report)}`,query:{reason:input.reason}}),"request")},{id:"support.reports.claim",summary:"Claim a support report (mark it in progress), optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,note:z27.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.update",summary:"Change a support report's status, category, tags or duplicate link, optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z27.array(z27.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z27.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z27.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.note",summary:"Add an internal message to a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,message:z27.string().trim().min(1).max(2e4)}),cli:{fileArgs:["message"]}},{id:"support.reports.link",summary:"Link a support report to a Linear issue, Pylon ticket, project, Sentry issue or other URL",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,kind:SupportReportLinkKindSchema,label:z27.string().trim().min(1).max(240),url:z27.url({protocol:/^https?$/}).max(2e3),externalId:z27.string().trim().min(1).max(255).optional()})},{id:"support.reports.unlink",summary:"Remove a link from a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,link:z27.uuid().describe("Link id")})},{id:"support.intake",summary:"Show the support intake receipt: reports received and delivered in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z27.object({since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/support/intake/status",query:{since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"support.pylon.list",summary:"List Pylon support tickets in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z27.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z27.enum(["open","closed","all"]).default("open"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/pylon/issues",query:compact({since:time2(input.since),until:time2(input.until)??new Date().toISOString(),state:input.state,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"support.pylon.thread",summary:"Read the full message thread of a Pylon ticket",permission:"ops:support:read",effect:"read",input:z27.object({issue:pylonIssue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/support/issues/${seg(input.issue)}/thread`,body:{reason:input.reason}}),"request")},{id:"support.pylon.resolve",summary:"Close a Pylon ticket",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({issue:pylonIssue})},{id:"support.pylon.note",summary:"Add an internal note to a Pylon ticket (not visible to the customer)",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({issue:pylonIssue,message:z27.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z28}from"zod";var userCommands,init_user=__esm({"../../packages/api-contracts/dist/esm/ops/commands/user.js"(){"use strict";init_args();init_types();init_shared();userCommands=[{id:"user.get",summary:"Show a user: profile, role, organizations, recent sessions and usage",permission:"ops:users:read",effect:"read",input:z28.object({user:opsArgs.user,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/users/${seg(input.user)}`,query:{reason:input.reason}}),"request")},{id:"user.sessions",summary:"List sign-in sessions, for one user or across the platform",permission:"ops:users:read",effect:"read",input:z28.object({user:opsArgs.user.optional(),active:z28.boolean().optional().describe("Only sessions that have not expired or been revoked"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/sessions",query:compact({userId:input.user,active:input.active,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"user.session.revoke",summary:"Revoke one sign-in session",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z28.object({session:z28.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z29}from"zod";var evidence,versions,detectionQueries,watchCommands,init_watch=__esm({"../../packages/api-contracts/dist/esm/ops/commands/watch.js"(){"use strict";init_ops();init_args();init_types();init_shared();evidence=z29.array(z29.record(z29.string(),z29.unknown())).max(100),versions=z29.array(z29.string().trim().min(1).max(120)).max(100),detectionQueries=z29.array(z29.string().trim().min(1).max(2e3)).max(50),watchCommands=[{id:"watch.list",summary:"List watched projects and why each is watched",permission:"ops:customers:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/customers"}),"request")},{id:"watch.add",summary:"Watch a project (or update why it is watched)",permission:"ops:customers:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,importance:z29.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z29.string().trim().max(120).optional(),packageManager:z29.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z29.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z29.object({project:opsArgs.project}),request:__name(input=>({method:"GET",path:`/customers/${seg(input.project)}/validations`}),"request")},{id:"watch.validations.record",summary:"Record the outcome of validating a release, migration or change against a watched project",permission:"ops:validations:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,change:z29.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z29.string().trim().min(1).max(1e4),evidence:evidence.default([])}),cli:{fileArgs:["evidence"]}},{id:"watch.investigations.list",summary:"List open and recent investigations",permission:"ops:investigations:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/investigations"}),"request")},{id:"watch.investigations.create",summary:"Open an investigation into a problem on a project",permission:"ops:investigations:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,title:z29.string().trim().min(1).max(240),userReport:z29.string().trim().max(1e4).optional().describe("The customer's own words")})},{id:"watch.investigations.update",summary:"Update an investigation's status, hypothesis, outcome or evidence",permission:"ops:investigations:write",effect:"write",risk:"low",input:z29.object({investigation:z29.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z29.string().trim().max(1e4).optional(),outcome:z29.string().trim().max(1e4).optional(),evidence:evidence.optional()}),cli:{fileArgs:["evidence"]}},{id:"watch.known-issues.list",summary:"List known issues and their detection queries",permission:"ops:known-issues:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/known-issues"}),"request")},{id:"watch.known-issues.create",summary:"Record a known issue with how to detect it and any workaround",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z29.object({fingerprint:z29.string().trim().min(1).max(240),title:z29.string().trim().min(1).max(240),description:z29.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z29.string().trim().min(1).max(64).optional(),workaround:z29.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.default("open")}),cli:{fileArgs:["detectionQueries"]}},{id:"watch.known-issues.update",summary:"Update a known issue",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z29.object({knownIssue:z29.uuid().describe("Known issue id"),title:z29.string().trim().min(1).max(240).optional(),description:z29.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z29.string().trim().min(1).max(64).optional(),workaround:z29.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.optional()}),cli:{fileArgs:["detectionQueries"]}}]}});var OPS_COMMANDS,BY_ID,OPS_OPERATION_IDS,init_commands=__esm({"../../packages/api-contracts/dist/esm/ops/commands/index.js"(){"use strict";init_agent();init_assistant();init_billing();init_core();init_health();init_merge();init_notify();init_observe();init_org();init_platform();init_platform();init_project();init_support();init_user();init_watch();OPS_COMMANDS=[...coreCommands,...projectCommands,...orgCommands,...userCommands,...mergeCommands,...agentCommands,...healthCommands,...billingCommands,...platformCommands,...observeCommands,...supportCommands,...watchCommands,...notifyCommands,...assistantCommands],BY_ID=new Map(OPS_COMMANDS.map(command=>[command.id,command])),OPS_OPERATION_IDS=OPS_COMMANDS.filter(command=>command.effect==="write").map(command=>command.id)}});import{z as z30}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=z30.object({kind:z30.literal("say"),label:z30.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z30.string().min(1).max(240).optional(),message:z30.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z30.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z30.discriminatedUnion("command",[z30.object({kind:z30.literal("app"),command:z30.literal("publish")}).strict(),z30.object({kind:z30.literal("app"),command:z30.literal("connect"),integrationKey:z30.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z30.object({fallback:z30.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z30.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z30.literal("choices"),text:z30.string().max(500).optional(),actions:z30.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("entry"),collection:z30.string().min(1).max(80),entryId:z30.string().min(1).max(120)}),z30.object({kind:z30.literal("asset"),assetId:z30.string().min(1).max(120)}),z30.object({kind:z30.literal("url"),url:z30.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z30.literal("table"),columns:z30.array(z30.object({label:z30.string().min(1).max(24)})).min(2).max(4),rows:z30.array(z30.object({cells:z30.array(z30.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:z30.literal("cards"),layout:z30.enum(["rail","stack"]).optional(),items:z30.array(z30.object({title:z30.string().min(1).max(60),subtitle:z30.string().min(1).max(120).optional(),imageUrl:z30.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z30.literal("entry"),label:z30.string().min(1).max(80),collection:z30.string().min(1).max(80),entryId:z30.string().min(1).max(120),path:z30.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z30.literal("assets"),items:z30.array(z30.object({url:z30.url({protocol:/^https$/}).max(2e3),alt:z30.string().min(1).max(120),label:z30.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z30.literal("callout"),title:z30.string().min(1).max(80),text:z30.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z30.literal("stat"),items:z30.array(z30.object({label:z30.string().min(1).max(24),value:z30.string().min(1).max(16),delta:z30.string().min(1).max(12).optional(),tone:z30.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z30.literal("chart"),unit:z30.string().min(1).max(12).optional(),points:z30.array(z30.object({label:z30.string().min(1).max(12),value:z30.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z30.literal("text"),placeholder:z30.string().min(1).max(120).optional(),multiline:z30.boolean().optional()}).strict(),ChatFormStepIdSchema=z30.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z30.object({id:ChatFormStepIdSchema,token:z30.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z30.string().trim().min(1).max(60),reason:z30.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z30.literal("capabilities"),items:z30.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=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z30.object({id:ChatFormStepIdSchema.optional(),question:z30.string().min(1).max(500),header:z30.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z30.boolean().optional(),recommended:z30.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:z30.literal("form"),steps:z30.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z30.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z30.object({stepId:ChatFormStepIdSchema.optional(),header:z30.string().min(1).max(25),question:z30.string().min(1).max(500),answer:z30.string().min(1),selectedLabels:z30.array(z30.string().min(1).max(120)).max(8),freeText:z30.string(),skipped:z30.boolean()}),ChatFormAnswerMetadataSchema=z30.object({toolCallId:z30.string().max(255).optional(),shortTitle:z30.string().max(80).optional(),questions:z30.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z30.object({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z30.object({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z30.string().min(1).max(255),partial:z30.boolean().optional()})}});import{z as z31}from"zod";var AdminTargetSchema,AdminToneSchema,AdminStatusSchema,AdminLinkSchema,AdminActionSchema,BlockBaseSchema2,AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,AdminActionsBlockSchema,AdminHandoffBlockSchema,AdminChatBlockSchema,AdminChatBlockToolInputSchema,init_admin_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/admin-chat-block.js"(){"use strict";init_chat_block();AdminTargetSchema=z31.union([z31.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z31.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z31.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z31.object({label:z31.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z31.object({label:z31.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z31.discriminatedUnion("kind",[BlockSayActionSchema,z31.object({kind:z31.literal("open"),label:z31.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z31.object({kind:z31.literal("op"),label:z31.string().trim().min(1).max(32),operation:z31.string().min(1).max(80),input:z31.record(z31.string(),z31.unknown())}).strict(),z31.object({kind:z31.literal("impersonate"),label:z31.string().trim().min(1).max(32),userId:z31.string().min(1).max(120)}).strict(),z31.object({kind:z31.literal("studio"),label:z31.string().trim().min(1).max(32),projectId:z31.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z31.object({fallback:z31.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z31.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z31.literal("record"),kind:z31.string().trim().min(1).max(24),name:z31.string().trim().min(1).max(80),id:z31.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z31.array(z31.object({label:z31.string().trim().min(1).max(24),value:z31.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z31.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z31.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("cards"),items:z31.array(z31.object({name:z31.string().trim().min(1).max(60),subtitle:z31.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z31.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z31.literal("table"),columns:z31.array(z31.object({label:z31.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z31.array(z31.object({cells:z31.array(z31.string().max(80)).min(2).max(3),tone:AdminToneSchema.optional(),target:AdminTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),AdminTimelineBlockSchema=BlockBaseSchema2.extend({type:z31.literal("timeline"),events:z31.array(z31.object({at:z31.string().trim().min(1).max(16),label:z31.string().trim().min(1).max(80),detail:z31.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("stats"),items:z31.array(z31.object({label:z31.string().min(1).max(24),value:z31.string().min(1).max(16),delta:z31.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z31.literal("excerpt"),source:z31.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z31.discriminatedUnion("kind",[z31.object({kind:z31.literal("lines"),lines:z31.array(z31.object({text:z31.string().max(200),highlight:z31.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z31.object({kind:z31.literal("message"),author:z31.string().trim().min(1).max(60),at:z31.string().max(24).optional(),text:z31.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z31.literal("media"),items:z31.array(z31.object({url:z31.url({protocol:/^https$/}).max(2e3),alt:z31.string().min(1).max(120),label:z31.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("actions"),actions:z31.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z31.literal("handoff"),prompt:z31.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z31.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z31.object({block:AdminChatBlockSchema})}});import{z as z32}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=z32.object({shape:z32.enum(CHAT_PORTRAIT_SHAPES),eyes:z32.enum(CHAT_PORTRAIT_EYES),mouth:z32.enum(CHAT_PORTRAIT_MOUTHS),color:z32.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z33}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,ChatRoutineWaitMinutesSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,AgentHoursUsageDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z33.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z33.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z33.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z33.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z33.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z33.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z33.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z33.object({text:z33.string(),title:z33.string(),explanation:z33.string(),watches:z33.array(z33.object({url:z33.string(),health:z33.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z33.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z33.object({text:z33.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z33.object({manual:z33.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z33.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z33.object({message:z33.string().trim().min(1).max(2e4),decision:z33.boolean().optional(),incomplete:z33.boolean().optional()}).refine(report2=>!(report2.decision===!0&&report2.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z33.object({id:z33.string().uuid(),threadId:z33.string().uuid(),runThreadId:z33.string().uuid(),name:z33.string(),instructions:z33.string(),template:z33.object({key:z33.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z33.string(),modelIsDefault:z33.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z33.boolean(),nextRunAt:z33.string().nullable(),lastRunAt:z33.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z33.string().nullable(),createdAt:z33.string(),updatedAt:z33.string()}),ChatRoutineListDTOSchema=z33.object({routines:z33.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z33.object({usedMs:z33.number().int().min(0),includedMs:z33.number().int().min(0),periodStart:z33.string(),periodEnd:z33.string(),stopsAtIncluded:z33.boolean(),canStart:z33.boolean(),canPayOverage:z33.boolean(),overageRateMicrosPerHour:z33.number().int().nullable(),billedMs:z33.number().int().min(0),billedMicros:z33.number().int().min(0)}),ChatRoutineCreateSchema=z33.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional(),waitMinutes:ChatRoutineWaitMinutesSchema.optional()}),ChatRoutineUpdateSchema=z33.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z33.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z33.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown","routine_needs_pro","routine_is_default"]),ChatRoutineRefusalDTOSchema=z33.object({message:z33.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z33.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z33.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z33.object({kind:z33.enum(["person","agent"]),name:z33.string().nullable()}),ChatRoutineRunDTOSchema=z33.object({messageId:z33.string().uuid(),invocationId:z33.string().uuid().nullable(),startedAt:z33.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z33.string().nullable(),events:z33.number().int().min(1),durationMs:z33.number().int().min(0).nullable(),credits:z33.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z33.object({runs:z33.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z33.object({message:z33.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z33.object({kind:z33.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z33.string().uuid().nullable()})}});import{z as z34}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=z34.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z34.string(),displayName:z34.string().nullable(),subdomain:z34.string().nullable().optional(),subdomainUpdatedAt:z34.date().nullable().optional(),organizationId:z34.string().nullable(),createdBy:z34.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z34.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z34.string(),thumbnailUrl:z34.string().nullable(),publishedThumbnailUrl:z34.string().nullable(),category:z34.string().nullable(),snapshotUrl:z34.string().startsWith("/").optional(),appUrl:z34.string().nullable(),lastPublishedAt:z34.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z34.object({name:z34.string().optional(),enabledChatModels:z34.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z34.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z34.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z34.object({id:z34.uuid(),name:z34.string(),displayName:z34.string().nullable(),thumbnailUrl:z34.string().nullable(),category:z34.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),avatar:z34.string().nullable(),color:z34.object({bg:z34.string(),text:z34.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z34.object({path:z34.string(),content:z34.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z34.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z34.object({id:z34.string(),messageId:z34.string(),versionId:z34.string().nullable(),role:ProjectChatMessageRole,parts:z34.array(z34.any()),createdAt:z34.coerce.date()}),MessageUserMetadataSchema=z34.object({id:z34.string(),name:z34.string().nullable().optional(),image:z34.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z34.number(),metadata:z34.object({user:MessageUserMetadataSchema,changeManifest:z34.array(z34.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z34.object({versionId:z34.uuid(),commitHash:z34.string(),name:z34.string(),description:z34.string().nullable(),kind:z34.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z34.object({versionCount:z34.number().int().nonnegative(),snapshotBytes:z34.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z34.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z34.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z34.object({content:z34.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z34.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z34.object({success:z34.boolean(),message:z34.string().optional(),warning:z34.string().optional(),durationMs:z34.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z34.object({code:z34.literal("PUBLISH_UPGRADE_REQUIRED"),message:z34.string(),currentVersion:z34.number().int().positive(),targetVersion:z34.literal(4)}),ProjectLatestPublicationAttemptSchema=z34.object({publicationId:z34.uuid(),status:z34.enum(["queued","building","published","failed","canceled"]),failureCode:z34.string().nullable(),sourceBranch:z34.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z34.object({isPublished:z34.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z34.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z34.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z34.object({label:z34.string().trim().min(1).max(120).optional(),notes:z34.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z34.object({success:z34.boolean(),message:z34.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z34.boolean(),publicationId:z34.string().optional(),url:z34.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z35}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_organization_features_dto();init_project_dto();ChatMessageListDTOSchema=z35.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z35.object({items:z35.array(ProjectMessagePublicDTOSchema),nextCursor:z35.string().nullable()}),ChatLiveTurnDTOSchema=z35.object({invocationId:z35.string(),step:z35.enum(["preparing","working","compacting","merging"]),startedAt:z35.string(),continuesInvocationId:z35.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z35.object({threadId:z35.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z35.object({kind:z35.enum(["person","agent","routine","system"]),id:z35.string().nullable()}),ChatThreadMessageDTOSchema=z35.object({id:z35.string(),role:z35.enum(["user","assistant"]),parts:z35.array(z35.unknown()),metadata:z35.record(z35.string(),z35.unknown()).nullable(),versionId:z35.string().nullable().optional(),createdAt:z35.date().transform(value=>value.toISOString()),providerMessageId:z35.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z35.string().nullable().optional(),invocationStatus:z35.string().nullable().optional(),invocationTerminalReason:z35.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z35.object({id:z35.string(),parts:z35.array(z35.unknown()),metadata:z35.record(z35.string(),z35.unknown()).nullable(),providerMessageId:z35.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z35.boolean(),queuedAt:z35.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z35.object({type:z35.literal("merge_conflict"),merge:z35.object({mergeId:z35.string().uuid(),projectId:z35.string(),fromBranch:z35.string(),toBranch:z35.string()}),publishAfterMerge:z35.boolean()}),ChatThreadMessagesPageDTOSchema=z35.object({threadId:z35.string().nullable(),title:z35.string().nullable(),messages:z35.array(ChatThreadMessageDTOSchema),nextCursor:z35.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z35.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z35.boolean().optional(),queueWaitUntil:z35.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z35.object({kind:z35.literal("replay"),threadId:z35.string(),userMessageId:z35.string()}),ChatQueuedOutcomeDTOSchema=z35.object({kind:z35.literal("queued"),threadId:z35.string(),userMessageId:z35.string(),blockingRootId:z35.string().optional()}),ChatBusyOutcomeDTOSchema=z35.object({kind:z35.literal("busy"),threadId:z35.string(),userMessageId:z35.string(),blockingRootId:z35.string().optional()}),ChatRefusedOutcomeDTOSchema=z35.object({kind:z35.literal("refused"),threadId:z35.string(),userMessageId:z35.string(),refusedInvocationId:z35.string(),terminalReason:z35.string()}),ChatNonStreamingOutcomeDTOSchema=z35.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z35.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z35.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z35.object({quietRuns:z35.number().int().nonnegative(),since:z35.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z35.string().nullable(),nextRunAt:z35.string().nullable(),wakesOnChanges:z35.boolean()}),ProjectChatDescriptionSchema=z35.string().trim().max(2e3),ProjectChatDTOSchema=z35.object({id:z35.string().uuid(),kind:ProjectChatKindSchema,title:z35.string().nullable(),description:z35.string().nullable(),template:z35.string().nullable(),parentThreadId:z35.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z35.string(),lastMessageAt:z35.string().nullable(),preview:z35.string().nullable(),running:z35.boolean(),awaitingAnswer:z35.boolean(),unread:z35.boolean(),pinned:z35.boolean(),archived:z35.boolean(),muted:z35.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z35.object({chats:z35.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z35.object({id:z35.string().uuid()}),ProjectChatTitleSchema=z35.string().trim().min(1).max(120),ProjectChatCreateSchema=z35.object({id:z35.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z35.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=z35.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=z35.object({cron:z35.string()}),ChatTemplateRoutineDTOSchema=z35.object({name:z35.string(),instructions:z35.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z35.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z35.object({id:z35.string(),name:z35.string(),summary:z35.string(),description:z35.string(),portrait:ChatPortraitSchema,plans:z35.array(AgentPlanSchema),routines:z35.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z35.object({templates:z35.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z35.object({read:z35.boolean(),pinned:z35.boolean(),archived:z35.boolean(),muted:z35.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 z36}from"zod";var ADMIN_ASSISTANT_BASE_PATH,ADMIN_ASSISTANT_PATHS,ADMIN_ASSISTANT_MESSAGE_MAX_CHARS,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS,ADMIN_ASSISTANT_REQUEST_MAX_BYTES,AdminAssistantFormResponseSchema,AdminAssistantOutgoingMessageSchema,AdminAssistantSendRequestSchema,AdminAssistantSendOutcomeSchema,AdminAssistantStreamHeadSchema,AdminAssistantThreadSummarySchema,AdminAssistantThreadListQuerySchema,AdminAssistantThreadListResponseSchema,AdminAssistantThreadResponseSchema,AdminAssistantLiveTurnResponseSchema,AdminAssistantAbortResponseSchema,AdminAssistantThreadUpdateSchema,AdminAssistantThreadDeleteResponseSchema,init_admin_assistant=__esm({"../../packages/api-contracts/dist/esm/types/admin-assistant.js"(){"use strict";init_chat_dto();init_chat_block();ADMIN_ASSISTANT_BASE_PATH="/api/ops/assistant",ADMIN_ASSISTANT_PATHS={chat:`${ADMIN_ASSISTANT_BASE_PATH}/chat`,threads:`${ADMIN_ASSISTANT_BASE_PATH}/threads`,thread:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}`,"thread"),live:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/live`,"live"),stream:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/stream`,"stream"),abort:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/abort`,"abort")},ADMIN_ASSISTANT_MESSAGE_MAX_CHARS=2e4,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS=4e3,ADMIN_ASSISTANT_REQUEST_MAX_BYTES=256*1024,AdminAssistantFormResponseSchema=ChatFormResponseSchema.extend({questions:z36.array(ChatFormAnswerItemSchema.extend({answer:z36.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z36.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z36.object({id:z36.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z36.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z36.object({threadId:z36.string().uuid().optional(),message:AdminAssistantOutgoingMessageSchema,formResponse:AdminAssistantFormResponseSchema.optional()}).strict().superRefine((body,context)=>{body.message.text.trim().length===0&&!body.formResponse&&context.addIssue({code:"custom",path:["message","text"],message:"A message cannot be empty."})}),AdminAssistantSendOutcomeSchema=z36.discriminatedUnion("kind",[z36.object({kind:z36.literal("replay"),threadId:z36.string(),userMessageId:z36.string()}),z36.object({kind:z36.literal("queued"),threadId:z36.string(),userMessageId:z36.string(),blockingRootId:z36.string().optional()}),z36.object({kind:z36.literal("busy"),threadId:z36.string(),userMessageId:z36.string(),blockingRootId:z36.string().optional()}),z36.object({kind:z36.literal("refused"),threadId:z36.string(),userMessageId:z36.string(),refusedInvocationId:z36.string(),terminalReason:z36.string()})]),AdminAssistantStreamHeadSchema=z36.object({kind:z36.literal("turn"),threadId:z36.string(),userMessageId:z36.string(),invocationId:z36.string()}),AdminAssistantThreadSummarySchema=z36.object({id:z36.string().uuid(),title:z36.string().nullable(),lastMessageAt:z36.string().nullable(),createdAt:z36.string()}),AdminAssistantThreadListQuerySchema=z36.object({q:z36.string().trim().max(200).optional(),cursor:z36.string().max(500).optional(),limit:z36.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z36.object({threads:z36.array(AdminAssistantThreadSummarySchema),nextCursor:z36.string().nullable()}),AdminAssistantThreadResponseSchema=z36.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z36.string().nullable()}),messages:z36.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z36.object({threadId:z36.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z36.object({aborted:z36.boolean()}),AdminAssistantThreadUpdateSchema=z36.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z36.object({deleted:z36.literal(!0)})}});import{z as z37}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(`
|
|
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 isProcessControlEnvKey(key){return PROCESS_CONTROL_ENV_KEYS.has(key)||PROCESS_CONTROL_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let 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,PROCESS_CONTROL_ENV_KEYS,PROCESS_CONTROL_ENV_PREFIXES,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],PROCESS_CONTROL_ENV_KEYS=new Set(["PATH","HOME","SHELL","BASH_ENV","ENV","PROMPT_COMMAND","USER","TMPDIR","HOST","HOSTNAME","PORT","NODE_ENV","NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_TLS_REJECT_UNAUTHORIZED","SSL_CERT_FILE","CURL_CA_BUNDLE","PYTHONPATH","LD_PRELOAD","LD_LIBRARY_PATH","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","FIMO_VALIDATION_BUILD","FIMO_SKIP_VERSION_CHECK","FIMO_EDITING_METADATA","FIMO_AGENT_TMP_DIR"]),PROCESS_CONTROL_ENV_PREFIXES=["GIT_","NPM_CONFIG_","PNPM_","YARN_","COREPACK_","BUN_","DENO_"];__name(isProcessControlEnvKey,"isProcessControlEnvKey");BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as z8}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z9}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z9.preprocess(referenceValuePreprocess,z9.object({documentId:z9.uuid()})),ReferenceInputValueSchema=z9.preprocess(referenceValuePreprocess,z9.union([z9.object({documentId:z9.uuid()}),z9.object({slug:z9.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.object({contentType:z9.string().min(1),documentId:z9.uuid()})),PolymorphicReferenceInputValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.union([z9.object({contentType:z9.string().min(1),documentId:z9.uuid()}),z9.object({contentType:z9.string().min(1),slug:z9.string().min(1)})]))}});import{z as z10}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path50){let conditionPath=[...path50,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,path50)=>{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,path50));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path50,fieldName,variant.uid]);else walk(field.schema.fields,[...path50,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path50,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path50,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z10.union([z10.object({field:z10.string().min(1),equals:z10.union([z10.string(),z10.number(),z10.boolean()])}).strict(),z10.object({field:z10.string().min(1),in:z10.array(z10.union([z10.string(),z10.number(),z10.boolean()])).min(1)}).strict()]),commonFieldShape={label:z10.string().min(1).optional(),description:z10.string().optional(),group:z10.union([z10.string().min(1),z10.array(z10.string().min(1)).min(1)]).optional(),editable:z10.boolean().optional(),required:z10.boolean().optional(),default:z10.unknown().optional(),showIf:z10.union([showIfClauseSchema,z10.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z10.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z10.object({...commonFieldShape,type:z10.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z10.number().optional(),max:z10.number().optional(),minLength:z10.number().int().nonnegative().optional(),maxLength:z10.number().int().nonnegative().optional(),regex:z10.string().optional(),multiple:z10.boolean().optional(),allowedMimeTypes:z10.array(z10.string()).optional(),options:z10.array(z10.string().min(1)).min(1).optional(),unique:z10.boolean().optional(),i18n:z10.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z10.object({...commonFieldShape,type:z10.literal("reference"),target:z10.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z10.array(z10.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z10.boolean().optional(),i18n:z10.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z10.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z10.record(z10.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z10.object({uid:z10.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z10.string().min(1),description:z10.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z10.object({fields:blockFieldsSchema}).strict(),blocksSchema=z10.object({oneOf:z10.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z10.object({...commonFieldShape,type:z10.literal("blocks"),min:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z10.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z10.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z11}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","site_onboarding_refusal_lift","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_trace_budget_wrap_up_read","ops_context_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_memory_health_read","ops_routine_metrics_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_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","ops_operation_plan","project_sync","project_thumbnail_regenerate","project_delete","project_import","organization_delete","credits_topup","credits_burn","user_session_revoke","user_ban","user_unban","user_impersonate","user_role_change","user_sessions_revoke","user_delete","platform_pool_change","platform_maintenance_change","platform_sync","platform_tenant_schema_sync","integration_event_replay","ops_billing_dispatch_retry","ops_billing_plan_projection_reconcile","ops_agent_chat_create","ops_pylon_issue_change","ops_pylon_note_create","ops_pylon_reply_preview","ops_pylon_reply_approve","ops_pylon_reply_send","admin_playground_run","ops_find","ops_project_health_read","ops_migrations_read","ops_operational_read","ops_billing_report_read","ops_users_read","ops_organizations_read","ops_merges_read","ops_platform_read","ops_watch_read","ops_notification_read","ops_audit_read"],AuditActionSchema=z11.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z11.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z11.enum(AUDIT_ACTOR_KINDS)}});import{z as z12}from"zod";var ORGANIZATION_FEATURES,AGENT_PLANS,AgentPlanSchema,OrganizationFeatureSchema,OrganizationFeaturesDTOSchema,OrganizationFeaturesDTO,OrganizationFeatureStateDTOSchema,OrganizationFeatureSetSchema,init_organization_features_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization-features.dto.js"(){"use strict";init_create_dto();ORGANIZATION_FEATURES=["agents","routine_planner","pro_agents"],AGENT_PLANS=["free","starter","pro"],AgentPlanSchema=z12.enum(AGENT_PLANS),OrganizationFeatureSchema=z12.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z12.object({features:z12.record(OrganizationFeatureSchema,z12.boolean()),lockedByPlan:z12.array(OrganizationFeatureSchema),agentPlan:AgentPlanSchema}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z12.object({feature:OrganizationFeatureSchema,enabled:z12.boolean(),default:z12.boolean(),lockedByPlan:z12.boolean(),override:z12.boolean().nullable(),reason:z12.string().nullable(),updatedBy:z12.string().nullable(),updatedAt:z12.string().datetime().nullable()}),OrganizationFeatureSetSchema=z12.object({state:z12.enum(["on","off","default"]),reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1)})}});import{z as z13}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_SUPPORT_PRESET,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OPS_MEMORY_HEALTH_MAX_WINDOW_MS,OpsMemoryHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OPS_ROUTINE_METRICS_MAX_WINDOW_MS,OpsRoutineMetricsGroupBySchema,OpsRoutineMetricsSortBySchema,OpsRoutineMetricsInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OpsBillingAgentRuntimeAttachInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_organization_features_dto();init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:project:agents:write","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:organization:features:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send","ops:users:read","ops:users:write","ops:organizations:read","ops:organizations:write","ops:merges:read","ops:merges:write","ops:platform:read","ops:platform:write","ops:project:admin","ops:credits:write"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_SUPPORT_PRESET=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:users:read","ops:organizations:read","ops:merges:read","ops:platform:read","ops:billing:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:audit:read","ops:notification:preview"],OPS_PERMISSION_PRESETS={support:OPS_SUPPORT_PRESET,engineer:[...OPS_SUPPORT_PRESET,"ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:customers:write","ops:billing:write","ops:organization:features:write","ops:known-issues:write","ops:validations:write","ops:merges:write","ops:platform:write","ops:users:write"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z13.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z13.strictObject({organizationId:z13.string().trim().min(1).max(255).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),OPS_MEMORY_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsMemoryHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_MEMORY_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"memory health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z13.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,limit:z13.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,sample:z13.coerce.number().int().min(1).max(25).default(10)})),OPS_ROUTINE_METRICS_MAX_WINDOW_MS=2160*60*60*1e3,OpsRoutineMetricsGroupBySchema=z13.enum(["routine","plan","day","project"]),OpsRoutineMetricsSortBySchema=z13.enum(["total","jev","runs"]),OpsRoutineMetricsInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),plan:AgentPlanSchema.optional(),routine:z13.string().trim().min(1).max(64).optional(),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total"),burstMinutes:z13.coerce.number().int().min(1).max(120).default(10),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_ROUTINE_METRICS_MAX_WINDOW_MS,{path:["since"],message:"routine metrics windows cannot exceed 90 days"}),OpsChatHistoryJudgeCalibrationInputSchema=z13.strictObject({reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z13.boolean().default(!1),correlationLimit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),organizationIds:z13.array(z13.string().min(1)).min(1).max(100).optional(),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z13.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z13.strictObject({projectId:z13.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z13.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z13.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z13.strictObject({completeAggregate:z13.boolean(),truncated:z13.boolean().nullable(),sampled:z13.boolean().nullable(),pagination:z13.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z13.literal(!1),providerAsOf:z13.null(),projectFilter:z13.literal("exact properties.projectId equality"),environmentFilterSupported:z13.literal(!1),excludesMissingProjectId:z13.literal(!0),transport:z13.literal("server"),consentCoverage:z13.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z13.literal(!1)}),OpsPosthogCountsSchema=z13.array(z13.strictObject({event:z13.enum(OPS_POSTHOG_EVENTS),captureCount:z13.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z13.strictObject({schemaVersion:z13.literal(1),questionId:z13.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z13.uuid().nullable(),projectEnvironment:z13.literal("mixed_or_unrecorded"),window:z13.strictObject({from:z13.iso.datetime(),to:z13.iso.datetime(),bounds:z13.literal("[from,to)")}).nullable(),source:z13.literal("posthog"),sourceStatus:z13.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z13.iso.datetime(),auditId:z13.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3),limit:z13.number().int().min(1).max(100).default(25),checkProvider:z13.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z13.object({branch:z13.string().trim().min(1).max(255),canaryPath:z13.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z13.iso.datetime({offset:!0}),until:z13.iso.datetime({offset:!0}),reason:z13.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z14}from"zod";function resolveOpsTime(value,now=new Date){let relative3=RELATIVE_WINDOW.exec(value.trim());if(relative3){let amount=Number(relative3[1]),unit=relative3[2];return new Date(now.getTime()-amount*UNIT_MS[unit]).toISOString()}return new Date(value).toISOString()}function opsHoursSince(value,now=new Date){let start=Date.parse(resolveOpsTime(value,now));return Math.max(1,Math.ceil((now.getTime()-start)/UNIT_MS.h))}var RELATIVE_WINDOW,time,opsArgs,OPS_STANDARD_ARG_KEYS,UNIT_MS,init_args=__esm({"../../packages/api-contracts/dist/esm/ops/args.js"(){"use strict";RELATIVE_WINDOW=/^(\d+)(m|h|d|w)$/,time=z14.string().trim().min(1).max(64).refine(value=>RELATIVE_WINDOW.test(value)||!Number.isNaN(Date.parse(value)),{message:"Expected an ISO timestamp or a relative window such as 30m, 24h, 7d or 2w"}),opsArgs={project:z14.uuid().describe("Fimo project id"),org:z14.string().trim().min(1).max(255).describe("Organization id"),user:z14.string().trim().min(1).max(255).describe("User id"),env:z14.string().trim().min(1).max(255).describe("Project environment (branch), e.g. main or prod"),since:time.describe("Start of the window: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:time.describe("End of the window: ISO timestamp or relative (defaults to now)"),limit:z14.coerce.number().int().min(1).max(1e3).describe("Maximum results"),cursor:z14.string().trim().min(1).max(2e3).describe("Continue from a previous page"),query:z14.string().trim().min(1).max(200).describe("Free-text search"),reason:z14.string().trim().min(1).max(1e3).describe("Why this is being read or changed; stored in the audit log"),output:z14.string().trim().min(1).max(4096).describe("Write the result to this local file")},OPS_STANDARD_ARG_KEYS=Object.keys(opsArgs),UNIT_MS={m:6e4,h:36e5,d:864e5,w:6048e5};__name(resolveOpsTime,"resolveOpsTime");__name(opsHoursSince,"opsHoursSince")}});var init_types=__esm({"../../packages/api-contracts/dist/esm/ops/types.js"(){"use strict"}});function compact(value){return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0))}function time2(value){return value===void 0?void 0:resolveOpsTime(value)}function seg(value){return encodeURIComponent(value)}var init_shared=__esm({"../../packages/api-contracts/dist/esm/ops/commands/shared.js"(){"use strict";init_args();__name(compact,"compact");__name(time2,"time");__name(seg,"seg")}});import{z as z15}from"zod";var invocation,span,agentCommands,init_agent=__esm({"../../packages/api-contracts/dist/esm/ops/commands/agent.js"(){"use strict";init_ops();init_args();init_types();init_shared();invocation=z15.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z15.string().trim().min(1).max(255).describe("Braintrust span id"),agentCommands=[{id:"agent.chats.recent",summary:"Read recent chat messages across every project in a time window",permission:"ops:project:chat:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional().describe("Only messages from this environment"),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z15.boolean().default(!1).describe("Include complete message parts instead of the slim transcript"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat/messages/recent",body:compact({from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"agent.chats.create",summary:"Create an agent chat with routines in a customer project, as the organization owner. Validate the spec and confirm intent first: routines run and spend credits",permission:"ops:project:agents:write",effect:"write",risk:"low",input:z15.object({project:opsArgs.project,spec:z15.record(z15.string(),z15.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{id:"agent.traces.list",summary:"List agent runs for a project, organization or thread, with cost and status",permission:"ops:project:read",effect:"read",input:z15.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z15.uuid().optional().describe("Chat thread id"),agent:z15.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z15.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z15.boolean().default(!1).describe("Only runs that recorded a Braintrust root span"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/list",body:compact({projectId:input.project,organizationId:input.org,threadId:input.thread,agentKey:input.agent,status:input.status,since:time2(input.since),minCostUsd:input.minCost,tracedOnly:input.tracedOnly,limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.budget",summary:"List chats whose runs crossed the context budget and had to wrap up (content-free)",permission:"ops:braintrust:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),limit:opsArgs.limit.max(25).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/budget-wrap-up",body:compact({since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.spans",summary:"List the spans of one agent run",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,limit:opsArgs.limit.max(500).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans`,body:{limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.span",summary:"Read one span body (input and output) of an agent run",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,span,maxChars:z15.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z15.boolean().default(!1).describe("Return the end of an over-long body instead of the start"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}`,body:{maxChars:input.maxChars,edge:input.tail?"end":"start",reason:input.reason}}),"request")},{id:"agent.traces.messages",summary:"Read the conversation the model saw in one LLM span",permission:"ops:braintrust:read",effect:"read",input:z15.object({invocation,span,message:z15.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z15.coerce.number().int().min(500).max(2e5).default(2e4),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}/messages`,body:compact({messageIndex:input.message,maxChars:input.maxChars,reason:input.reason})}),"request")},{id:"agent.traces.stats",summary:"Aggregate agent step latency, tokens and cost by model, provider, span or type",permission:"ops:braintrust:read",effect:"read",input:z15.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z15.coerce.number().positive().optional().describe("Only steps at least this many seconds slow"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/stats",body:compact({since:time2(input.since),until:time2(input.until),groupBy:input.groupBy,spanType:input.spanType,slowerThanSeconds:input.slowerThan,limit:input.limit,reason:input.reason})}),"request")}]}});import{z as z16}from"zod";var assistantCommands,init_assistant=__esm({"../../packages/api-contracts/dist/esm/ops/commands/assistant.js"(){"use strict";init_args();init_types();init_shared();assistantCommands=[{id:"assistant.threads.list",summary:"List your admin assistant threads, newest activity first",permission:"ops:platform:read",effect:"read",input:z16.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z16.coerce.number().int().min(1).max(100).optional().describe("Maximum results"),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/assistant/threads",query:{q:input.query,limit:input.limit,cursor:input.cursor}}),"request")},{id:"assistant.threads.get",summary:"Read one admin assistant thread with every message",permission:"ops:platform:read",effect:"read",input:z16.object({thread:z16.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z17}from"zod";var day,billingCommands,init_billing=__esm({"../../packages/api-contracts/dist/esm/ops/commands/billing.js"(){"use strict";init_args();init_types();init_shared();day=z17.iso.date().describe("UTC day, YYYY-MM-DD"),billingCommands=[{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z17.object({customer:z17.string().trim().min(1).max(255).describe("Hyperline customer id"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/customers/${seg(input.customer)}`,query:{reason:input.reason}}),"request")},{id:"billing.org",summary:"Read an organization's billing state: subscription, plan projection, credits and wallet",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"billing.bandwidth-contract",summary:"Read an organization's hosting bandwidth contract and current usage",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}/bandwidth-contract`,query:{reason:input.reason}}),"request")},{id:"billing.ledger",summary:"Read an organization's credit ledger: holds, settlements, grants or usage events",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,kind:z17.enum(["holds","settlements","grants","usage-events"]),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/ledger",query:compact({organizationId:input.org,kind:input.kind,since:time2(input.since),limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z17.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z17.iso.datetime({offset:!0}).optional().describe("Reuse evaluatedAt when resuming a scan"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/plan-projections/report",query:compact({reason:input.reason,at:input.at??new Date().toISOString(),cursor:input.cursor})}),"request")},{id:"billing.plans.reconcile",summary:"Repair organizations' local plan projections from Hyperline",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({orgs:z17.array(opsArgs.org).min(1).max(100).describe("Organization ids")})},{id:"billing.legacy-premium.report",summary:"Report legacy Premium organizations and where each stands in the Pro transition",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org.optional(),limit:opsArgs.limit.max(200).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/legacy-premium-report",query:compact({reason:input.reason,org:input.org,limit:input.limit})}),"request")},{id:"billing.legacy-premium.enroll",summary:"Record the approved Pro offer for one legacy Premium organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({org:opsArgs.org,deadline:z17.string().trim().min(1).max(64).describe("Decision date exactly 90 calendar days from today")})},{id:"billing.legacy-premium.notify",summary:"Send the due legacy Premium transition notices for one organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({org:opsArgs.org})},{id:"billing.entitlements.sync",summary:"Reconcile subscription entitlement properties in Hyperline with Fimo's plans (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({batchSize:z17.coerce.number().int().min(1).max(100).default(50),concurrency:z17.coerce.number().int().min(1).max(10).default(2),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.agent-runtime.attach",summary:"Attach the Agent runtime product to PAYG and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({orgs:z17.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z17.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.dispatches.list",summary:"List billing usage dispatches to Hyperline by state",permission:"ops:billing:read",effect:"read",input:z17.object({state:z17.enum(["pending","dispatched","dead-lettered","discarded"]),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/billing/dispatches",body:{state:input.state,reason:input.reason}}),"request")},{id:"billing.dispatches.discard",summary:"Discard dead-lettered billing dispatches so they are never sent",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z17.object({dispatches:z17.array(z17.uuid()).min(1).max(100).describe("Dispatch ids")})},{id:"billing.dispatches.retry",summary:"Retry a dead-lettered billing dispatch",permission:"ops:billing:write",effect:"write",risk:"low",input:z17.object({dispatch:z17.uuid().describe("Dispatch id")})},{id:"billing.cache.invalidate",summary:"Clear an organization's cached billing state so the next read goes to Hyperline",permission:"ops:billing:write",effect:"write",risk:"low",input:z17.object({org:opsArgs.org})},{id:"billing.hosting-usage.day",summary:"Read hosting usage recorded for one source, meter and day",permission:"ops:billing:read",effect:"read",input:z17.object({source:z17.string().trim().min(1).max(100),meter:z17.string().trim().min(1).max(100),day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage",query:{source:input.source,meter:input.meter,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.reconciliation",summary:"Compare a project's served traffic with the hosting usage billed for one day",permission:"ops:billing:read",effect:"read",input:z17.object({project:opsArgs.project,day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/reconciliation",query:{projectId:input.project,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.periods",summary:"List an organization's hosting billing periods",permission:"ops:billing:read",effect:"read",input:z17.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/customer-periods",query:{organizationId:input.org,reason:input.reason}}),"request")}]}});import{z as z18}from"zod";var coreCommands,init_core=__esm({"../../packages/api-contracts/dist/esm/ops/commands/core.js"(){"use strict";init_args();init_types();init_shared();coreCommands=[{id:"find",summary:"Find projects, organizations or users by name, slug, domain, email or id",permission:"ops:project:read",effect:"read",input:z18.object({query:opsArgs.query,kind:z18.enum(["project","org","user"]).optional().describe("Only this kind of record"),limit:opsArgs.limit.max(100).default(20),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/find",query:compact({q:input.query,kind:input.kind,limit:input.limit,cursor:input.cursor})}),"request"),cli:{positional:"query"}},{id:"audit.list",summary:"List audit log entries, newest first",permission:"ops:audit:read",effect:"read",input:z18.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z18.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z18.string().trim().min(1).max(64).optional().describe("Audit action, e.g. project_takedown"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"GET",path:"/audit",query:compact({projectId:input.project,organizationId:input.org,actor:input.actor,action:input.action,since:time2(input.since),limit:input.limit})}),"request")}]}});import{z as z19}from"zod";var window2,healthCommands,init_health=__esm({"../../packages/api-contracts/dist/esm/ops/commands/health.js"(){"use strict";init_organization_features_dto();init_ops();init_args();init_types();init_shared();window2={since:opsArgs.since,until:opsArgs.until.optional()},healthCommands=[{id:"health.overview",summary:"Platform health brief: Sentry, logs, agents, publishing and support in one window",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional().describe("Narrow every source that can be narrowed to one project"),limit:opsArgs.limit.max(100).default(25).describe("Maximum findings per source"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.agents",summary:"Agent run outcomes, cost and duration grouped by agent, status, branch, project or day",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z19.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z19.boolean().default(!1).describe("Count sub-steps too"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,branch:input.env,agentKey:input.agent,groupBy:input.groupBy,includeChildren:input.includeChildren,limit:input.limit,reason:input.reason})}),"request")},{id:"health.context",summary:"Context-window pressure and compaction facts for agent turns",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(500),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/context-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.memory",summary:"Agent memory health: threads and routines with missing or stale memory",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/memory-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.providers",summary:"Model provider errors grouped by signature, optionally correlated to agent runs",permission:"ops:braintrust:read",effect:"read",input:z19.object({...window2,model:z19.string().trim().min(1).max(200).optional(),provider:z19.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z19.string().trim().min(1).max(64).optional().describe("Page boundary: nextBefore from the previous page"),limit:opsArgs.limit.max(1e3).default(500).describe("Error spans to scan per page"),correlate:z19.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z19.coerce.number().int().min(1).max(100).default(25),sampleChars:z19.coerce.number().int().min(200).max(2e4).default(1200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-provider-errors",body:compact({since:time2(input.since),until:time2(input.until),model:input.model,provider:input.provider,spanType:input.spanType,before:input.before,limit:input.limit,sampleChars:input.sampleChars,correlateInvocations:input.correlate||void 0,correlationLimit:input.correlate?input.correlationLimit:void 0,reason:input.reason})}),"request")},{id:"health.chat-history.summary",summary:"How often agents call the chatHistory tool and whether it finds what they need",permission:"ops:project:read",effect:"read",input:z19.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat-history/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,reason:input.reason})}),"request")},{id:"health.chat-history.calls",summary:"List chatHistory tool calls; --with-content adds the surrounding messages (needs chat read)",permission:"ops:project:read",effect:"read",input:z19.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z19.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:input.withContent?"/chat-history/calls/content":"/chat-history/calls",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.chat-history.judge",summary:"Have a model judge a sample of chatHistory calls; --calibrate runs the labelled benchmark",permission:"ops:project:chat:read",effect:"read",input:z19.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z19.coerce.number().int().min(1).max(25).default(10),calibrate:z19.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>input.calibrate?{method:"POST",path:"/chat-history/judge/calibration",body:{reason:input.reason}}:{method:"POST",path:"/chat-history/judge",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,sample:input.sample,reason:input.reason})},"request")},{id:"health.data-usage",summary:"Data-provider usage (search, scraping, enrichment) grouped by operation, provider, day, org or agent",permission:"ops:project:read",effect:"read",input:z19.object({...window2,org:opsArgs.org.optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/data-usage",body:compact({since:time2(input.since),until:time2(input.until),organizationId:input.org,groupBy:input.groupBy,limit:input.limit,reason:input.reason})}),"request")},{id:"health.routines",summary:"Routine runs, event bursts, Jev trigger calls and cost, by routine, plan, day or project",permission:"ops:project:read",effect:"read",input:z19.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z19.string().trim().min(1).max(64).optional().describe("Template routine key, or custom"),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total").describe("Rank buckets by total cost, Jev's trigger cost, or runs"),burstMinutes:z19.coerce.number().int().min(1).max(120).default(10).describe("An event this many minutes or less after the routine's previous one is a burst"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/routine-metrics",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,plan:input.plan,routine:input.routine,groupBy:input.groupBy,sortBy:input.sortBy,burstMinutes:input.burstMinutes,reason:input.reason})}),"request")},{id:"health.analytics",summary:"Whether a project's website analytics are arriving (content-free counts, max 7 days)",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z19.string().max(300).optional().describe("Exact test path ending in ?fimo_monitor=<UUID>"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/analytics-health`,body:compact({branch:input.env,canaryPath:input.canaryPath,since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason})}),"request")},{id:"health.session",summary:"A project's work-session and database-branch health: cleanup due, unresolved allocations, capacity",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,checkProvider:z19.boolean().default(!1).describe("Include one bounded read-only Neon inventory page"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/session-health`,body:{reason:input.reason,limit:input.limit,checkProvider:input.checkProvider}}),"request")},{id:"health.sandbox",summary:"A project environment's sandbox and preview status",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project,env:opsArgs.env.default("main"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/sandbox/status`,body:{projectEnv:input.env,reason:input.reason}}),"request")},{id:"health.schedules",summary:"Failed scheduled runs and webhook deliveries",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z19.uuid().optional().describe("Schedule id"),run:z19.uuid().optional().describe("Schedule run id (needs --project)"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/schedules/failures",body:compact({projectId:input.project,projectEnv:input.env,scheduleId:input.schedule,runId:input.run,since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"health.integrations",summary:"Failing integration connections and inbound events",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/integrations/failures",body:compact({projectId:input.project,reason:input.reason})}),"request")},{id:"health.domains",summary:"Custom domains with DNS, SSL or provider problems",permission:"ops:project:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/domains/problems",body:compact({projectId:input.project,organizationId:input.org,reason:input.reason})}),"request")}]}});import{z as z20}from"zod";var mergeCommands,init_merge=__esm({"../../packages/api-contracts/dist/esm/ops/commands/merge.js"(){"use strict";init_args();init_types();init_shared();mergeCommands=[{id:"merge.list",summary:"List merges, newest first; --stuck lists only merges that stopped progressing",permission:"ops:merges:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),stuck:z20.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z20.string().trim().min(1).max(64).optional().describe("Only merges in this status"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/merges",query:compact({projectId:input.project,stuck:input.stuck||void 0,status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"merge.get",summary:"Show one merge with its steps, conflicts and release",permission:"ops:merges:read",effect:"read",input:z20.object({merge:z20.uuid().describe("Merge id")}),request:__name(input=>({method:"GET",path:`/merges/${seg(input.merge)}`}),"request")},{id:"merge.unwind",summary:"Force-unwind a stuck merge: reset the target branch to its pre-merge head and reopen the merge",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z20.object({merge:z20.uuid().describe("Merge id")})},{id:"merge.fail",summary:"Force-fail a stuck merge without touching the target branch",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z20.object({merge:z20.uuid().describe("Merge id")})}]}});import{z as z21}from"zod";var channel,draft,notifyCommands,init_notify=__esm({"../../packages/api-contracts/dist/esm/ops/commands/notify.js"(){"use strict";init_ops();init_args();init_types();init_shared();channel=z21.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z21.uuid().describe("Draft id"),notifyCommands=[{id:"notify.draft",summary:"Draft a customer-visible message: an email to a project owner or a reply on a Pylon ticket",permission:"ops:notification:preview",effect:"write",risk:"low",input:z21.object({channel,message:z21.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z21.email().optional().describe("email: override the recipient"),subject:z21.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z21.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z21.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z21.array(z21.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z21.array(z21.email()).max(50).optional(),bccEmails:z21.array(z21.email()).max(50).optional()}),cli:{fileArgs:["message"]}},{id:"notify.show",summary:"Show a drafted customer message and its approval state",permission:"ops:notification:preview",effect:"read",input:z21.object({channel,draft}),request:__name(input=>({method:"GET",path:input.channel==="pylon"?`/support/pylon/replies/${seg(input.draft)}`:`/notifications/${seg(input.draft)}`}),"request")},{id:"notify.approve",summary:"Approve a drafted customer message (a person must approve before it can be sent)",permission:"ops:notification:approve",effect:"write",risk:"low",humanOnly:!0,input:z21.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z21.object({channel,draft})}]}});function normalizeSentryIssueReference(reference){let trimmed=reference.trim();if(SENTRY_ISSUE_ID_PATTERN.test(trimmed))return trimmed;let url;try{url=new URL(trimmed)}catch{throw new Error("Expected a Sentry issue id or /issues/<id>/ URL")}let segments=url.pathname.split("/").filter(Boolean),issuesIndex=segments.lastIndexOf("issues"),issueId=issuesIndex>=0&&issuesIndex===segments.length-2?segments[issuesIndex+1]:void 0;if(!issueId||!SENTRY_ISSUE_ID_PATTERN.test(issueId))throw new Error("Expected a Sentry issue id or /issues/<id>/ URL");return issueId}function collectTraceIds(value,candidates,depth=0){if(!(depth>32)){if(typeof value=="string"){TRACE_ID_PATTERN.test(value.trim())&&candidates.add(value.trim().toLowerCase());return}if(Array.isArray(value)){for(let item of value)collectTraceIds(item,candidates,depth+1);return}if(typeof value=="object"&&value!==null)for(let item of Object.values(value))collectTraceIds(item,candidates,depth+1)}}function normalizeTempoTraceReference(reference){let trimmed=reference.trim();if(TRACE_ID_PATTERN.test(trimmed))return trimmed.toLowerCase();let url;try{url=new URL(trimmed)}catch{throw new Error("Expected an exact 32-character trace id or a Grafana trace URL")}let candidates=new Set;for(let segment of url.pathname.split("/"))collectTraceIds(segment,candidates);for(let value of url.searchParams.values()){collectTraceIds(value,candidates);try{collectTraceIds(JSON.parse(value),candidates)}catch{continue}}if(candidates.size!==1)throw new Error(candidates.size===0?"Grafana URL did not contain a trace id":"Grafana URL contained multiple trace ids");return[...candidates][0]}var SENTRY_ISSUE_ID_PATTERN,TRACE_ID_PATTERN,init_references2=__esm({"../../packages/api-contracts/dist/esm/ops/references.js"(){"use strict";SENTRY_ISSUE_ID_PATTERN=/^[a-zA-Z0-9-]{1,100}$/,TRACE_ID_PATTERN=/^[a-fA-F0-9]{32}$/;__name(normalizeSentryIssueReference,"normalizeSentryIssueReference");__name(collectTraceIds,"collectTraceIds");__name(normalizeTempoTraceReference,"normalizeTempoTraceReference")}});import{z as z22}from"zod";function parseWhere(values){if(!(!values||values.length===0))return Object.fromEntries(values.map(value=>{let separator=value.indexOf("=");if(separator<1)throw new Error("--where expects key=value");return[value.slice(0,separator),value.slice(separator+1)]}))}var issue,logFilters,observeCommands,init_observe=__esm({"../../packages/api-contracts/dist/esm/ops/commands/observe.js"(){"use strict";init_args();init_references2();init_types();init_shared();issue=z22.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z22.array(z22.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z22.string().min(1).max(500).optional().describe("Plain-text line filter"),limit:opsArgs.limit.max(1e3).default(100),reason:opsArgs.reason,output:opsArgs.output.optional()},observeCommands=[{id:"observe.logs.query",summary:"Query a project's production logs in a time window",permission:"ops:logs:read",effect:"read",input:z22.object({...logFilters,since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}),"request")},{id:"observe.logs.around",summary:"Read a project's production logs a few minutes either side of a moment",permission:"ops:logs:read",effect:"read",input:z22.object({...logFilters,at:z22.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z22.coerce.number().int().min(1).max(120).default(5).describe("Minutes before and after")}),request:__name(input=>{let at2=Date.parse(input.at);return{method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:new Date(at2-input.minutes*6e4).toISOString(),to:new Date(at2+input.minutes*6e4).toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}},"request")},{id:"observe.traces.get",summary:"Read one Grafana Tempo trace (id or Grafana URL) for a project",permission:"ops:traces:read",effect:"read",input:z22.object({trace:z22.string().trim().min(1).max(4e3).describe("32-character trace id or Grafana trace URL"),project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/traces/${normalizeTempoTraceReference(input.trace)}`,body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"observe.sentry.issues",summary:"Search Sentry issues, for one project or every project",permission:"ops:sentry:read",effect:"read",input:z22.object({project:opsArgs.project.optional(),search:z22.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z22.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z22.enum(["date","new","freq","user","trends"]).optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/sentry/issues",body:compact({projectId:input.project,query:input.search,statsPeriod:input.period,sort:input.sort,limit:input.limit,reason:input.reason})}),"request")},{id:"observe.sentry.issue",summary:"Read one Sentry issue",permission:"ops:sentry:read",effect:"read",input:z22.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.event",summary:"Read one full Sentry event",permission:"ops:sentry:read",effect:"read",input:z22.object({event:z22.string().trim().min(1).max(100).describe("Sentry event id"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/events/${seg(input.event)}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.latest-event",summary:"Read the latest full event of a Sentry issue",permission:"ops:sentry:read",effect:"read",input:z22.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}/events/latest`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.resolve",summary:"Mark a Sentry issue resolved",permission:"ops:sentry:write",effect:"write",risk:"low",input:z22.object({issue})},{id:"observe.posthog.milestones",summary:"Count a project's PostHog lifecycle milestones (create, deploy, first publish) in a window",permission:"ops:posthog:read",effect:"read",input:z22.object({project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/posthog/milestones",body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")}]}});import{z as z23}from"zod";var orgCommands,init_org=__esm({"../../packages/api-contracts/dist/esm/ops/commands/org.js"(){"use strict";init_organization_features_dto();init_args();init_types();init_shared();orgCommands=[{id:"org.get",summary:"Show an organization: plan, members, projects and subscription summary",permission:"ops:organizations:read",effect:"read",input:z23.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"org.features.list",summary:"List an organization's features and any staff overrides",permission:"ops:customers:read",effect:"read",input:z23.object({org:opsArgs.org}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}/features`}),"request")},{id:"org.features.set",summary:"Force an organization feature on or off, or clear the override",permission:"ops:organization:features:write",effect:"write",risk:"low",humanOnly:!0,input:z23.object({org:opsArgs.org,feature:z23.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z23.enum(["on","off","default"]).describe("on, off, or default to clear the override")})},{id:"org.takedown",summary:"Take every project of an organization off Fimo domains and block publishing",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.delete",summary:"Delete an organization and everything it owns permanently",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org})},{id:"org.credits.topup",summary:"Grant credits to an organization, free or as a recorded purchase",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org,credits:z23.coerce.number().int().positive().describe("Number of credits"),type:z23.enum(["free","purchase"]).default("free"),amountCents:z23.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z23.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z23.string().trim().optional().describe("Note shown with the grant")})},{id:"org.credits.burn-zombies",summary:"Burn credits held by abandoned (zombie) holds of one organization since a date",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z23.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z24}from"zod";var OPS_PLATFORM_DASHBOARDS,platformCommands,init_platform=__esm({"../../packages/api-contracts/dist/esm/ops/commands/platform.js"(){"use strict";init_args();init_types();init_shared();OPS_PLATFORM_DASHBOARDS=["agents","money","projects","automation","growth","platform","usage","stats"],platformCommands=[{id:"platform.metrics",summary:"Read an admin dashboard as data: agents, money, projects, automation, growth, platform, usage or stats",permission:"ops:platform:read",effect:"read",input:z24.object({dashboard:z24.enum(OPS_PLATFORM_DASHBOARDS),since:opsArgs.since.default("7d"),until:opsArgs.until.optional()}),request:__name(input=>({method:"GET",path:"/platform/metrics",query:compact({dashboard:input.dashboard,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"platform.pool.status",summary:"Show the warm sandbox pool: size, target, and projects waiting in it",permission:"ops:platform:read",effect:"read",input:z24.object({}),request:__name(()=>({method:"GET",path:"/platform/pool"}),"request")},{id:"platform.pool.refill",summary:"Top the warm sandbox pool up to its target size",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.pool.flush",summary:"Delete warm sandboxes from the pool, all of them or only the listed ones (new projects start cold until it refills)",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({pooled:z24.array(z24.uuid()).min(1).max(500).optional().describe("Only these pooled project ids; omit to flush all")})},{id:"platform.maintenance.status",summary:"Show whether maintenance mode is on and its message",permission:"ops:platform:read",effect:"read",input:z24.object({}),request:__name(()=>({method:"GET",path:"/platform/maintenance"}),"request")},{id:"platform.maintenance.enable",summary:"Turn maintenance mode on: Studio shows the message and refuses work",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({message:z24.string().max(500).optional().describe("Message shown to users")})},{id:"platform.maintenance.disable",summary:"Turn maintenance mode off",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.maintenance.message",summary:"Change the maintenance message without toggling maintenance mode",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({message:z24.string().max(500).describe("Message shown to users")})},{id:"platform.sync-all",summary:"Re-sync every project's database records from its repository",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.sync-tenant-schemas",summary:"Apply pending tenant schema migrations to every project database",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z24.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z24.object({event:z24.string().trim().min(1).max(255).describe("Inbound event id")})},{id:"platform.onboardings.list",summary:"List site onboardings (start from an existing website) with their status",permission:"ops:platform:read",effect:"read",input:z24.object({status:z24.string().trim().min(1).max(64).optional(),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/onboardings",query:compact({status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.onboardings.get",summary:"Show one project's site onboarding: questions, answers, refusal and timeline",permission:"ops:platform:read",effect:"read",input:z24.object({project:opsArgs.project,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/platform/onboardings/${seg(input.project)}`,query:{reason:input.reason}}),"request")},{id:"platform.onboardings.lift-refusal",summary:"Lift a site onboarding's Terms refusal so the project can continue",permission:"ops:platform:write",effect:"write",risk:"low",input:z24.object({project:opsArgs.project})},{id:"platform.unclaimed.list",summary:"List unclaimed projects (created without an account) and their claim state",permission:"ops:platform:read",effect:"read",input:z24.object({since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/unclaimed",query:compact({since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.resources.resolve",summary:"Resolve any id, URL, email or domain to the Fimo record it names",permission:"ops:platform:read",effect:"read",input:z24.object({query:z24.string().trim().min(1).max(512).describe("Id, URL, email or domain")}),request:__name(input=>({method:"GET",path:"/platform/resources/resolve",query:{q:input.query}}),"request"),cli:{positional:"query"}}]}});import{z as z25}from"zod";function files(project,action,env){return`/projects/${seg(project)}/files/${action}?projectEnv=${seg(env)}`}var envMain,projectCommands,init_project=__esm({"../../packages/api-contracts/dist/esm/ops/commands/project.js"(){"use strict";init_args();init_types();init_shared();envMain=opsArgs.env.default("main");__name(files,"files");projectCommands=[{id:"project.get",summary:"Inspect a project: owner, environments, domains, publications, recent runs and logs",permission:"ops:project:read",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,since:opsArgs.since.default("24h"),limit:opsArgs.limit.max(500).default(100).describe("Maximum log entries")}),request:__name(input=>({method:"GET",path:`/projects/${seg(input.project)}/inspect`,query:{projectEnv:input.env,hours:Math.min(168,opsHoursSince(input.since)),logLimit:input.limit}}),"request")},{id:"project.snapshot",summary:"Download a zip snapshot of a project's source and content",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/snapshot`,body:{reason:input.reason}}),"request")},{id:"project.chat",summary:"Read a project's agent chat transcript (the most recently active chat unless --thread is set)",permission:"ops:project:chat:read",effect:"read",input:z25.object({project:opsArgs.project,thread:z25.uuid().optional().describe("One chat thread id"),env:opsArgs.env.optional().describe("Only turns that targeted this environment"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z25.boolean().default(!1).describe("Include tool inputs, outputs and other message parts"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/chat/messages`,body:compact({projectEnv:input.env,threadId:input.thread,from:time2(input.since),to:time2(input.until),limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"project.files.read",summary:"Read one source file from a project environment",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,path:z25.string().trim().min(1).max(1024).describe("File path relative to the project root"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:files(input.project,"read",input.env),body:{path:input.path,reason:input.reason}}),"request")},{id:"project.files.glob",summary:"List source file paths in a project environment",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,pattern:z25.string().min(1).max(300).optional().describe("Glob pattern, e.g. src/**/*.tsx"),limit:opsArgs.limit.max(2e3).default(2e3),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"glob",input.env),body:compact({pattern:input.pattern,limit:input.limit,reason:input.reason})}),"request")},{id:"project.files.grep",summary:"Search source files in a project environment with a regular expression",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,pattern:z25.string().min(1).max(200).describe("Regular expression"),include:z25.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z25.boolean().default(!1),limit:opsArgs.limit.max(200).default(100).describe("Maximum matches"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"grep",input.env),body:compact({pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.limit,reason:input.reason})}),"request")},{id:"project.files.package-manager",summary:"Report which package manager a project declares and which lockfiles it has",permission:"ops:project:snapshot",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"package-manager",input.env),body:{reason:input.reason}}),"request")},{id:"project.files.write",summary:"Create or replace one source file in a project environment (commits to its branch)",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,path:z25.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z25.string().max(256*1024).describe("The exact desired file contents"),overwrite:z25.boolean().default(!1).describe("Allow replacing an existing file")}),cli:{fileArgs:["content"]}},{id:"project.runtime.bump",summary:"Pin the project's fimo runtime packages to an exact version, install, and restart the dev server",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,version:z25.string().trim().min(1).max(64).describe("Exact target version, e.g. 0.11.0")})},{id:"project.preview.restart",summary:"Restart the project's preview dev server",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain})},{id:"project.publish",summary:"Publish the customer's site on their behalf. Only when a Fimo admin explicitly asks for it; never on an agent's own initiative",permission:"ops:project:publish",effect:"write",risk:"high",humanOnly:!0,consent:!0,input:z25.object({project:opsArgs.project,env:opsArgs.env.optional().describe("Source environment; defaults to the project's publish source")})},{id:"project.domain.refresh",summary:"Refresh a custom domain's provider and SSL state",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z25.object({project:opsArgs.project,domain:z25.uuid().describe("Project domain id")})},{id:"project.migrations.dry-run",summary:"Plan a source migration for one project without changing it",permission:"ops:project:read",effect:"read",input:z25.object({project:opsArgs.project,env:envMain,migration:z25.string().trim().min(1).max(120).optional().describe("Migration id (default: the current one)"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/migrations/projects/${seg(input.project)}/dry-run`,body:compact({migrationId:input.migration,projectEnv:input.env,reason:input.reason})}),"request")},{id:"project.sync",summary:"Re-sync a project's database records from its repository",permission:"ops:project:operate",effect:"write",risk:"low",input:z25.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z25.object({project:opsArgs.project,type:z25.enum(["dev","published"]).default("dev").describe("dev (the preview) or published (the live site)")})},{id:"project.version.restore",summary:"Restore a project environment to an earlier version (overwrites the current state)",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,env:envMain,version:z25.string().trim().min(1).max(255).describe("Version id to restore")})},{id:"project.takedown",summary:"Take a project off Fimo domains and block it from publishing",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})},{id:"project.restore",summary:"Lift a project takedown so it can serve and publish again",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})},{id:"project.transfer",summary:"Move a project to another organization",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project,toOrg:opsArgs.org.describe("Destination organization id")})},{id:"project.delete",summary:"Delete a project and its resources permanently",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z25.object({project:opsArgs.project})}]}});import{z as z26}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=z26.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z26.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z26.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z26.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z26.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z26.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z26.enum(["user","agent","system"]),SupportReportTagSchema=z26.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z26.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z26.object({organization:z26.object({id:z26.string().trim().min(1).max(255),name:z26.string().trim().max(240).optional()}),project:z26.object({id:z26.uuid(),name:z26.string().trim().max(240).optional(),createdAt:z26.coerce.date().optional()}).optional(),environment:z26.string().trim().max(255).optional(),clientVersion:z26.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z26.object({message:z26.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z26.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z26.string().trim().max(200).optional(),limit:z26.coerce.number().int().min(1).max(100).default(50),offset:z26.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z26.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z26.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z26.uuid().nullable().optional(),note:z26.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=z26.object({message:z26.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z26.object({kind:SupportReportLinkKindSchema,label:z26.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z26.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z26.object({kind:SupportReportActorKindSchema,id:z26.string().nullable(),name:z26.string().nullable()}),SupportReportLinkDTOSchema=z26.object({id:z26.uuid(),kind:SupportReportLinkKindSchema,label:z26.string(),url:SupportReportHttpUrlSchema,externalId:z26.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z26.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z26.object({id:z26.uuid(),kind:SupportReportEventKindSchema,body:z26.string().nullable(),metadata:z26.record(z26.string(),z26.unknown()),actor:SupportReportActorDTOSchema,createdAt:z26.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z26.object({id:z26.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z26.array(z26.string()),source:SupportReportSourceSchema,message:z26.string(),reporter:z26.object({id:z26.string().nullable(),name:z26.string().nullable(),email:z26.string().nullable()}),organization:z26.object({id:z26.string().nullable(),name:z26.string()}),project:z26.object({id:z26.uuid().nullable(),name:z26.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z26.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z26.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z26.string().nullable(),deliveredAt:z26.coerce.date().nullable()}).nullable(),duplicateOfReportId:z26.uuid().nullable(),resolvedAt:z26.coerce.date().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z26.string().nullable(),clientVersion:z26.string().nullable(),links:z26.array(SupportReportLinkDTOSchema),events:z26.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z26.object({reports:z26.array(SupportReportSummaryDTOSchema),total:z26.number().int().nonnegative(),statusCounts:z26.object({new:z26.number().int().nonnegative(),in_progress:z26.number().int().nonnegative(),waiting:z26.number().int().nonnegative(),resolved:z26.number().int().nonnegative(),duplicate:z26.number().int().nonnegative(),irrelevant:z26.number().int().nonnegative(),ignored:z26.number().int().nonnegative()}),limit:z26.number().int().positive(),offset:z26.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z26.object({id:z26.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z26.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z27}from"zod";var report,pylonIssue,supportCommands,init_support=__esm({"../../packages/api-contracts/dist/esm/ops/commands/support.js"(){"use strict";init_support_report_dto();init_ops();init_args();init_types();init_shared();report=z27.uuid().describe("Support report id"),pylonIssue=OpsPylonIssueIdSchema.describe("Pylon issue id"),supportCommands=[{id:"support.reports.list",summary:"List Fimo support reports, newest first",permission:"ops:support:read",effect:"read",input:z27.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z27.string().trim().min(1).max(50).optional(),search:z27.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z27.coerce.number().int().min(0).default(0),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/reports",query:compact({reason:input.reason,status:input.status,category:input.category,source:input.source,tag:input.tag,query:input.search,limit:input.limit,offset:input.offset})}),"request")},{id:"support.reports.get",summary:"Read one support report with its messages, links and context",permission:"ops:support:read",effect:"read",input:z27.object({report,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:`/support/reports/${seg(input.report)}`,query:{reason:input.reason}}),"request")},{id:"support.reports.claim",summary:"Claim a support report (mark it in progress), optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,note:z27.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.update",summary:"Change a support report's status, category, tags or duplicate link, optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z27.array(z27.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z27.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z27.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.note",summary:"Add an internal message to a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,message:z27.string().trim().min(1).max(2e4)}),cli:{fileArgs:["message"]}},{id:"support.reports.link",summary:"Link a support report to a Linear issue, Pylon ticket, project, Sentry issue or other URL",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,kind:SupportReportLinkKindSchema,label:z27.string().trim().min(1).max(240),url:z27.url({protocol:/^https?$/}).max(2e3),externalId:z27.string().trim().min(1).max(255).optional()})},{id:"support.reports.unlink",summary:"Remove a link from a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({report,link:z27.uuid().describe("Link id")})},{id:"support.intake",summary:"Show the support intake receipt: reports received and delivered in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z27.object({since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/support/intake/status",query:{since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"support.pylon.list",summary:"List Pylon support tickets in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z27.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z27.enum(["open","closed","all"]).default("open"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/pylon/issues",query:compact({since:time2(input.since),until:time2(input.until)??new Date().toISOString(),state:input.state,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"support.pylon.thread",summary:"Read the full message thread of a Pylon ticket",permission:"ops:support:read",effect:"read",input:z27.object({issue:pylonIssue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/support/issues/${seg(input.issue)}/thread`,body:{reason:input.reason}}),"request")},{id:"support.pylon.resolve",summary:"Close a Pylon ticket",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({issue:pylonIssue})},{id:"support.pylon.note",summary:"Add an internal note to a Pylon ticket (not visible to the customer)",permission:"ops:support:write",effect:"write",risk:"low",input:z27.object({issue:pylonIssue,message:z27.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z28}from"zod";var userCommands,init_user=__esm({"../../packages/api-contracts/dist/esm/ops/commands/user.js"(){"use strict";init_args();init_types();init_shared();userCommands=[{id:"user.get",summary:"Show a user: profile, role, organizations, recent sessions and usage",permission:"ops:users:read",effect:"read",input:z28.object({user:opsArgs.user,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/users/${seg(input.user)}`,query:{reason:input.reason}}),"request")},{id:"user.sessions",summary:"List sign-in sessions, for one user or across the platform",permission:"ops:users:read",effect:"read",input:z28.object({user:opsArgs.user.optional(),active:z28.boolean().optional().describe("Only sessions that have not expired or been revoked"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/sessions",query:compact({userId:input.user,active:input.active,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"user.session.revoke",summary:"Revoke one sign-in session",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z28.object({session:z28.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z29}from"zod";var evidence,versions,detectionQueries,watchCommands,init_watch=__esm({"../../packages/api-contracts/dist/esm/ops/commands/watch.js"(){"use strict";init_ops();init_args();init_types();init_shared();evidence=z29.array(z29.record(z29.string(),z29.unknown())).max(100),versions=z29.array(z29.string().trim().min(1).max(120)).max(100),detectionQueries=z29.array(z29.string().trim().min(1).max(2e3)).max(50),watchCommands=[{id:"watch.list",summary:"List watched projects and why each is watched",permission:"ops:customers:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/customers"}),"request")},{id:"watch.add",summary:"Watch a project (or update why it is watched)",permission:"ops:customers:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,importance:z29.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z29.string().trim().max(120).optional(),packageManager:z29.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z29.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z29.object({project:opsArgs.project}),request:__name(input=>({method:"GET",path:`/customers/${seg(input.project)}/validations`}),"request")},{id:"watch.validations.record",summary:"Record the outcome of validating a release, migration or change against a watched project",permission:"ops:validations:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,change:z29.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z29.string().trim().min(1).max(1e4),evidence:evidence.default([])}),cli:{fileArgs:["evidence"]}},{id:"watch.investigations.list",summary:"List open and recent investigations",permission:"ops:investigations:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/investigations"}),"request")},{id:"watch.investigations.create",summary:"Open an investigation into a problem on a project",permission:"ops:investigations:write",effect:"write",risk:"low",input:z29.object({project:opsArgs.project,title:z29.string().trim().min(1).max(240),userReport:z29.string().trim().max(1e4).optional().describe("The customer's own words")})},{id:"watch.investigations.update",summary:"Update an investigation's status, hypothesis, outcome or evidence",permission:"ops:investigations:write",effect:"write",risk:"low",input:z29.object({investigation:z29.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z29.string().trim().max(1e4).optional(),outcome:z29.string().trim().max(1e4).optional(),evidence:evidence.optional()}),cli:{fileArgs:["evidence"]}},{id:"watch.known-issues.list",summary:"List known issues and their detection queries",permission:"ops:known-issues:read",effect:"read",input:z29.object({}),request:__name(()=>({method:"GET",path:"/known-issues"}),"request")},{id:"watch.known-issues.create",summary:"Record a known issue with how to detect it and any workaround",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z29.object({fingerprint:z29.string().trim().min(1).max(240),title:z29.string().trim().min(1).max(240),description:z29.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z29.string().trim().min(1).max(64).optional(),workaround:z29.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.default("open")}),cli:{fileArgs:["detectionQueries"]}},{id:"watch.known-issues.update",summary:"Update a known issue",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z29.object({knownIssue:z29.uuid().describe("Known issue id"),title:z29.string().trim().min(1).max(240).optional(),description:z29.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z29.string().trim().min(1).max(64).optional(),workaround:z29.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.optional()}),cli:{fileArgs:["detectionQueries"]}}]}});var OPS_COMMANDS,BY_ID,OPS_OPERATION_IDS,init_commands=__esm({"../../packages/api-contracts/dist/esm/ops/commands/index.js"(){"use strict";init_agent();init_assistant();init_billing();init_core();init_health();init_merge();init_notify();init_observe();init_org();init_platform();init_platform();init_project();init_support();init_user();init_watch();OPS_COMMANDS=[...coreCommands,...projectCommands,...orgCommands,...userCommands,...mergeCommands,...agentCommands,...healthCommands,...billingCommands,...platformCommands,...observeCommands,...supportCommands,...watchCommands,...notifyCommands,...assistantCommands],BY_ID=new Map(OPS_COMMANDS.map(command=>[command.id,command])),OPS_OPERATION_IDS=OPS_COMMANDS.filter(command=>command.effect==="write").map(command=>command.id)}});import{z as z30}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=z30.object({kind:z30.literal("say"),label:z30.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z30.string().min(1).max(240).optional(),message:z30.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z30.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z30.discriminatedUnion("command",[z30.object({kind:z30.literal("app"),command:z30.literal("publish")}).strict(),z30.object({kind:z30.literal("app"),command:z30.literal("connect"),integrationKey:z30.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z30.object({fallback:z30.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z30.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z30.literal("choices"),text:z30.string().max(500).optional(),actions:z30.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("entry"),collection:z30.string().min(1).max(80),entryId:z30.string().min(1).max(120)}),z30.object({kind:z30.literal("asset"),assetId:z30.string().min(1).max(120)}),z30.object({kind:z30.literal("url"),url:z30.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z30.literal("table"),columns:z30.array(z30.object({label:z30.string().min(1).max(24)})).min(2).max(4),rows:z30.array(z30.object({cells:z30.array(z30.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:z30.literal("cards"),layout:z30.enum(["rail","stack"]).optional(),items:z30.array(z30.object({title:z30.string().min(1).max(60),subtitle:z30.string().min(1).max(120).optional(),imageUrl:z30.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z30.literal("entry"),label:z30.string().min(1).max(80),collection:z30.string().min(1).max(80),entryId:z30.string().min(1).max(120),path:z30.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z30.literal("assets"),items:z30.array(z30.object({url:z30.url({protocol:/^https$/}).max(2e3),alt:z30.string().min(1).max(120),label:z30.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z30.literal("callout"),title:z30.string().min(1).max(80),text:z30.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z30.literal("stat"),items:z30.array(z30.object({label:z30.string().min(1).max(24),value:z30.string().min(1).max(16),delta:z30.string().min(1).max(12).optional(),tone:z30.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z30.literal("chart"),unit:z30.string().min(1).max(12).optional(),points:z30.array(z30.object({label:z30.string().min(1).max(12),value:z30.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z30.literal("text"),placeholder:z30.string().min(1).max(120).optional(),multiline:z30.boolean().optional()}).strict(),ChatFormStepIdSchema=z30.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z30.object({id:ChatFormStepIdSchema,token:z30.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z30.string().trim().min(1).max(60),reason:z30.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z30.literal("capabilities"),items:z30.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=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z30.object({id:ChatFormStepIdSchema.optional(),question:z30.string().min(1).max(500),header:z30.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z30.boolean().optional(),recommended:z30.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:z30.literal("form"),steps:z30.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z30.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z30.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z30.object({stepId:ChatFormStepIdSchema.optional(),header:z30.string().min(1).max(25),question:z30.string().min(1).max(500),answer:z30.string().min(1),selectedLabels:z30.array(z30.string().min(1).max(120)).max(8),freeText:z30.string(),skipped:z30.boolean()}),ChatFormAnswerMetadataSchema=z30.object({toolCallId:z30.string().max(255).optional(),shortTitle:z30.string().max(80).optional(),questions:z30.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z30.object({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z30.object({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z30.string().min(1).max(255),partial:z30.boolean().optional()})}});import{z as z31}from"zod";var AdminTargetSchema,AdminToneSchema,AdminStatusSchema,AdminLinkSchema,AdminActionSchema,BlockBaseSchema2,AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,AdminActionsBlockSchema,AdminHandoffBlockSchema,AdminChatBlockSchema,AdminChatBlockToolInputSchema,init_admin_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/admin-chat-block.js"(){"use strict";init_chat_block();AdminTargetSchema=z31.union([z31.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z31.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z31.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z31.object({label:z31.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z31.object({label:z31.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z31.discriminatedUnion("kind",[BlockSayActionSchema,z31.object({kind:z31.literal("open"),label:z31.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z31.object({kind:z31.literal("op"),label:z31.string().trim().min(1).max(32),operation:z31.string().min(1).max(80),input:z31.record(z31.string(),z31.unknown())}).strict(),z31.object({kind:z31.literal("impersonate"),label:z31.string().trim().min(1).max(32),userId:z31.string().min(1).max(120)}).strict(),z31.object({kind:z31.literal("studio"),label:z31.string().trim().min(1).max(32),projectId:z31.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z31.object({fallback:z31.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z31.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z31.literal("record"),kind:z31.string().trim().min(1).max(24),name:z31.string().trim().min(1).max(80),id:z31.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z31.array(z31.object({label:z31.string().trim().min(1).max(24),value:z31.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z31.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z31.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("cards"),items:z31.array(z31.object({name:z31.string().trim().min(1).max(60),subtitle:z31.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z31.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z31.literal("table"),columns:z31.array(z31.object({label:z31.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z31.array(z31.object({cells:z31.array(z31.string().max(80)).min(2).max(3),tone:AdminToneSchema.optional(),target:AdminTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),AdminTimelineBlockSchema=BlockBaseSchema2.extend({type:z31.literal("timeline"),events:z31.array(z31.object({at:z31.string().trim().min(1).max(16),label:z31.string().trim().min(1).max(80),detail:z31.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("stats"),items:z31.array(z31.object({label:z31.string().min(1).max(24),value:z31.string().min(1).max(16),delta:z31.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z31.literal("excerpt"),source:z31.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z31.discriminatedUnion("kind",[z31.object({kind:z31.literal("lines"),lines:z31.array(z31.object({text:z31.string().max(200),highlight:z31.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z31.object({kind:z31.literal("message"),author:z31.string().trim().min(1).max(60),at:z31.string().max(24).optional(),text:z31.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z31.literal("media"),items:z31.array(z31.object({url:z31.url({protocol:/^https$/}).max(2e3),alt:z31.string().min(1).max(120),label:z31.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z31.literal("actions"),actions:z31.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z31.literal("handoff"),prompt:z31.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z31.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z31.object({block:AdminChatBlockSchema})}});import{z as z32}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=z32.object({shape:z32.enum(CHAT_PORTRAIT_SHAPES),eyes:z32.enum(CHAT_PORTRAIT_EYES),mouth:z32.enum(CHAT_PORTRAIT_MOUTHS),color:z32.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z33}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,ChatRoutineWaitMinutesSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,AgentHoursUsageDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z33.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z33.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z33.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z33.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z33.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z33.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z33.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z33.object({text:z33.string(),title:z33.string(),explanation:z33.string(),watches:z33.array(z33.object({url:z33.string(),health:z33.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z33.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z33.object({text:z33.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z33.object({manual:z33.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z33.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z33.object({message:z33.string().trim().min(1).max(2e4),decision:z33.boolean().optional(),incomplete:z33.boolean().optional()}).refine(report2=>!(report2.decision===!0&&report2.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z33.object({id:z33.string().uuid(),threadId:z33.string().uuid(),runThreadId:z33.string().uuid(),name:z33.string(),instructions:z33.string(),template:z33.object({key:z33.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z33.string(),modelIsDefault:z33.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z33.boolean(),nextRunAt:z33.string().nullable(),lastRunAt:z33.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z33.string().nullable(),createdAt:z33.string(),updatedAt:z33.string()}),ChatRoutineListDTOSchema=z33.object({routines:z33.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z33.object({usedMs:z33.number().int().min(0),includedMs:z33.number().int().min(0),periodStart:z33.string(),periodEnd:z33.string(),stopsAtIncluded:z33.boolean(),canStart:z33.boolean(),canPayOverage:z33.boolean(),overageRateMicrosPerHour:z33.number().int().nullable(),billedMs:z33.number().int().min(0),billedMicros:z33.number().int().min(0)}),ChatRoutineCreateSchema=z33.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional(),waitMinutes:ChatRoutineWaitMinutesSchema.optional()}),ChatRoutineUpdateSchema=z33.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z33.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z33.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown","routine_needs_pro","routine_is_default"]),ChatRoutineRefusalDTOSchema=z33.object({message:z33.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z33.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z33.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z33.object({kind:z33.enum(["person","agent"]),name:z33.string().nullable()}),ChatRoutineRunDTOSchema=z33.object({messageId:z33.string().uuid(),invocationId:z33.string().uuid().nullable(),startedAt:z33.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z33.string().nullable(),events:z33.number().int().min(1),durationMs:z33.number().int().min(0).nullable(),credits:z33.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z33.object({runs:z33.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z33.object({message:z33.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z33.object({kind:z33.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z33.string().uuid().nullable()})}});import{z as z34}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=z34.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z34.string(),displayName:z34.string().nullable(),subdomain:z34.string().nullable().optional(),subdomainUpdatedAt:z34.date().nullable().optional(),organizationId:z34.string().nullable(),createdBy:z34.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z34.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z34.string(),thumbnailUrl:z34.string().nullable(),publishedThumbnailUrl:z34.string().nullable(),category:z34.string().nullable(),snapshotUrl:z34.string().startsWith("/").optional(),appUrl:z34.string().nullable(),lastPublishedAt:z34.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z34.object({name:z34.string().optional(),enabledChatModels:z34.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z34.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z34.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z34.object({id:z34.uuid(),name:z34.string(),displayName:z34.string().nullable(),thumbnailUrl:z34.string().nullable(),category:z34.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),avatar:z34.string().nullable(),color:z34.object({bg:z34.string(),text:z34.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z34.object({path:z34.string(),content:z34.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z34.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z34.object({id:z34.string(),messageId:z34.string(),versionId:z34.string().nullable(),role:ProjectChatMessageRole,parts:z34.array(z34.any()),createdAt:z34.coerce.date()}),MessageUserMetadataSchema=z34.object({id:z34.string(),name:z34.string().nullable().optional(),image:z34.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z34.number(),metadata:z34.object({user:MessageUserMetadataSchema,changeManifest:z34.array(z34.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z34.object({versionId:z34.uuid(),commitHash:z34.string(),name:z34.string(),description:z34.string().nullable(),kind:z34.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z34.object({versionCount:z34.number().int().nonnegative(),snapshotBytes:z34.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z34.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z34.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z34.object({content:z34.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z34.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z34.object({success:z34.boolean(),message:z34.string().optional(),warning:z34.string().optional(),durationMs:z34.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z34.object({code:z34.literal("PUBLISH_UPGRADE_REQUIRED"),message:z34.string(),currentVersion:z34.number().int().positive(),targetVersion:z34.literal(4)}),ProjectLatestPublicationAttemptSchema=z34.object({publicationId:z34.uuid(),status:z34.enum(["queued","building","published","failed","canceled"]),failureCode:z34.string().nullable(),sourceBranch:z34.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z34.object({isPublished:z34.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z34.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z34.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z34.object({label:z34.string().trim().min(1).max(120).optional(),notes:z34.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z34.object({success:z34.boolean(),message:z34.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z34.boolean(),publicationId:z34.string().optional(),url:z34.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z35}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_organization_features_dto();init_project_dto();ChatMessageListDTOSchema=z35.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z35.object({items:z35.array(ProjectMessagePublicDTOSchema),nextCursor:z35.string().nullable()}),ChatLiveTurnDTOSchema=z35.object({invocationId:z35.string(),step:z35.enum(["preparing","working","compacting","merging"]),startedAt:z35.string(),continuesInvocationId:z35.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z35.object({threadId:z35.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z35.object({kind:z35.enum(["person","agent","routine","system"]),id:z35.string().nullable()}),ChatThreadMessageDTOSchema=z35.object({id:z35.string(),role:z35.enum(["user","assistant"]),parts:z35.array(z35.unknown()),metadata:z35.record(z35.string(),z35.unknown()).nullable(),versionId:z35.string().nullable().optional(),createdAt:z35.date().transform(value=>value.toISOString()),providerMessageId:z35.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z35.string().nullable().optional(),invocationStatus:z35.string().nullable().optional(),invocationTerminalReason:z35.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z35.object({id:z35.string(),parts:z35.array(z35.unknown()),metadata:z35.record(z35.string(),z35.unknown()).nullable(),providerMessageId:z35.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z35.boolean(),queuedAt:z35.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z35.object({type:z35.literal("merge_conflict"),merge:z35.object({mergeId:z35.string().uuid(),projectId:z35.string(),fromBranch:z35.string(),toBranch:z35.string()}),publishAfterMerge:z35.boolean()}),ChatThreadMessagesPageDTOSchema=z35.object({threadId:z35.string().nullable(),title:z35.string().nullable(),messages:z35.array(ChatThreadMessageDTOSchema),nextCursor:z35.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z35.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z35.boolean().optional(),queueWaitUntil:z35.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z35.object({kind:z35.literal("replay"),threadId:z35.string(),userMessageId:z35.string()}),ChatQueuedOutcomeDTOSchema=z35.object({kind:z35.literal("queued"),threadId:z35.string(),userMessageId:z35.string(),blockingRootId:z35.string().optional()}),ChatBusyOutcomeDTOSchema=z35.object({kind:z35.literal("busy"),threadId:z35.string(),userMessageId:z35.string(),blockingRootId:z35.string().optional()}),ChatRefusedOutcomeDTOSchema=z35.object({kind:z35.literal("refused"),threadId:z35.string(),userMessageId:z35.string(),refusedInvocationId:z35.string(),terminalReason:z35.string()}),ChatNonStreamingOutcomeDTOSchema=z35.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z35.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z35.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z35.object({quietRuns:z35.number().int().nonnegative(),since:z35.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z35.string().nullable(),nextRunAt:z35.string().nullable(),wakesOnChanges:z35.boolean()}),ProjectChatDescriptionSchema=z35.string().trim().max(2e3),ProjectChatDTOSchema=z35.object({id:z35.string().uuid(),kind:ProjectChatKindSchema,title:z35.string().nullable(),description:z35.string().nullable(),template:z35.string().nullable(),parentThreadId:z35.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z35.string(),lastMessageAt:z35.string().nullable(),preview:z35.string().nullable(),running:z35.boolean(),awaitingAnswer:z35.boolean(),unread:z35.boolean(),pinned:z35.boolean(),archived:z35.boolean(),muted:z35.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z35.object({chats:z35.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z35.object({id:z35.string().uuid()}),ProjectChatTitleSchema=z35.string().trim().min(1).max(120),ProjectChatCreateSchema=z35.object({id:z35.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z35.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=z35.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=z35.object({cron:z35.string()}),ChatTemplateRoutineDTOSchema=z35.object({name:z35.string(),instructions:z35.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z35.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z35.object({id:z35.string(),name:z35.string(),summary:z35.string(),description:z35.string(),portrait:ChatPortraitSchema,plans:z35.array(AgentPlanSchema),routines:z35.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z35.object({templates:z35.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z35.object({read:z35.boolean(),pinned:z35.boolean(),archived:z35.boolean(),muted:z35.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 z36}from"zod";var ADMIN_ASSISTANT_BASE_PATH,ADMIN_ASSISTANT_PATHS,ADMIN_ASSISTANT_MESSAGE_MAX_CHARS,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS,ADMIN_ASSISTANT_REQUEST_MAX_BYTES,AdminAssistantFormResponseSchema,AdminAssistantOutgoingMessageSchema,AdminAssistantSendRequestSchema,AdminAssistantSendOutcomeSchema,AdminAssistantStreamHeadSchema,AdminAssistantThreadSummarySchema,AdminAssistantThreadListQuerySchema,AdminAssistantThreadListResponseSchema,AdminAssistantThreadResponseSchema,AdminAssistantLiveTurnResponseSchema,AdminAssistantAbortResponseSchema,AdminAssistantThreadUpdateSchema,AdminAssistantThreadDeleteResponseSchema,init_admin_assistant=__esm({"../../packages/api-contracts/dist/esm/types/admin-assistant.js"(){"use strict";init_chat_dto();init_chat_block();ADMIN_ASSISTANT_BASE_PATH="/api/ops/assistant",ADMIN_ASSISTANT_PATHS={chat:`${ADMIN_ASSISTANT_BASE_PATH}/chat`,threads:`${ADMIN_ASSISTANT_BASE_PATH}/threads`,thread:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}`,"thread"),live:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/live`,"live"),stream:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/stream`,"stream"),abort:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/abort`,"abort")},ADMIN_ASSISTANT_MESSAGE_MAX_CHARS=2e4,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS=4e3,ADMIN_ASSISTANT_REQUEST_MAX_BYTES=256*1024,AdminAssistantFormResponseSchema=ChatFormResponseSchema.extend({questions:z36.array(ChatFormAnswerItemSchema.extend({answer:z36.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z36.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z36.object({id:z36.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z36.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z36.object({threadId:z36.string().uuid().optional(),message:AdminAssistantOutgoingMessageSchema,formResponse:AdminAssistantFormResponseSchema.optional()}).strict().superRefine((body,context)=>{body.message.text.trim().length===0&&!body.formResponse&&context.addIssue({code:"custom",path:["message","text"],message:"A message cannot be empty."})}),AdminAssistantSendOutcomeSchema=z36.discriminatedUnion("kind",[z36.object({kind:z36.literal("replay"),threadId:z36.string(),userMessageId:z36.string()}),z36.object({kind:z36.literal("queued"),threadId:z36.string(),userMessageId:z36.string(),blockingRootId:z36.string().optional()}),z36.object({kind:z36.literal("busy"),threadId:z36.string(),userMessageId:z36.string(),blockingRootId:z36.string().optional()}),z36.object({kind:z36.literal("refused"),threadId:z36.string(),userMessageId:z36.string(),refusedInvocationId:z36.string(),terminalReason:z36.string()})]),AdminAssistantStreamHeadSchema=z36.object({kind:z36.literal("turn"),threadId:z36.string(),userMessageId:z36.string(),invocationId:z36.string()}),AdminAssistantThreadSummarySchema=z36.object({id:z36.string().uuid(),title:z36.string().nullable(),lastMessageAt:z36.string().nullable(),createdAt:z36.string()}),AdminAssistantThreadListQuerySchema=z36.object({q:z36.string().trim().max(200).optional(),cursor:z36.string().max(500).optional(),limit:z36.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z36.object({threads:z36.array(AdminAssistantThreadSummarySchema),nextCursor:z36.string().nullable()}),AdminAssistantThreadResponseSchema=z36.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z36.string().nullable()}),messages:z36.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z36.object({threadId:z36.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z36.object({aborted:z36.boolean()}),AdminAssistantThreadUpdateSchema=z36.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z36.object({deleted:z36.literal(!0)})}});import{z as z37}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
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=z37.enum(REPORT_TONES),blockCommon={title:z37.string().trim().min(1).max(120).optional(),fallback:z37.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z37.object({type:z37.literal("text"),...blockCommon,text:z37.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=z37.object({type:z37.literal("metric"),...blockCommon,items:z37.array(z37.object({value:z37.string().trim().min(1).max(24),unit:z37.string().trim().min(1).max(12).optional(),label:z37.string().trim().min(1).max(160),note:z37.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z37.array(z37.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=z37.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z37.object({type:z37.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z37.string().trim().min(1).max(12).optional(),points:z37.array(z37.object({label:z37.string().trim().min(1).max(24),value:z37.number().finite(),highlight:z37.boolean().optional()}).strict()).min(2).max(24),caption:z37.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=z37.object({type:z37.literal("list"),...blockCommon,items:z37.array(z37.object({tone:ReportToneSchema.optional(),label:z37.string().trim().min(1).max(24).optional(),heading:z37.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z37.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z37.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=z37.object({type:z37.literal("table"),...blockCommon,columns:z37.array(z37.object({label:z37.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z37.array(z37.object({cells:z37.array(z37.object({text:z37.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z37.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=z37.object({type:z37.literal("media"),...blockCommon,assetId:z37.uuid(),alt:z37.string().trim().min(1).max(300),caption:z37.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=z37.object({type:z37.literal("links"),...blockCommon,items:z37.array(z37.object({label:z37.string().trim().min(1).max(120),url:z37.url({protocol:/^https$/}).max(2e3),description:z37.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z37.object({type:z37.literal("code"),...blockCommon,language:z37.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z37.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z37.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z37.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z37.object({title:z37.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z37.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z37.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=z37.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=z37.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z37.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z38}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=z38.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z38.object({dev:z38.string().trim().min(1).optional(),build:z38.string().trim().min(1).optional(),install:z38.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z38.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z38.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z38.object({type:z38.enum(["header","cookie","query","host"]),key:z38.string().min(1).optional(),value:z38.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:z38.array(FimoHostingConditionSchema).min(1).optional(),missing:z38.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z38.object({source:z38.string().min(1),destination:z38.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z38.object({source:z38.string().min(1),destination:z38.string().min(1),permanent:z38.boolean().optional(),statusCode:z38.union([z38.literal(301),z38.literal(302),z38.literal(307),z38.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z38.object({source:z38.string().min(1),headers:z38.array(z38.object({key:z38.string().min(1),value:z38.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z38.object({rewrites:z38.array(FimoHostingRewriteSchema).optional(),redirects:z38.array(FimoHostingRedirectSchema).optional(),headers:z38.array(FimoHostingHeaderSchema).optional(),cleanUrls:z38.boolean().optional(),trailingSlash:z38.boolean().optional()}).strict(),FimoAppConfigSchema=z38.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(path50){return[...path50.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path50,params){return pageRouteParamNames(path50).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 z39}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=z39.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z39.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z39.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z39.string().nullable(),deletedAt:z39.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z39.object({id:z39.union([z39.literal(PREVIEW_ENVIRONMENT_KEY),z39.uuid()]),name:z39.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z39.object({sessionId:z39.uuid(),name:z39.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z39.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=z39.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z39.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z39.object({surface:z39.enum(["code","schemas","content","translations","assets","forms"]),status:z39.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z39.number().int().nonnegative(),conflictCount:z39.number().int().nonnegative()}),BranchDiffResultSchema=z39.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z39.coerce.date(),surfaces:z39.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z40}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=z40.object({projectId:z40.uuid(),name:z40.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z40.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z40.literal("production"),sourceBranch:BranchSchema,isPublished:z40.boolean(),url:z40.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z40.literal(PREVIEW_ENVIRONMENT_KEY),kind:z40.literal("preview"),matchedBranchCount:z40.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z40.literal("custom"),matchedBranchCount:z40.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z40.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z40.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z40.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z40.object({deletedId:z40.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z41}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectVariableBaseSchema,ProjectVariableDTOSchema,ProjectVariableDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z41.object({kind:z41.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z41.object({kind:z41.enum(["variable","secret"]),value:z41.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z41.string().min(1).max(255),exposure:z41.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z41.object({kind:z41.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z41.object({id:z41.uuid(),projectId:z41.uuid(),key:z41.string(),kind:z41.literal("secret"),exposure:z41.literal("private"),environment:EnvironmentKeySchema,maskedValue:z41.string().optional(),createdAt:z41.date().transform(value=>value.toISOString()),updatedAt:z41.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z41.object({id:z41.uuid(),projectId:z41.uuid(),key:z41.string(),kind:z41.literal("variable"),environment:EnvironmentKeySchema,createdAt:z41.date().transform(value=>value.toISOString()),updatedAt:z41.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z41.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z41.literal("public"),value:z41.string()}),ProjectVariableBaseSchema.extend({exposure:z41.literal("private"),maskedValue:z41.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z41.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z42}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=z42.object({success:z42.literal(!0),downloadUrl:z42.string(),expiresAt:z42.string(),fileSize:z42.number(),duration:z42.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z42.object({success:z42.literal(!0),projectId:z42.string(),projectName:z42.string(),displayName:z42.string(),projectUrl:z42.string(),duration:z42.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z42.object({contentTypes:z42.number(),entries:z42.number(),assets:z42.number(),translations:z42.number(),forms:z42.number(),codeFiles:z42.number(),assetFiles:z42.number()}),ImportPreviewSurfaceDTOSchema=z42.object({name:z42.string(),included:z42.boolean(),count:z42.number().optional(),note:z42.string().optional()}),ImportPreviewDTOSchema=z42.object({projectName:z42.string(),displayName:z42.string().nullable(),category:z42.string().nullable(),exportedAt:z42.string(),version:z42.string(),envScope:z42.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z42.array(ImportPreviewSurfaceDTOSchema),fileSize:z42.number(),fileName:z42.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z42.object({success:z42.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z43}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictTargetCommitSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z43.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z43.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z43.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z43.object({verb:SurfaceDeltaVerbSchema,key:z43.string(),detail:z43.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z43.record(z43.string(),z43.unknown()).optional()}),PerSurfaceDeltaSchema=z43.object({surface:SurfaceNameSchema,status:z43.enum(["ok","timed_out","failed","unchanged"]),durationMs:z43.number().int().nonnegative().optional(),changedCount:z43.number().int().nonnegative(),conflictCount:z43.number().int().nonnegative(),items:z43.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z43.boolean().optional(),error:z43.string().optional()}),CrossSurfaceFindingSchema=z43.object({id:z43.string(),kind:z43.string(),description:z43.string(),severity:z43.enum(["warning","error"]),source:z43.object({surface:SurfaceNameSchema,key:z43.string()}),target:z43.object({surface:SurfaceNameSchema,key:z43.string()}),actions:z43.array(z43.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z43.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z43.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z43.coerce.date(),surfaces:z43.array(PerSurfaceDeltaSchema),agents:z43.array(z43.object({id:z43.string(),name:z43.string(),status:z43.enum(["active","paused","failed"]),lastRunAt:z43.coerce.date().nullable()})).optional(),crossSurface:z43.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z43.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z43.coerce.date(),surfaces:z43.array(PerSurfaceDeltaSchema),crossSurface:z43.array(CrossSurfaceFindingSchema).optional(),fingerprint:z43.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z43.object({path:z43.string(),state:z43.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z43.string(),additions:z43.number().int().nonnegative(),deletions:z43.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z43.object({oid:z43.string().optional(),content:z43.string().optional(),truncated:z43.boolean(),binary:z43.boolean()}),CodeConflictDetailSchema=z43.object({path:z43.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z43.string(),targetTipSha:z43.string(),mergeBaseSha:z43.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z43.object({id:z43.string(),slug:z43.string(),contentType:z43.string(),data:z43.record(z43.string(),z43.unknown()),updatedAt:z43.coerce.date()}),ContentRowDiffSchema=z43.object({collection:z43.string(),rowId:z43.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z43.object({name:z43.string(),label:z43.string(),isSingleton:z43.boolean(),fields:z43.record(z43.string(),z43.unknown())}),SchemaTypeDiffSchema=z43.object({typeName:z43.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),mimeType:z43.string().nullable(),storageKey:z43.string().nullable(),url:z43.string().nullable(),fileSize:z43.number().nullable(),width:z43.number().nullable(),height:z43.number().nullable(),altText:z43.string().nullable(),caption:z43.string().nullable(),createdAt:z43.coerce.date(),updatedAt:z43.coerce.date()}),AssetDiffSchema=z43.object({assetId:z43.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z43.object({locale:z43.string(),key:z43.string(),parent:z43.string().nullable(),child:z43.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z43.object({formName:z43.string(),label:z43.string().nullable(),schemaFingerprint:z43.string(),fields:z43.record(z43.string(),z43.unknown()),settings:z43.record(z43.string(),z43.unknown()).optional()}),FormSchemaDiffSchema=z43.object({formName:z43.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=z43.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z43.object({sha:z43.string(),subject:z43.string(),body:z43.string().optional(),author:z43.string(),date:z43.string()}),ConflictSchema=z43.object({surface:SurfaceNameSchema,key:z43.string(),kind:ConflictKindSchema.optional(),description:z43.string(),parentValue:z43.unknown().optional(),childValue:z43.unknown().optional(),conflictingFields:z43.array(z43.string()).optional(),code:z43.object({path:z43.string(),unresolvable:z43.boolean().optional(),reason:z43.string().optional(),targetCommits:z43.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z43.object({field:z43.string(),choice:z43.enum(["parent","child","pick","ai-pick"]),pickedValue:z43.unknown().optional(),aiSessionId:z43.string().optional()}),ConflictResolutionSchema=z43.object({surface:SurfaceNameSchema,key:z43.string(),choice:z43.enum(["parent","child","pick"]),pickedValue:z43.unknown().optional(),fieldPicks:z43.array(FieldPickSchema).optional()}),MergeResultSchema=z43.object({ok:z43.boolean(),mergeId:z43.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z43.array(z43.object({surface:SurfaceNameSchema,count:z43.number().int().nonnegative()})),conflicts:z43.array(ConflictSchema).optional(),summary:z43.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z43.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z43.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z43.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z43.boolean().optional()}),ResolvedStrategySchema=z43.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z43.boolean()}),MergeRequestSchema=z43.object({from:BranchSchema,allowDirectMerge:z43.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z43.object({mergeId:z43.string().uuid(),streamUrl:z43.string(),strategy:ResolvedStrategySchema,acceptedAt:z43.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z43.object({mergeId:z43.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z43.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z43.array(ConflictSchema),draftResolutions:z43.array(ConflictResolutionSchema),lastEditedBy:z43.string().nullable(),lastEditedAt:z43.coerce.date().nullable(),initiator:z43.object({userId:z43.string().nullable(),role:z43.string().nullable(),agentName:z43.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z43.object({resolutions:z43.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z43.object({mergeId:z43.string().uuid(),draftResolutions:z43.array(ConflictResolutionSchema),lastEditedAt:z43.coerce.date(),lastEditedBy:z43.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z43.object({mergeId:z43.string().uuid(),resolutions:z43.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z43.object({mergeId:z43.string().uuid()}),PublishReleaseRequestSchema=z43.object({version:z43.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z43.string().max(2e4).optional()}),PublishReleaseResultSchema=z43.object({releaseTag:z43.string(),sha:z43.string(),publishedAt:z43.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z44}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=z44.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z44.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z44.object({capturedAt:z44.coerce.date(),fingerprint:z44.string().min(1).max(256),counts:z44.object({code:z44.number().int().nonnegative(),content:z44.number().int().nonnegative(),schemas:z44.number().int().nonnegative(),labels:z44.number().int().nonnegative(),assets:z44.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z44.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z44.object({diff:DiffReportSchema,code:z44.array(CodeFileDiffSchema.extend({raw:z44.string().max(24576)})).max(200),schemas:z44.array(SchemaTypeDiffSchema).max(200),content:z44.array(z44.object({key:z44.string().min(1).max(512),collection:z44.string().min(1).max(256),slug:z44.string().max(512).optional(),verb:z44.enum(["added","modified","deleted"]),fields:z44.array(z44.object({name:z44.string().min(1).max(256),before:z44.unknown().optional(),after:z44.unknown().optional()})).max(20)})).max(200),labels:z44.array(z44.object({key:z44.string().min(1).max(512),locale:z44.string().min(1).max(64).optional(),before:z44.unknown().nullable(),after:z44.unknown().nullable()})).max(200),assets:z44.array(z44.object({key:z44.string().min(1).max(512),name:z44.string().min(1).max(512),verb:z44.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z44.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z45}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=z45.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z45.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z45.object({sessionId:z45.uuid(),branch:z45.string().min(1),targetBranch:z45.string().min(1),revision:z45.string().min(1),fingerprint:z45.string().min(1),source:z45.enum(["studio","slack","mcp"]),threadId:z45.uuid().nullable(),invocationId:z45.uuid().nullable(),conversationBranch:z45.string().nullable(),capturedAt:z45.string(),surfaces:z45.array(PerSurfaceDeltaSchema).optional(),counts:z45.record(z45.string(),z45.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z45.strictObject({sessionId:z45.uuid(),summary:z45.string().trim().min(1).max(240),targetBranch:z45.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z45.object({requested:z45.literal(!0),alreadyRequested:z45.boolean(),reviewId:z45.uuid(),reviewUrl:z45.url(),status:z45.literal("pending"),sessionId:z45.uuid(),branch:z45.string(),targetBranch:z45.string(),revision:z45.string(),savedRevision:z45.string(),fingerprint:z45.string(),visibility:z45.literal("user-visible"),retention:z45.literal("durable"),expiresAt:z45.null(),merged:z45.literal(!1),published:z45.literal(!1),links:z45.object({preview:z45.url(),changes:z45.url(),conversation:z45.url().nullable()})}),AgentBranchProposalDTOSchema=z45.object({id:z45.uuid(),envId:z45.uuid(),sessionId:z45.uuid().nullable(),skillName:z45.string().min(1),classification:AgentBranchClassificationSchema,rationale:z45.string().nullable(),summary:z45.string().nullable(),surfaceDeltas:z45.record(z45.string(),z45.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z45.coerce.date(),decidedAt:z45.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z45.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z45.object({path:z45.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z45.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z45.object({code:z45.literal("merge_conflict"),message:z45.string(),conflicts:z45.record(z45.string(),z45.number().int().nonnegative())})}});import{z as z46}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=z46.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z46.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=z46.object({description:z46.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z46.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z46.array(z46.uuid()).optional()}),AgentQuestionSchema=z46.object({id:z46.uuid(),projectId:z46.uuid(),threadId:z46.uuid(),invocationId:z46.uuid(),agentKey:z46.string().min(1).max(120),anchorEnv:z46.string().min(1).max(64),retainedEnv:z46.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z46.string().min(1).nullable(),continuationInvocationId:z46.uuid().nullable(),askedAt:z46.coerce.date(),expiresAt:z46.coerce.date(),closedAt:z46.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z46.object({questionId:z46.uuid(),invocationId:z46.uuid(),askedAt:z46.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z46.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z46.object({question:AgentQuestionSchema,continuationInvocationId:z46.uuid(),deduped:z46.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z47}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=z47.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z47.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z47.enum(["secret_text"]),IntegrationCredentialUsageSchema=z47.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z47.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z47.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z47.object({mode:IntegrationAuthModeSchema,label:z47.string().min(1),description:z47.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z47.object({id:z47.string().min(1),label:z47.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z47.boolean()}),IntegrationToolDefinitionDTOSchema=z47.object({key:z47.string().min(1),name:z47.string().min(1),description:z47.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z47.object({title:z47.string().min(1),description:z47.string().min(1),command:z47.string().min(1).optional()}),IntegrationInfoDTOSchema=z47.object({key:z47.string().min(1),name:z47.string().min(1),summary:z47.string().min(1),type:z47.enum(["native","mcp"]).optional(),url:z47.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z47.array(IntegrationAuthModeDTOSchema),credentials:z47.array(IntegrationCredentialDefinitionDTOSchema),tools:z47.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z47.enum(["available","unavailable"]).optional(),connectionCapabilities:z47.object({customIdentityCreation:z47.boolean()}).optional(),recipes:z47.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z47.object({projectId:z47.uuid(),integrationKey:z47.string().min(1),name:z47.string().min(1),summary:z47.string().min(1),installed:z47.boolean(),enabled:z47.boolean(),setupState:z47.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z47.string().nullable(),connectionId:z47.uuid().nullable().optional(),connectionAlias:z47.string().min(1).nullable().optional(),connectionStatus:z47.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z47.array(z47.string()),installedAt:z47.coerce.date().nullable(),updatedAt:z47.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z47.object({id:z47.uuid(),projectId:z47.uuid(),integrationKey:z47.string().min(1),enabled:z47.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z47.string(),connectionId:z47.uuid().nullable().optional(),connectionAlias:z47.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z47.array(z47.string()),createdAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z47.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z47.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z47.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z47.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z47.object({id:z47.uuid(),organizationId:z47.string().min(1),integrationKey:z47.string().min(1),registrationId:z47.uuid().nullable(),alias:z47.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z47.string().min(1),externalAccountName:z47.string().nullable(),externalBotUserId:z47.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z47.array(z47.string()),connectedAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z47.boolean(),isDefault:z47.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z47.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z47.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z47.record(McpHeaderNameSchema,z47.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z47.object({alias:z47.string().min(1).max(120).optional(),token:z47.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z47.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=z47.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z47.object({displayName:z47.string().trim().min(1).max(35),backgroundColor:z47.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z47.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z47.discriminatedUnion("mode",[z47.object({mode:z47.literal("personal"),alias:z47.string().min(1).max(120),token:z47.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z47.boolean().optional()}),z47.object({mode:z47.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z47.boolean().optional(),registrationId:z47.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=z47.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z47.union([z47.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z47.object({type:z47.literal("mcp"),name:z47.string().trim().min(1).max(120),url:z47.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z47.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z47.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=z47.object({integrationKey:z47.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z47.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z47.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z47.literal("oauth"),connectUrl:z47.string().url(),expiresAt:z47.coerce.date()})]),ReusableMcpServerAuthKindSchema=z47.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z47.object({id:z47.uuid(),name:z47.string().min(1),host:z47.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z47.string().min(1),availability:z47.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z47.object({query:z47.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z47.object({serverId:z47.uuid()}),LinearOAuthApplicationDistributionSchema=z47.enum(["private","public"]),OrganizationLinearAppDTOSchema=z47.object({id:z47.uuid(),displayName:z47.string().min(1),description:z47.string().nullable(),iconUrl:z47.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z47.enum(["active","revoked"]),connectionIds:z47.array(z47.uuid()),createdAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z47.object({appName:z47.string().trim().min(2).max(80),description:z47.string().trim().max(1e3).optional(),iconUrl:z47.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z47.object({projectId:z47.uuid(),registrationId:z47.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z47.object({integrationKey:z47.string().min(1),connectUrl:z47.string().url(),expiresAt:z47.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z47.discriminatedUnion("mode",[z47.object({mode:z47.literal("personal"),integrationKey:z47.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z47.object({mode:z47.literal("oauth"),integrationKey:z47.string().min(1),connectUrl:z47.string().url(),expiresAt:z47.coerce.date()})]),BindProjectChannelRequestSchema=z47.object({ref:z47.string().min(1),connectionAlias:z47.string().min(1).optional(),agentName:z47.string().min(1).max(160).nullable().optional(),force:z47.boolean().optional()}),ListProjectChannelsQuerySchema=z47.object({integrationKey:z47.string().min(1)}),SearchProjectChannelsQuerySchema=z47.object({integrationKey:z47.string().min(1),connectionAlias:z47.string().min(1),query:z47.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z47.object({id:z47.uuid(),projectId:z47.uuid(),integrationKey:z47.string().min(1),connectionId:z47.uuid(),externalWorkspaceId:z47.string().min(1),externalChannelId:z47.string().min(1),externalChannelName:z47.string().nullable(),agentName:z47.string().nullable(),enabled:z47.boolean(),createdAt:z47.coerce.date(),updatedAt:z47.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z47.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z47.object({id:z47.string().min(1),name:z47.string().min(1),visibility:z47.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z47.string().min(1).nullable(),canMove:z47.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z47.object({markdown:z47.boolean().optional(),summary:z47.boolean().optional(),links:z47.boolean().optional(),branding:z47.boolean().optional(),images:z47.boolean().optional(),html:z47.union([z47.literal("cleaned"),z47.literal("raw"),z47.boolean()]).optional(),json:z47.union([z47.boolean(),z47.object({prompt:z47.string().min(1).max(1e4),schema:z47.record(z47.string(),z47.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z47.object({url:z47.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z47.boolean().optional(),timeoutMs:z47.number().int().positive().max(12e4).optional(),waitForMs:z47.number().int().min(0).max(3e4).optional(),maxAgeMs:z47.number().int().min(0).optional(),minAgeMs:z47.number().int().min(0).optional(),storeInCache:z47.boolean().optional(),proxy:z47.enum(["basic","enhanced","auto"]).optional(),mobile:z47.boolean().optional(),location:z47.object({country:z47.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z47.array(z47.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z47.object({query:z47.string().min(1),maxResults:z47.number().int().positive().max(20).optional(),sources:z47.array(z47.enum(["web","news","images"])).min(1).max(3).optional(),categories:z47.array(z47.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z47.array(z47.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z47.array(z47.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z47.enum(["hour","day","week","month","year"]).optional(),location:z47.string().min(1).max(160).optional(),country:z47.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z47.boolean().optional(),timeoutMs:z47.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z47.object({query:z47.string().min(1).max(500),maxResults:z47.number().int().min(1).max(100).optional(),types:z47.array(z47.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z47.array(z47.string().min(1).max(512)).min(1).max(20).optional(),sources:z47.array(z47.string().min(1).max(512)).min(1).max(20).optional(),passages:z47.number().int().min(1).max(5).optional(),skills:z47.literal("only").optional(),language:z47.string().min(1).optional(),topic:z47.string().min(1).optional(),license:z47.string().min(1).optional(),minStars:z47.number().int().min(0).optional(),maxStars:z47.number().int().min(0).optional(),archived:z47.boolean().optional(),fork:z47.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z47.object({query:z47.string().min(1).max(500),maxResults:z47.number().int().min(1).max(500).optional(),authors:z47.array(z47.string().min(1)).min(1).optional(),categories:z47.array(z47.string().min(1)).min(1).optional(),from:z47.iso.date().optional(),to:z47.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z47.object({paperId:z47.string().min(1).max(512),query:z47.string().min(1).max(500).optional(),maxPassages:z47.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z47.object({paperId:z47.string().min(1).max(512),intent:z47.string().min(1).max(500),mode:z47.enum(["similar","citers","references"]).optional(),maxResults:z47.number().int().min(1).max(500).optional(),rerank:z47.boolean().optional(),anchors:z47.array(z47.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z47.object({url:z47.string().url(),search:z47.string().min(1).optional(),limit:z47.number().int().positive().max(200).optional(),includeSubdomains:z47.boolean().optional(),timeoutMs:z47.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z47.object({url:z47.string().url(),limit:z47.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z47.boolean().optional(),timeoutMs:z47.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z47.object({text:z47.string().min(1).max(200).optional(),cron:z47.string().min(1).max(120).optional(),timezone:z47.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z47.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z47.boolean().optional(),timeoutMs:z47.number().int().positive().max(12e4).optional(),waitForMs:z47.number().int().min(0).max(3e4).optional(),maxAgeMs:z47.number().int().min(0).optional(),minAgeMs:z47.number().int().min(0).optional(),storeInCache:z47.boolean().optional(),proxy:z47.enum(["basic","enhanced","auto"]).optional(),mobile:z47.boolean().optional(),location:z47.object({country:z47.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z47.array(z47.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z47.union([z47.object({type:z47.enum(["scrape","crawl"]).default("scrape"),urls:z47.array(z47.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z47.object({type:z47.literal("search"),queries:z47.array(z47.string().min(1).max(256)).min(1).max(12),searchWindow:z47.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z47.number().int().min(1).max(50).optional(),includeDomains:z47.array(z47.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z47.array(z47.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z47.object({name:z47.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z47.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z47.string().min(1).max(2e3).optional(),judgeEnabled:z47.boolean().optional(),retentionDays:z47.number().int().min(1).max(365).optional(),notification:z47.object({email:z47.object({enabled:z47.boolean().default(!0),recipients:z47.array(z47.string().email()).min(1).max(20),includeDiffs:z47.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=z47.object({monitorId:z47.string().uuid(),name:z47.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z47.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z47.string().min(1).max(2e3).optional(),judgeEnabled:z47.boolean().optional(),retentionDays:z47.number().int().min(1).max(365).optional(),status:z47.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z47.object({monitorId:z47.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z47.string().uuid()}),RunProjectIntegrationToolRequestSchema=z47.object({tool:z47.string().min(1),input:z47.record(z47.string(),z47.unknown()),connectionAlias:z47.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z47.object({provider:z47.string().min(1),providerCredits:z47.number().nonnegative().optional(),providerCostUsd:z47.number().nonnegative().optional(),requests:z47.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z47.object({credits:z47.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z47.object({url:z47.string(),provider:z47.literal("firecrawl"),title:z47.string().optional(),statusCode:z47.number().optional(),markdown:z47.string().optional(),summary:z47.string().optional(),links:z47.array(z47.string()).optional(),images:z47.array(z47.string()).optional(),html:z47.string().optional(),json:z47.unknown().optional(),branding:z47.record(z47.string(),z47.unknown()).optional(),warning:z47.string().optional()}),FirecrawlSearchToolOutputSchema=z47.object({query:z47.string(),provider:z47.literal("firecrawl"),warning:z47.string().optional(),results:z47.array(z47.object({title:z47.string(),url:z47.string(),snippet:z47.string().optional(),content:z47.string().optional(),score:z47.number().optional(),publishedAt:z47.string().optional()}))}),FirecrawlResearchPaperSchema=z47.object({paperId:z47.string(),primaryId:z47.string().optional(),ids:z47.record(z47.string(),z47.array(z47.string())).optional(),title:z47.string().optional(),abstract:z47.string().optional(),score:z47.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z47.object({text:z47.string(),score:z47.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),results:z47.array(z47.object({id:z47.string(),type:z47.string().min(1).optional(),url:z47.string(),title:z47.string().optional(),passages:z47.array(z47.object({text:z47.string()}).passthrough())}).passthrough()),coverage:z47.record(z47.string(),z47.string()).optional(),reranked:z47.boolean().optional(),repos:z47.array(z47.record(z47.string(),z47.unknown())).optional(),sources:z47.array(z47.record(z47.string(),z47.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),results:z47.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),paper:z47.record(z47.string(),z47.unknown()),paperId:z47.string().optional(),query:z47.string().optional(),passages:z47.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),results:z47.array(FirecrawlResearchPaperSchema),poolSize:z47.number().int().nonnegative(),truncated:z47.boolean(),note:z47.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z47.object({url:z47.string(),provider:z47.literal("firecrawl"),count:z47.number(),links:z47.array(z47.object({url:z47.string(),title:z47.string().optional(),description:z47.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z47.object({url:z47.string(),provider:z47.literal("firecrawl"),total:z47.number(),pages:z47.array(z47.object({url:z47.string(),title:z47.string().optional(),statusCode:z47.number().optional(),markdown:z47.string().optional(),summary:z47.string().optional(),links:z47.array(z47.string()).optional(),images:z47.array(z47.string()).optional(),html:z47.string().optional(),warning:z47.string().optional()})),warning:z47.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z47.object({cron:z47.string().optional(),text:z47.string().optional(),timezone:z47.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z47.object({id:z47.string().optional(),type:z47.enum(["scrape","crawl","search"]).optional(),urls:z47.array(z47.string()).optional(),queries:z47.array(z47.string()).optional(),searchWindow:z47.string().optional(),maxResults:z47.number().optional(),includeDomains:z47.array(z47.string()).optional(),excludeDomains:z47.array(z47.string()).optional(),scrapeOptions:z47.record(z47.string(),z47.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z47.object({id:z47.string(),name:z47.string(),status:z47.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z47.string().nullable().optional(),lastRunAt:z47.string().nullable().optional(),currentCheckId:z47.string().nullable().optional(),targets:z47.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z47.string().nullable().optional(),judgeEnabled:z47.boolean().optional(),estimatedCreditsPerMonth:z47.number().optional(),createdAt:z47.string().optional(),updatedAt:z47.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z47.object({id:z47.string(),monitorId:z47.string(),scheduledFor:z47.string().nullable().optional(),startedAt:z47.string().nullable().optional(),finishedAt:z47.string().nullable().optional(),estimatedCredits:z47.number().nullable().optional(),reservedCredits:z47.number().nullable().optional(),actualCredits:z47.number().nullable().optional(),billingStatus:z47.string().nullable().optional(),summary:z47.object({totalPages:z47.number().optional(),same:z47.number().optional(),changed:z47.number().optional(),new:z47.number().optional(),removed:z47.number().optional(),error:z47.number().optional()}).passthrough().optional(),error:z47.string().nullable().optional(),createdAt:z47.string().optional(),updatedAt:z47.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),monitors:z47.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),monitorId:z47.string(),deleted:z47.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),monitorId:z47.string(),checks:z47.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z47.object({provider:z47.literal("firecrawl"),monitorId:z47.string(),check:FirecrawlMonitorCheckOutputSchema,next:z47.string().optional()}),FirecrawlToolKeySchema=z47.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=z47.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z47.object({projectId:z47.uuid(),integrationKey:z47.string().min(1),tool:z47.string().min(1),connectionAlias:z47.string().min(1).nullable().optional(),output:z47.record(z47.string(),z47.unknown()),executedAt:z47.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z47.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z47.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z47.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z47.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z47.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z47.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z47.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z47.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z47.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z47.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z47.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z47.array(ProjectChannelCandidateDTOSchema))}});import{z as z48}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=z48.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z48.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z48.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z48.object({userId:z48.string().min(1),name:z48.string(),email:z48.string().min(1),subscribed:z48.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z48.object({maxSubscribers:z48.number().int().positive(),subscriberCount:z48.number().int().nonnegative(),effectiveRecipientCount:z48.number().int().nonnegative(),currentUserSubscribed:z48.boolean(),candidates:z48.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z48.object({userIds:z48.array(z48.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z48.object({topic:UserManagedNotificationTopicSchema,enabled:z48.boolean(),source:z48.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z48.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z48.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z48.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z48.string().nullable(),maskedEmail:z48.string().min(1),applied:z48.boolean(),expiresAt:z48.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z48.object({scheduleId:z48.string().min(1),scheduleName:z48.string(),projectId:z48.string().min(1),projectName:z48.string(),env:z48.string().min(1)}),FollowedSchedulesSchema=z48.object({schedules:z48.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z49}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=z49.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=z49.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),env:z49.string().min(1),name:z49.string().min(1),cron:z49.string().min(1),command:z49.string().min(1),secretKeys:z49.array(z49.string().min(1)),enabled:z49.boolean(),lastRunAt:z49.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z49.string().nullable(),suspendedAt:z49.coerce.date().nullable().optional(),suspensionReason:z49.string().nullable().optional(),overPolicyReasons:z49.array(z49.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z49.object({name:z49.string().min(1).max(120),cron:z49.string().min(1).max(120),command:z49.string().min(1).max(500),secretKeys:z49.array(ProjectSecretKeySchema).default([]),enabled:z49.boolean().optional()}),UpdateProjectScheduleRequestSchema=z49.object({name:z49.string().min(1).max(120).optional(),cron:z49.string().min(1).max(120).optional(),command:z49.string().min(1).max(500).optional(),secretKeys:z49.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z49.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z49.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z49.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z49.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z49.object({maxRuns:z49.number().int().positive(),retentionDays:z49.number().int().positive().nullable(),outputRetentionDays:z49.number().int().positive(),maxOutputBytes:z49.number().int().positive()}),SchedulePolicyStateSchema=z49.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z49.object({code:z49.enum(["Free","PAYG","Premium","Pro"]),source:z49.enum(["cached_subscription","free_fallback"]),activeSchedules:z49.object({used:z49.number().int().nonnegative(),limit:z49.number().int().nonnegative()}),minCadenceMinutes:z49.number().int().positive(),maxRunMs:z49.number().int().positive(),concurrency:z49.object({used:z49.number().int().nonnegative(),limit:z49.number().int().positive()}),compute:z49.object({settledMs:z49.number().int().nonnegative(),activeMs:z49.number().int().nonnegative(),reservedMs:z49.number().int().nonnegative().optional(),includedMs:z49.number().int().nonnegative(),remainingMs:z49.number().int().nonnegative(),resetsAt:z49.coerce.date()}),upgrade:z49.object({code:z49.literal("Pro"),activeSchedulesLimit:z49.number().int().positive(),minCadenceMinutes:z49.number().int().positive(),maxRunMs:z49.number().int().positive(),maxConcurrentRuns:z49.number().int().positive(),computeIncludedMs:z49.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z49.array(z49.string())}),ProjectScheduleUsageSchema=z49.object({runCount:z49.number().int().nonnegative(),runsWithOutput:z49.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z49.object({id:z49.uuid(),scheduleId:z49.uuid(),projectId:z49.uuid(),env:z49.string().min(1),scheduleName:z49.string().min(1),command:z49.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z49.object({id:z49.string().min(1),name:z49.string().min(1)}).nullable(),queuedAt:z49.coerce.date(),startedAt:z49.coerce.date().nullable(),finishedAt:z49.coerce.date().nullable(),exitCode:z49.number().int().nullable(),errorCode:z49.string().nullable(),error:z49.string().nullable(),outputBytes:z49.number().int().nonnegative(),outputTruncated:z49.boolean(),outputExpiresAt:z49.coerce.date().nullable(),metadataExpiresAt:z49.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z49.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z49.coerce.date().nullable(),items:z49.array(z49.object({key:z49.string().min(1),updatedAt:z49.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z49.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z49.object({trigger:z49.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z49.object({limit:z49.coerce.number().int().min(1).max(100).default(25),cursor:z49.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z49.object({items:z49.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z49.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z49.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z49.object({items:z49.array(ProjectScheduleRunDTOSchema),nextCursor:z49.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z50}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=z50.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z50.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z50.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z50.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z50.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z50.discriminatedUnion("kind",[z50.object({kind:z50.literal("user"),userId:z50.string().min(1)}).strict(),z50.object({kind:z50.literal("agent"),agentKey:z50.string().min(1).max(120),agentId:z50.uuid().optional()}).strict(),z50.object({kind:z50.literal("system")}).strict()]),NotificationSummarySchema=z50.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z50.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z50.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z50.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z50.object({sessionId:z50.uuid(),branch:z50.string().min(1),targetBranch:z50.string().min(1),revision:z50.string().min(1),fingerprint:z50.string().min(1)}),NotificationPayloadSchema=z50.discriminatedUnion("topic",[z50.object({topic:z50.literal("agent_run_outcome"),threadId:z50.uuid(),invocationId:z50.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z50.object({topic:z50.literal("agent_retained_review"),threadId:z50.uuid().optional(),invocationId:z50.uuid().optional(),proposalId:z50.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z50.object({topic:z50.literal("agent_conflict"),mergeId:z50.uuid(),threadId:z50.uuid().optional(),invocationId:z50.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z50.object({topic:z50.literal("publication_failed"),publicationId:z50.uuid(),sourceBranch:z50.string().trim().min(1).max(120),failureCode:z50.string().trim().min(1).max(64),failedAt:z50.iso.datetime(),firstPublication:z50.boolean()}).strict()]),NotificationEnvelopeSchema=z50.object({id:z50.uuid(),projectId:z50.uuid(),sourceKey:z50.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z50.literal(1),payload:NotificationPayloadSchema,createdAt:z50.coerce.date()}),NotificationDeliveryStateSchema=z50.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z50.object({id:z50.uuid(),notificationRecipientId:z50.uuid(),projectId:z50.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z50.number().int().nonnegative(),nextAttemptAt:z50.coerce.date().nullable(),lastAttemptAt:z50.coerce.date().nullable(),sentAt:z50.coerce.date().nullable(),failureCode:z50.string().max(80).nullable(),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),NotificationPreferenceSchema=z50.object({topic:WorkNotificationTopicSchema,channel:z50.literal("email"),enabled:z50.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z50.enum(["default","explicit"])})}});import{z as z51}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=z51.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=z51.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z51.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z51.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z51.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z51.object({enabled:z51.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z51.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z51.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z51.discriminatedUnion("kind",[z51.object({kind:z51.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z51.enum(["work_review","publishing","schedule"]),enabled:z51.boolean(),source:PreferenceSourceSchema}).strict(),z51.object({kind:z51.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z51.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z51.object({kind:z51.literal("provider_subscription"),id:z51.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z51.literal("marketing"),name:z51.string(),description:z51.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z51.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z51.object({email:EmailNotificationPreferenceSchema,entries:z51.array(NotificationPreferenceEntrySchema),unavailableGroups:z51.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z51.object({enabled:z51.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z51.discriminatedUnion("kind",[z51.object({kind:z51.literal("toggle"),enabled:z51.boolean()}).strict(),z51.object({kind:z51.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z51.object({kind:z51.literal("provider_subscription"),enabled:z51.boolean()}).strict()])}});import{z as z52}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=z52.object({surface:SurfaceNameSchema,key:z52.string(),label:z52.string()}),InlineSchema=z52.object({text:z52.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z52.discriminatedUnion("type",[z52.object({type:z52.literal("paragraph"),content:z52.array(InlineSchema).max(24)}),z52.object({type:z52.literal("preview"),ref:DiffRefSchema,caption:z52.string().optional()}),z52.object({type:z52.literal("code"),code:z52.string(),lang:z52.string().optional(),caption:z52.string().optional()}),z52.object({type:z52.literal("risk"),level:z52.enum(["warning","error"]),content:z52.array(InlineSchema).max(24)}),z52.object({type:z52.literal("list"),items:z52.array(z52.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z52.object({headline:z52.string(),blocks:z52.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z52.object({summary:EnvDiffSummarySchema,fingerprint:z52.string(),generatedAt:z52.coerce.date(),cached:z52.boolean().optional(),credits:z52.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z53}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=z53.object({date:z53.string(),visitors:z53.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z53.object({key:z53.string(),visitors:z53.number().int().nonnegative(),pageviews:z53.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z53.object({path:z53.string(),pageName:z53.string().nullable().optional(),visitors:z53.number().int().nonnegative(),pageviews:z53.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z53.object({preset:z53.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z53.string(),requestedTo:z53.string(),effectiveFrom:z53.string(),effectiveTo:z53.string(),isRetentionLimited:z53.boolean(),groupBy:z53.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z53.object({date:z53.string(),content:z53.string(),updatedAt:z53.string(),updatedByUserId:z53.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z53.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z53.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z53.number().int().nonnegative(),pageviews:z53.number().int().nonnegative(),botPageviews:z53.number().int().nonnegative(),botVisitors:z53.number().int().nonnegative(),bounceRate:z53.number().min(0).max(100),viewsPerVisit:z53.number().nonnegative(),averageVisitDurationSeconds:z53.number().nonnegative(),visitorsSeries:z53.array(ProjectDailyVisitorsDTOSchema),topPages:z53.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z53.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z53.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z53.object({state:z53.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z53.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z54}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=z54.object({id:z54.string(),email:z54.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z54.coerce.date(),createdAt:z54.coerce.date(),inviterUserId:z54.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z54.object({id:z54.string(),token:z54.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z54.object({success:z54.boolean(),projectId:z54.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z55}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=z55.object({id:z55.string(),name:z55.string(),image:z55.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z55.object({count:z55.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z55.object({counts:z55.object({signed_up:z55.int(),activated:z55.int()}),credits:z55.object({total:z55.int(),earned:z55.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z55.email(),emailVerified:z55.boolean(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z56}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=z56.object({id:z56.string(),principalType:ProjectPrincipalTypeSchema,principalId:z56.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z56.coerce.date(),expiresAt:z56.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z56.boolean().default(!1)}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","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=z56.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z56.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z56.record(z56.string(),z56.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z56.object({access:z56.array(ProjectAccessItemDTOSchema),invites:z56.array(ProjectInviteDTOSchema),organization:z56.object({name:z56.string().nullable(),logo:z56.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z56.object({success:z56.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),projectId:z56.uuid()}))}});import{z as z57}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=z57.object({publicationStatus:PublicationStatusSchema,appUrl:z57.string().nullable(),lastPublishedAt:z57.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z58}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=z58.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z58.object({branch:BranchSchema,revision:z58.string().min(1).max(64).nullable(),generation:z58.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z58.url().nullable()})}});import{z as z59}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewStartFailureSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewUpgradeRequiredSchema=z59.object({code:z59.literal("PREVIEW_UPGRADE_REQUIRED"),message:z59.string(),currentVersion:z59.number().int().positive(),targetVersion:z59.literal(4)}),PreviewBridgePackageSchema=z59.object({name:z59.string().min(1),version:z59.string().min(1)}),PreviewBridgeCapabilitySchema=z59.object({integrated:z59.boolean(),packages:z59.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z59.object({url:z59.url(),expiresAt:z59.iso.datetime().nullable(),source:z59.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z59.object({name:z59.string().min(1),locator:z59.string().min(1).optional(),source:z59.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z59.object({kind:z59.literal("dependency_build_scripts_blocked"),packageManager:z59.enum(["pnpm","yarn","bun"]),packages:z59.array(z59.string()),targets:z59.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z59.string(),approvalKey:z59.string(),command:z59.string().optional(),approval:z59.object({id:z59.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z59.object({code:z59.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z59.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z59.object({code:z59.literal("PREVIEW_START_FAILED"),message:z59.string(),logTail:z59.array(z59.string()).optional(),logTailTruncated:z59.boolean().optional()}),SandboxPullPhaseSchema=z59.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z59.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z59.object({message:z59.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z59.number().int().optional().catch(void 0),logTail:z59.array(z59.string()).optional().catch(void 0),logTailTruncated:z59.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z59.object({approvalId:z59.uuid()}),PreviewInstallPolicyApprovalEventSchema=z59.discriminatedUnion("type",[z59.object({type:z59.literal("progress"),step:z59.enum(["approval","install","restart","readiness"]),message:z59.string()}),z59.object({type:z59.literal("approved")}),z59.object({type:z59.literal("complete")}),z59.object({type:z59.literal("error"),code:z59.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z59.string()})])}});import{z as z60}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,OrganizationProjectCapacityDTOSchema,OrganizationProjectCapacityDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z60.string(),slug:z60.string().nullable(),logo:z60.string().nullable(),metadata:z60.record(z60.string(),z60.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z60.object({id:z60.string(),name:z60.string(),email:z60.email(),image:z60.string().nullable()}),OrganizationMemberDTOSchema=z60.object({id:z60.string(),userId:z60.string(),organizationId:z60.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z60.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z60.object({canCreateProject:z60.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z61}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=z61.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z61.object({reason:CancellationReasonCodeSchema,details:z61.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z61.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z61.object({offerVersion:z61.string().trim().min(1),unusedPremiumCreditAmount:z61.number().int().nonnegative(),amountDueNow:z61.number().int().nonnegative(),renewsOn:z61.string()}),PlanMigrationPreviewDTOSchema=z61.object({currency:z61.string().trim().min(1),unusedPremiumCreditAmount:z61.number().int().nonnegative(),amountDueNow:z61.number().int().nonnegative(),startsAt:z61.string(),renewsAt:z61.string(),nextRenewalAmount:z61.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z61.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z61.object({id:z61.string(),organizationId:z61.string(),legacySubscriptionId:z61.string(),offeredPlanCode:z61.string(),offeredPlanName:z61.string(),offeredPriceAmount:z61.number(),offeredCurrency:z61.string(),offerVersion:z61.string(),state:PlanMigrationStateSchema,checkoutToken:z61.string().nullable(),deadlineAt:z61.string(),transitions:z61.array(z61.object({event:z61.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z61.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z61.object({included:z61.number().optional(),unitPrice:z61.number().optional(),dailyCap:z61.number().nullable().optional()}),EntitlementsDTOSchema=z61.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z61.object({retentionDays:z61.number().int().positive(),canUseExtendedDateRanges:z61.boolean()}).optional(),history:z61.object({retentionDays:z61.number().int().positive()}).optional(),members:z61.object({canInvite:z61.boolean(),maxMembers:z61.number().int().positive().nullable()}).optional(),projects:z61.object({maxProjects:z61.number().int().positive().nullable()}).optional(),domains:z61.object({canUseCustomDomains:z61.boolean(),maxDomains:z61.number().int().nonnegative().nullable()}).optional(),media_storage:z61.object({limitBytes:z61.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z61.object({usedBytes:z61.number().int().nonnegative().nullable(),limitBytes:z61.number().int().nonnegative().nullable(),state:z61.enum(["ready","unavailable"]),measuredAt:z61.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z61.object({toPlanCode:TemplateCodeSchema,effectiveAt:z61.string(),scheduledAt:z61.string().nullable()}),AutomaticSpendStopDTOSchema=z61.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z61.string(),spendStopped:z61.boolean(),settlementEndsAt:z61.string()}),HostingOverageStatusDTOSchema=z61.object({state:z61.enum(["ready","unavailable"]),planCode:z61.string(),overageAvailable:z61.boolean(),overageEnabled:z61.boolean(),monthlyCapUsd:z61.number().int().positive().nullable(),periodStart:z61.iso.datetime().nullable(),periodEnd:z61.iso.datetime().nullable(),usedBytes:z61.number().nonnegative().nullable(),includedBytes:z61.number().nonnegative().nullable(),overageBytes:z61.number().nonnegative(),currentOverageAmountMicros:z61.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z61.number().nonnegative().nullable(),currency:z61.string().nullable(),status:z61.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z61.object({enabled:z61.boolean(),monthlyCapUsd:z61.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z61.object({id:z61.string(),external_id:z61.string(),customerId:z61.string(),planId:z61.string(),planCode:z61.union([TemplateCodeSchema,z61.literal("Unknown")]),currentPeriod:z61.object({start:z61.string(),end:z61.string().nullable()}),cancelAt:z61.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z61.string(),nextPaymentAt:z61.string().nullable(),baseAmount:z61.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z61.object({totalCap:z61.number(),dailyCap:z61.number(),usedTotal:z61.number()}),CreditBalanceDTOSchema=z61.object({total:z61.number(),base:z61.number(),dailyBase:z61.number(),purchases:z61.number(),awards:z61.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z61.object({total:z61.number(),nearLimit:z61.boolean(),canChat:z61.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z61.object({dailyFreeAvailable:z61.number(),monthlyAvailable:z61.number(),purchasedAvailable:z61.number(),awardedAvailable:z61.number()}),ProjectDailyCreditAllowanceDTOSchema=z61.object({periodCap:z61.number(),dailyGrant:z61.number(),usedThisPeriod:z61.number(),remainingThisPeriod:z61.number()}),ProjectCreditBalanceDTOSchema=z61.object({projectId:z61.uuid(),organizationId:z61.string(),balance:z61.object({totalAvailable:z61.number(),nearLimit:z61.boolean(),canUseAi:z61.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z61.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z61.discriminatedUnion("enabled",[z61.object({enabled:z61.literal(!0),thresholdUsd:z61.number().nonnegative(),refillAmountUsd:z61.number().nonnegative()}),z61.object({enabled:z61.literal(!1),thresholdUsd:z61.number().nonnegative().nullable(),refillAmountUsd:z61.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z61.discriminatedUnion("enabled",[z61.object({enabled:z61.literal(!0),thresholdUsd:z61.number().min(.01).multipleOf(.01),refillAmountUsd:z61.number().min(.01).multipleOf(.01),expectedRateToken:z61.string().trim().min(1).max(40)}).strict(),z61.object({enabled:z61.literal(!1),thresholdUsd:z61.number().min(.01).multipleOf(.01),expectedRateToken:z61.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z61.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z61.object({planCode:z61.union([TemplateCodeSchema,z61.literal("Unknown")]).nullable(),canPurchase:z61.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z61.number().int().positive(),minAmountUsd:z61.number().positive(),maxAmountUsd:z61.number().positive(),rateToken:z61.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z61.object({amountUsd:z61.number(),idempotencyKey:z61.string().trim().min(8).max(120),expectedRateToken:z61.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z61.object({invoiceId:z61.string(),newBalance:z61.int(),creditCount:z61.int(),amountUsd:z61.number(),creditsPerDollar:z61.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z61.object({url:z61.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z61.object({id:z61.string(),number:z61.string().nullable(),status:z61.string(),amountDue:z61.int(),currency:z61.string(),issuedAt:z61.string().nullable(),hostedInvoiceUrl:z61.string().nullable()}),PaymentRecoveryDTOSchema=z61.discriminatedUnion("status",[z61.object({status:z61.literal("eligible"),checkedAt:z61.string()}),z61.object({status:z61.literal("recovery_required"),checkedAt:z61.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z61.int().min(1)}),z61.object({status:z61.literal("unavailable"),checkedAt:z61.string(),reason:z61.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 z62}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=z62.object({brand:z62.string(),last4:z62.string(),exp:z62.string(),isDefault:z62.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z63}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=z63.string().superRefine((path50,ctx)=>{let segments=path50.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=z63.object({type:z63.literal("renameField"),contentType:z63.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z63.object({enabled:z63.boolean()}).strict(),ContentFieldGroupSchema=z63.object({id:z63.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z63.string().min(1).max(255),default:z63.boolean().optional()}).strict(),ContentTypeDTOSchema=z63.object({id:z63.string(),name:z63.string(),label:z63.string(),isSingleton:z63.boolean(),i18n:ContentTypeI18nSchema,groups:z63.array(ContentFieldGroupSchema).default([]),fields:z63.record(z63.string(),FieldDefinitionSchema),createdAt:z63.string(),updatedAt:z63.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z63.object({contentTypes:z63.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z63.object({id:z63.string(),entryId:z63.string(),documentId:z63.string(),slug:z63.string(),locale:z63.string().optional(),createdAt:z63.string(),updatedAt:z63.string(),__fimo:z63.object({contentType:z63.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z63.object({data:z63.array(EntryDTOSchema),meta:z63.object({limit:z63.number(),offset:z63.number(),total:z63.number(),hasMore:z63.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z63.object({contentType:z63.string(),count:z63.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z63.object({counts:z63.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z63.object({count:z63.number().int().nonnegative(),sourceLocale:z63.string(),targetLocale:z63.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z63.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z63.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z63.union([z63.string(),z63.number(),z63.boolean(),z63.null()]),entryWhereOperatorSchema=z63.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z63.array(entryWhereScalarSchema).optional(),$nin:z63.array(entryWhereScalarSchema).optional(),$contains:z63.string().optional(),$startsWith:z63.string().optional(),$null:z63.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z63.record(z63.string(),z63.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z63.record(z63.string(),z63.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z63.object({data:z63.record(z63.string(),z63.unknown()),locale:z63.string().min(1).optional(),documentId:z63.uuid().optional()}),entryIdsSchema=z63.array(z63.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z63.object({sql:z63.string().min(1)}),BulkCreateEntriesRequestSchema=z63.object({entries:z63.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z63.union([z63.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z63.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z63.object({updates:z63.array(z63.object({id:z63.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z63.union([z63.object({ids:entryIdsSchema,locale:z63.string().min(1).optional()}),z63.object({where:EntryWhereSchema,locale:z63.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z63.object({data:z63.array(z63.record(z63.string(),z63.unknown())),meta:z63.object({rowCount:z63.number().int().nonnegative(),truncated:z63.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z63.object({data:z63.array(EntryDTOSchema),meta:z63.object({created:z63.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z63.object({data:z63.array(EntryDTOSchema),meta:z63.object({updated:z63.number().int().nonnegative(),missing:z63.array(z63.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z63.object({data:z63.array(EntryDTOSchema),meta:z63.object({deleted:z63.number().int().nonnegative(),missing:z63.array(z63.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z64}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z64.object({index:z64.number().int().nonnegative(),contentType:z64.string(),field:z64.string(),value:z64.string(),against:z64.enum(["stored","batch"]),ownerDocumentId:z64.uuid().optional(),ownerIndex:z64.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z64.object({code:z64.literal("unique_conflict"),message:z64.string(),conflicts:z64.array(UniqueConflictSchema),truncated:z64.boolean().optional()})}});import{z as z65}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=z65.object({kind:z65.literal("unique_conflict"),contentType:z65.string(),field:z65.string(),value:z65.string(),documentCount:z65.number().int().positive(),documentIds:z65.array(z65.uuid()),documentIdsTruncated:z65.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z65.object({code:z65.literal("schema_transition_rejected"),message:z65.string(),issues:z65.array(SchemaTransitionIssueSchema),truncated:z65.boolean().optional()})}});import{z as z66}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=z66.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z66.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z66.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z66.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z66.object({field:CmsFieldNameSchema,direction:z66.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z66.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z66.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z66.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z66.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z66.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z67}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=z67.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z68}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=z68.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z68.object({event:ClientTrackedEventSchema,properties:z68.record(z68.string(),z68.unknown()).default({})})}});import{z as z69}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=z69.object({id:z69.string(),name:z69.string()}),AssetDTOSchema=z69.object({id:z69.string(),name:z69.string(),type:AssetTypeSchema,originalFileName:z69.string().nullable(),parentId:z69.string().nullable(),mimeType:z69.string().nullable(),fileSize:z69.number().nullable(),url:z69.string().nullable(),storageKey:z69.string().nullable(),createdAt:z69.string(),updatedAt:z69.string(),altText:z69.string().nullable().optional(),caption:z69.string().nullable().optional(),aiCaption:z69.string().nullable().optional(),aiAltText:z69.string().nullable().optional(),aiTags:z69.array(z69.string()).nullable().optional(),aiPrimaryColor:z69.string().nullable().optional(),aiProcessingStatus:z69.string().nullable().optional(),width:z69.number().nullable().optional(),height:z69.number().nullable().optional(),path:z69.array(AssetPathItemSchema).optional(),hasChildren:z69.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z69.lazy(()=>z69.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z69.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z69.object({error:z69.string(),code:z69.literal("media_storage_limit_exceeded"),usedBytes:z69.number().int().nonnegative(),limitBytes:z69.number().int().positive(),incomingBytes:z69.number().int().nonnegative()}),AssetReferenceScopeSchema=z69.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z69.object({assetIds:z69.array(z69.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z69.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z69.object({totalFiles:z69.number().int().nonnegative(),checkedFiles:z69.number().int().nonnegative(),limit:z69.number().int().positive()}),AssetReferenceFindingDTOSchema=z69.object({assetId:z69.uuid(),entryId:z69.string(),documentId:z69.string(),contentType:z69.string(),locale:z69.string().nullable(),slug:z69.string(),fieldPath:z69.string()}),AssetReferenceScopeResultDTOSchema=z69.object({scope:AssetReferenceScopeSchema,label:z69.string(),state:z69.enum(["available","not-published","failed"]),coverage:z69.enum(["complete","partial","failed"]),referenceCount:z69.number().int().nonnegative().optional(),codeReferenceCount:z69.number().int().nonnegative().optional(),referencedAssetIds:z69.array(z69.uuid()).optional(),references:z69.array(AssetReferenceFindingDTOSchema),reason:z69.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z69.discriminatedUnion("type",[z69.object({type:z69.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z69.object({type:z69.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z69.object({type:z69.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z69.object({replacementAssetId:z69.uuid()}),AssetReferenceReplacementResultSchema=z69.object({referencesReplaced:z69.number().int().nonnegative(),entriesChanged:z69.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z69.object({referencesReplaced:z69.number().int().nonnegative(),filesChanged:z69.number().int().nonnegative(),commitSha:z69.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z69.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=z69.object({error:z69.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z69.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=z69.object({intent:AssetRemovalIntentSchema,assetIds:z69.array(z69.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z69.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=z69.object({id:z69.uuid(),intent:AssetRemovalIntentSchema,assetIds:z69.array(z69.uuid()),replacementAssetId:z69.uuid().nullable(),expiresAt:z69.iso.datetime(),undoable:z69.boolean(),requestedByMe:z69.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z69.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z69.object({error:z69.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z70}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z70.object({key:z70.string(),value:z70.string().optional(),defaultValue:z70.string(),locale:z70.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z71}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=z71.object({id:z71.string(),name:z71.string(),type:z71.enum(["file","folder"]),path:z71.string(),children:z71.lazy(()=>z71.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z71.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z71.object({path:z71.string(),exists:z71.boolean(),type:z71.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z72}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=z72.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z72.object({minLength:z72.number().optional(),maxLength:z72.number().optional(),min:z72.number().optional(),max:z72.number().optional(),pattern:z72.string().optional(),maxFileSize:z72.number().optional(),accept:z72.array(z72.string()).optional()}),FormFieldSchema=z72.object({type:FormFieldTypeSchema,label:z72.string(),placeholder:z72.string().optional(),required:z72.boolean().optional(),defaultValue:z72.string().optional(),options:z72.array(z72.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z72.record(z72.string(),FormFieldSchema),FormContentSchema=z72.object({name:z72.string().min(1).max(255),label:z72.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 z73}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=z73.object({url:z73.string().url(),key:z73.string(),size:z73.number(),contentType:z73.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z74}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=z74.object({canAccess:z74.boolean(),permissions:z74.record(z74.string(),z74.boolean()),role:z74.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z75}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:z75.string().trim().default(""),sort:z75.enum(["recent","name","relevance"]).default("recent"),category:z75.string().optional()})}});import{z as z76}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=z76.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z76.enum(["fimo","external"]),PaymentStatusSchema=z76.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z76.object({id:z76.string().uuid(),domain:z76.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z76.boolean(),price:z76.number().int().nullable(),renewalPrice:z76.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z76.string().nullable(),failureReason:z76.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z76.object({domain:z76.string(),available:z76.boolean(),premium:z76.boolean(),price:z76.number().nullable(),renewalPrice:z76.number().nullable(),purchaseType:z76.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z76.object({domain:z76.string(),price:z76.number().nullable(),renewalPrice:z76.number().nullable(),premium:z76.boolean(),allowedYears:z76.array(z76.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z76.object({firstName:z76.string().max(100),lastName:z76.string().max(100),companyName:z76.string().max(100).optional(),address1:z76.string().max(255),address2:z76.string().max(255).optional(),city:z76.string().max(100),state:z76.string().max(100),zip:z76.string().max(20),country:z76.string().max(2),phone:z76.string().max(30),email:z76.union([z76.string().email().max(255),z76.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z76.object({firstName:z76.string().min(1).max(100),lastName:z76.string().min(1).max(100),companyName:z76.string().max(100).optional(),address1:z76.string().min(1).max(255),address2:z76.string().max(255).optional(),city:z76.string().min(1).max(100),state:z76.string().min(1).max(100),zip:z76.string().min(1).max(20),country:z76.string().min(1).max(2),phone:z76.string().min(1).max(30),email:z76.string().email().max(255)}),SearchDomainsRequestSchema=z76.object({keyword:z76.string().min(1).max(100),tldFilter:z76.array(z76.string()).optional()}),CheckAvailabilityRequestSchema=z76.object({domains:z76.array(z76.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=z76.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z76.object({domain:DomainNameSchema,years:z76.number().int().min(1).max(10).optional().default(3),autoRenew:z76.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z76.object({autoRenew:z76.boolean().optional()}),RenewDomainRequestSchema=z76.object({years:z76.number().int().min(1).max(10).optional().default(1),autoRenew:z76.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z76.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z76.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z76.object({verified:z76.boolean(),email:z76.string().nullable(),verifyBy:z76.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z77}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=z77.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=z77.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=z77.object({txtName:z77.string().nullable().optional(),txtValue:z77.string().nullable().optional(),httpUrl:z77.string().nullable().optional(),httpBody:z77.string().nullable().optional(),cname:z77.string().nullable().optional(),cnameTarget:z77.string().nullable().optional()}),SSLValidationErrorSchema=z77.object({message:z77.string()}),OwnershipVerificationSchema=z77.object({type:z77.string(),name:z77.string(),value:z77.string()}),ProjectDomainSSLDTOSchema=z77.object({status:z77.string(),method:z77.string().nullable(),type:z77.string().nullable(),validationRecords:z77.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z77.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z77.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z77.enum(["subdomain","apex"]),RedirectConfigSchema=z77.object({type:z77.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z77.string()}).nullable().optional(),ProjectDomainDTOSchema=z77.object({id:z77.string(),hostname:z77.string(),status:z77.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z77.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z77.string(),scdCnameTarget:z77.string().optional(),apexTargets:z77.array(z77.string()),dnsAutoConfigured:z77.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z77.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z77.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z77.object({hostname:z77.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:z77.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z77.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z77.object({available:z77.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z77.object({success:z77.boolean(),hostname:z77.string()}))}});import{z as z78}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=z78.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z78.object({available:z78.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z78.object({slug:z78.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z78.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z78.object({subdomain:z78.string(),subdomainUpdatedAt:z78.coerce.date()})),SubdomainSuggestionsQuerySchema=z78.object({base:z78.string().max(100).optional(),max:z78.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z78.object({suggestions:z78.array(z78.string())}))}});import{z as z79}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=z79.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z79.object({code:ProjectTransferBlockerCodeSchema,message:z79.string(),count:z79.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z79.object({targetOrganizationId:z79.string().min(1)}),ProjectTransferResultDTO=createDTO(z79.object({projectId:z79.string(),sourceOrganizationId:z79.string(),targetOrganizationId:z79.string(),movedThreads:z79.number().int().nonnegative(),revokedInvites:z79.number().int().nonnegative(),revokedGrants:z79.number().int().nonnegative(),preservedGrants:z79.number().int().nonnegative(),warnings:z79.array(z79.string())}))}});import{z as z80}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=z80.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z80.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=z80.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z80.object({displayName:z80.string().trim().min(1).max(80),machineId:z80.string().trim().min(1).max(128).optional(),cliVersion:z80.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z80.object({ttlHours:z80.number().int().positive(),lockedFeatures:z80.array(UnclaimedLockedFeatureSchema),media:z80.object({totalBytes:z80.number().int().nonnegative(),fileBytes:z80.number().int().positive(),maxFiles:z80.number().int().nonnegative(),mimeTypes:z80.array(z80.string())}),database:z80.object({storageBytes:z80.number().int().positive(),computeSeconds:z80.number().int().positive(),maxComputeUnits:z80.number().positive()})}),UnclaimedProjectClaimSchema=z80.object({url:z80.string().url(),expiresAt:z80.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z80.object({project:ProjectDTOSchema,token:z80.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z80.object({state:UnclaimedClaimStateSchema,displayName:z80.string().nullable(),expiresAt:z80.coerce.date().nullable(),projectId:z80.string().nullable()})),UnclaimedClaimSecretSchema=z80.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z80.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z80.object({secrets:z80.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z80.object({claims:z80.array(z80.object({state:UnclaimedClaimStateSchema,expiresAt:z80.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z80.object({secret:UnclaimedClaimSecretSchema,organizationId:z80.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z80.object({projectId:z80.string(),organizationId:z80.string()})),ProjectTokenSelfDTO=createDTO(z80.object({kind:z80.literal("project_token"),projectId:z80.string(),projectName:z80.string(),displayName:z80.string().nullable(),organizationId:z80.string().nullable(),organizationName:z80.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z80.coerce.date().nullable(),tokenExpiresAt:z80.coerce.date().nullable()}))}});import{z as z81}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=z81.object({translated:z81.number().int().nonnegative(),total:z81.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z81.object({locale:z81.string(),isDefault:z81.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z81.object({defaultLocale:z81.string(),locales:z81.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z81.object({locale:z81.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z81.object({locale:z81.string().min(1).max(40)}),ProjectLocaleMutationSchema=z81.object({locale:z81.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z81.object({locale:z81.string(),entriesDeleted:z81.number().int().nonnegative(),labelsDeleted:z81.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z82}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=z82.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z82.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=z82.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z82.number(),credits:z82.number().optional(),billingMode:z82.enum(["fimo-credits","provider-account"]).optional(),confidence:z82.enum(["exact","estimated","metered"]),basis:z82.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z83}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=z83.object({options:z83.record(z83.string(),z83.unknown()),name:z83.string().optional(),parentId:z83.string().nullable().optional(),altText:z83.string().optional(),caption:z83.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z83.string().min(1).optional(),model:z83.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=z83.object({jobId:z83.string(),status:z83.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z83.string().nullable().optional(),credits:z83.number().optional(),costUsd:z83.number().optional(),billingMode:z83.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z83.object({error:z83.string(),code:z83.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:z83.array(GenerationTaskIdSchema).optional(),availableModels:z83.array(z83.string()).optional(),issues:z83.array(z83.unknown()).optional()})}});import{z as z84}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=z84.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z84.object({name:z84.string(),key:z84.string(),description:z84.string(),type:FlagTypeSchema,required:z84.boolean(),defaultValue:z84.unknown().optional(),enumValues:z84.array(z84.string()).optional(),isArray:z84.boolean()}),AssetModelPriceSchema=z84.object({unitPrice:z84.number(),unit:z84.string(),confidence:z84.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z84.object({id:z84.string(),shortName:z84.string(),provider:z84.string(),source:z84.string(),modality:z84.enum(["image","video","audio"]),tags:z84.array(z84.string()),displayName:z84.string(),description:z84.string(),flags:z84.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z84.object({model:z84.string(),costUsd:z84.number(),credits:z84.number(),billingMode:z84.enum(["fimo-credits","provider-account"]),confidence:z84.enum(["exact","estimated","metered"]),basis:z84.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z85}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=z85.object({tourId:z85.string(),version:z85.string(),status:z85.string(),completedAt:z85.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z85.array(UserTourDTOSchema))}});import{z as z86}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=z86.iso.datetime({offset:!0}).pipe(z86.coerce.date()),OpsRecentChatInputSchema=z86.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z86.string().trim().min(1).max(255).optional(),limit:z86.coerce.number().int().min(1).max(200).default(100),cursor:z86.string().trim().min(1).max(2e3).optional(),slim:z86.boolean().default(!0),reason:z86.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=z86.object({id:z86.string(),threadId:z86.string(),providerMessageId:z86.string().nullable(),invocationId:z86.string().nullable(),env:z86.string().nullable(),role:z86.string(),parts:z86.array(z86.record(z86.string(),z86.unknown())),metadata:z86.object({status:z86.string().optional(),traceUrl:z86.string().optional(),externalFileChanges:z86.array(z86.unknown()).optional()}),stats:z86.object({toolCount:z86.number().int().nonnegative(),failedToolCount:z86.number().int().nonnegative()}),createdAt:z86.iso.datetime({offset:!0}),project:z86.object({id:z86.string(),name:z86.string(),displayName:z86.string().nullable(),organizationId:z86.string().nullable()})}),OpsRecentChatResponseSchema=z86.object({target:z86.object({backendProfile:OpsBackendProfileSchema,projectEnv:z86.string().nullable()}),window:z86.object({from:z86.iso.datetime({offset:!0}),to:z86.iso.datetime({offset:!0})}),messages:z86.object({items:z86.array(OpsRecentChatMessageSchema),nextCursor:z86.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z87}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=z87.object({backendProfile:OpsBackendProfileSchema,provider:z87.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z87.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z87.object({backendProfile:OpsBackendProfileSchema,provider:z87.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z87.literal(!1),reason:z87.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z88}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=z88.object({packageManager:z88.string().trim().min(1).max(200).nullable(),trackedLockfiles:z88.array(z88.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z88.string().trim().min(1)}),OpsProjectPackageManagerSchema=z88.object({target:z88.object({backendProfile:OpsBackendProfileSchema,projectId:z88.uuid(),projectEnv:z88.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z89}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:z89.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z89.union([z89.object({name:z89.string().trim().min(1).max(120),description:z89.string().trim().min(1).max(2e3)}).strict(),z89.object({template:z89.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z89.object({agent:OpsAgentChatAgentSpecSchema,routines:z89.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:z89.string().trim().min(1).max(1e3),dryRun:z89.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z89.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z89.object({id:z89.string().uuid().nullable(),name:z89.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z89.string().nullable(),paused:z89.boolean(),outcome:z89.enum(["created","would_create"]),source:z89.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z89.object({target:z89.object({backendProfile:OpsBackendProfileSchema,projectId:z89.string().uuid()}),dryRun:z89.boolean(),applied:z89.boolean(),createdBy:z89.object({userId:z89.string()}),agent:z89.object({id:z89.string().uuid().nullable(),title:z89.string(),template:z89.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z89.array(OpsAgentChatRoutineResultSchema),skipped:z89.array(z89.object({name:z89.string(),reason:z89.literal("routine_exists")})),refused:z89.array(z89.object({name:z89.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z90}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=z90.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z90.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z90.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z90.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z90.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z90.object({reason:WebhookEntryChangeReasonSchema,operationId:z90.string().optional(),batch:z90.object({index:z90.number().int().positive(),total:z90.number().int().positive()}).optional(),changes:z90.array(z90.object({action:WebhookEntryChangeActionSchema,contentType:z90.string(),id:z90.string(),documentId:z90.string(),locale:z90.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z90.object({form:z90.object({id:z90.string(),label:z90.string()}),submission:z90.object({id:z90.string(),data:z90.record(z90.string(),z90.unknown()),submittedAt:z90.string()})}),PublishStartedWebhookEventDataSchema=z90.object({publication:z90.object({status:z90.literal("publishing"),startedAt:z90.string()})}),PublishSucceededWebhookEventDataSchema=z90.object({publication:z90.object({status:z90.literal("published"),url:z90.string(),publishedAt:z90.string(),firstPublish:z90.boolean()})}),PublishFailedWebhookEventDataSchema=z90.object({publication:z90.object({status:z90.literal("failed"),reason:z90.string()})}),PublishUnpublishedWebhookEventDataSchema=z90.object({publication:z90.object({previousUrl:z90.string(),unpublishedAt:z90.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z90.object({report:z90.object({weekStart:z90.string(),weekEnd:z90.string(),pageviews:z90.number(),visitors:z90.number(),previousPageviews:z90.number(),previousVisitors:z90.number()})}),MediaAssetWebhookEventDataSchema=z90.object({id:z90.string().nullable(),name:z90.string().nullable(),type:z90.string(),mimeType:z90.string().nullable(),fileSize:z90.number().nullable()}),MediaUploadedWebhookEventDataSchema=z90.object({asset:MediaAssetWebhookEventDataSchema,operation:z90.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z90.object({asset:MediaAssetWebhookEventDataSchema,operation:z90.literal("updated")}),MediaDeletedWebhookEventDataSchema=z90.object({asset:MediaAssetWebhookEventDataSchema,operation:z90.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z90.object({domain:z90.object({id:z90.string(),hostname:z90.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z90.object({domain:z90.object({id:z90.string(),hostname:z90.string()})}),LabelChangedWebhookEventDataSchema=z90.object({changes:z90.array(z90.object({action:z90.enum(["created","updated","deleted"]),key:z90.string(),locale:z90.string(),value:z90.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z90.object({locale:z90.object({code:z90.string(),isDefault:z90.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z90.object({locale:z90.object({code:z90.string(),previousCode:z90.string()})}),LocaleDeletedWebhookEventDataSchema=z90.object({locale:z90.object({code:z90.string(),entriesDeleted:z90.number().int().nonnegative(),labelsDeleted:z90.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z90.object({environment:z90.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z90.object({environment:z90.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z90.object({merge:z90.object({id:z90.string(),from:BranchSchema,to:BranchSchema,applied:z90.array(z90.object({surface:SurfaceNameSchema,count:z90.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z90.object({branch:z90.object({name:BranchSchema}),version:z90.object({versionId:z90.uuid(),name:z90.string()})}),WebhookEventFamilySchema=z90.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z90.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z90.discriminatedUnion("source",[z90.object({source:z90.literal("literal"),value:z90.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z90.object({source:z90.literal("secret"),key:z90.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z90.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z90.object({name:z90.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z90.object({name:z90.string(),source:z90.enum(["literal","secret"]),secretKey:z90.string().nullable(),secretPrefix:z90.string().nullable(),configured:z90.literal(!0)}),WebhookFilterSchema=z90.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z90.string().min(1).max(255).optional(),mediaType:z90.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z90.string().min(1).max(255).optional(),locale:z90.string().min(1).max(120).optional()}),JsonValueSchema=z90.lazy(()=>z90.union([z90.string(),z90.number(),z90.boolean(),z90.null(),z90.array(JsonValueSchema),z90.record(z90.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z90.object({name:z90.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z90.url(),enabled:z90.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z90.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z90.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z90.object({name:z90.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z90.url().optional(),enabled:z90.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z90.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z90.boolean().optional()}),TestProjectWebhookRequestSchema=z90.object({eventType:WebhookEventTypeSchema.optional(),data:z90.record(z90.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z90.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z90.uuid(),name:z90.string(),eventType:WebhookEventTypeSchema,enabled:z90.boolean(),destination:z90.object({host:z90.string(),maskedUrl:z90.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z90.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z90.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z90.coerce.date().nullable(),deliveryStats24h:z90.object({succeeded:z90.number().int().nonnegative(),failed:z90.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z90.uuid(),projectId:z90.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z90.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z90.number().int().positive(),test:z90.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z90.number().int().nonnegative(),responseStatus:z90.number().int().nullable(),lastErrorCode:z90.string().nullable(),lastErrorMessage:z90.string().nullable(),payloadAvailable:z90.boolean(),destination:z90.object({host:z90.string(),maskedUrl:z90.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z90.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z90.string().nullable(),qstashMessageId:z90.string().nullable(),deliveredAt:z90.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z90.object({items:z90.array(WebhookDeliveryDTOSchema),pagination:z90.object({page:z90.number().int().positive(),limit:z90.number().int().positive(),total:z90.number().int().nonnegative(),totalPages:z90.number().int().positive(),hasMore:z90.boolean()}),stats:z90.object({total:z90.number().int().nonnegative(),succeeded:z90.number().int().nonnegative(),failed:z90.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z90.object({id:z90.uuid(),deliveryId:z90.uuid(),attempt:z90.number().int().positive(),status:z90.enum(["delivering","succeeded","failed"]),responseStatus:z90.number().int().nullable(),durationMs:z90.number().int().nonnegative(),responseExcerpt:z90.string().nullable(),errorCode:z90.string().nullable(),errorMessage:z90.string().nullable(),createdAt:z90.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z90.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z90.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z91}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=z91.object({key:z91.literal("fimo-2"),enabled:z91.boolean(),dismissed:z91.boolean().default(!1),interacted:z91.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z92}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=z92.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z92.enum(["running","done","failed"]),SiteCloneStatusSchema=z92.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z92.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z92.object({code:SiteRefusalCodeSchema,suggestedUrl:z92.string().nullable()}),SiteCheckGroupSchema=z92.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z92.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=z92.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z92.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z92.record(z92.string(),z92.union([z92.string(),z92.number(),z92.boolean(),z92.array(z92.string())])),SiteCheckResultSchema=z92.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z92.object({id:SiteCheckGroupSchema,score:z92.number().int().min(0).max(100).nullable()}),SiteReportSchema=z92.object({siteUrl:z92.string(),scannedAt:z92.coerce.date(),seoScore:z92.number().int().min(0).max(100).nullable(),geoScore:z92.number().int().min(0).max(100).nullable(),groups:z92.array(SiteReportGroupSchema),checks:z92.array(SiteCheckResultSchema),blockers:z92.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z92.enum(["budget","standard","premium","luxury"]),SiteTypeSchema=z92.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z92.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=z92.object({name:z92.string(),summary:z92.string(),audience:z92.string(),positioning:z92.string(),priceTier:SitePriceTierSchema,homepage:z92.string()}),SiteSuggestionSchema=z92.object({label:z92.string(),url:z92.string().nullable()}),SiteInterviewSuggestionsSchema=z92.record(z92.string(),z92.record(z92.string(),z92.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z92.record(z92.string().max(50),z92.union([z92.string().trim().max(2e3),z92.array(z92.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z92.object({status:z92.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z92.record(z92.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z92.object({questionId:z92.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z92.object({fixes:z92.array(z92.object({checkId:SiteCheckIdSchema,status:z92.enum(["fixed","not_fixed","not_applicable"]),note:z92.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z92.object({fixes:SiteFixesReportSchema.nullable(),summary:z92.string().nullable()}),StartSiteOnboardingRequestSchema=z92.object({organizationId:z92.string().min(1),url:z92.string().trim().min(1).max(2048),locale:z92.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z92.object({projectId:z92.string()})),SiteOnboardingRefusedResponseSchema=z92.object({error:z92.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z92.object({projectId:z92.string(),siteUrl:z92.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z92.boolean(),budgetExhausted:z92.boolean(),sponsored:z92.boolean(),cloneOutOfCredits:z92.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z92.string().nullable(),welcomeThreadId:z92.string().nullable(),competitors:z92.array(z92.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z92.coerce.date(),openedAt:z92.coerce.date().nullable(),bannerDismissed:z92.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z92.object({task:z92.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z92.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z92.object({search:z92.string().trim().max(200).optional(),organizationId:z92.string().trim().min(1).max(200).optional(),startDate:z92.coerce.date().optional(),endDate:z92.coerce.date().optional(),outcomes:z92.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z92.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z92.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z92.array(SiteTypeSchema).optional()),page:z92.coerce.number().int().min(1).default(1),pageSize:z92.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z92.object({projectId:z92.string(),projectName:z92.string(),organizationId:z92.string(),organizationName:z92.string().nullable(),ownerEmail:z92.string().nullable(),ownerName:z92.string().nullable(),siteUrl:z92.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z92.boolean(),cloneRetries:z92.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z92.number(),interviewQuestions:z92.number().nullable(),seoScore:z92.number().nullable(),geoScore:z92.number().nullable(),spentUsd:z92.number(),budgetCapUsd:z92.number(),capReached:z92.boolean(),cloneSeconds:z92.number().nullable(),createdAt:z92.coerce.date(),openedAt:z92.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z92.object({onboardings:z92.array(AdminSiteOnboardingDTOSchema),page:z92.number(),limit:z92.number(),total:z92.number(),totalPages:z92.number()})),AdminSiteOnboardingStatsSchema=z92.object({total:z92.number(),outcomes:z92.record(SiteOnboardingOutcomeSchema,z92.number()),funnel:z92.object({started:z92.number(),confirmed:z92.number(),finished:z92.number(),opened:z92.number()}),bySiteType:z92.array(z92.object({siteType:SiteTypeSchema,total:z92.number(),finished:z92.number(),opened:z92.number()})),granularity:z92.enum(["hour","day"]),series:z92.array(z92.object({at:z92.coerce.date(),outcomes:z92.record(SiteOnboardingOutcomeSchema,z92.number())})),spentUsd:z92.object({total:z92.number(),average:z92.number().nullable()}),sponsored:z92.number(),paidByOrganization:z92.object({usd:z92.number(),credits:z92.number()}),capReached:z92.number(),cloneSeconds:z92.object({median:z92.number().nullable(),average:z92.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z92.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z92.string(),cloneThreadId:z92.string().nullable(),paidByOrganizationUsd:z92.number()}),interview:SiteInterviewSchema.extend({invocationIds:z92.array(z92.string())}).nullable(),knowledgeWritten:z92.string().nullable(),knowledgeNow:z92.object({content:z92.string(),updatedAt:z92.coerce.date().nullable(),updatedBy:z92.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z93}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=z93.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z93.object({total:z93.number(),base:z93.number(),purchases:z93.number(),awards:z93.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z93.object({id:z93.string(),name:z93.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z93.object({type:z93.string(),brand:z93.string().nullable(),last4:z93.string().nullable(),expirationDate:z93.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z93.object({currency:z93.string(),nextPaymentAmount:z93.number().nullable(),nextPaymentAt:z93.string().nullable(),billingInterval:z93.string().nullable(),totalAmount:z93.number().nullable(),discountAmount:z93.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z93.object({id:z93.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z93.string().nullable(),currentPeriodEndsAt:z93.string().nullable(),renewsAt:z93.string().nullable(),cancelAt:z93.string().nullable(),renewAutomatically:z93.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z93.object({type:z93.enum(["low_balance","critical_balance","approaching_limit"]),message:z93.string(),estimatedPromptsRemaining:z93.number().nullable(),avgCostPerPrompt:z93.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z93.object({monthlyCredits:z93.number().nullable(),usedThisPeriod:z93.number(),remainingThisPeriod:z93.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z93.object({organizationId:z93.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z93.string().nullable(),tenureDays:z93.number().int().nonnegative(),capturedAt:z93.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z93.object({hasSubscription:z93.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z93.number().nullable(),alerts:z93.array(CreditAlertDTOSchema),portalUrl:z93.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z93.object({creditCount:z93.number().int().positive(),expiresAt:z93.string().datetime().nullable().optional(),message:z93.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z93.literal("free"),amountCents:z93.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z93.literal("purchase"),amountCents:z93.number().int().positive()}),CreditTopupRequestDTOSchema=z93.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z93.object({success:z93.boolean(),transactionId:z93.string().nullable(),newBalance:z93.number(),creditCount:z93.number(),type:z93.enum(["free","purchase"]),invoiceId:z93.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z94}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=z94.object({totalCredits:z94.number(),totalCostUsd:z94.number(),totalMessages:z94.number(),avgCostPerMessage:z94.number(),periodStart:z94.string().nullable(),periodEnd:z94.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z94.object({projectId:z94.string(),projectName:z94.string(),projectDisplayName:z94.string().nullable(),credits:z94.number(),costUsd:z94.number(),messages:z94.number(),percentage:z94.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z94.object({userId:z94.string(),userName:z94.string().nullable(),userEmail:z94.string().email().nullable(),credits:z94.number(),costUsd:z94.number(),messages:z94.number(),percentage:z94.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z94.object({date:z94.string(),credits:z94.number(),costUsd:z94.number(),messages:z94.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z94.object({userId:z94.string(),userName:z94.string().nullable(),userEmail:z94.string().email().nullable(),credits:z94.number(),costUsd:z94.number(),messages:z94.number(),percentage:z94.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z94.object({projectId:z94.string(),projectName:z94.string(),projectDisplayName:z94.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z94.array(UsageByUserForProjectDTOSchema),timeline:z94.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z94.object({summary:UsageSummaryDTOSchema,byProject:z94.array(UsageByProjectDTOSchema),byUser:z94.array(UsageByUserDTOSchema),timeline:z94.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z95}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=z95.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z95.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z95.object({startDate:z95.string().optional(),endDate:z95.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z95.coerce.number().int().positive().default(1),limit:z95.coerce.number().int().positive().max(100).default(20),sortBy:z95.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z95.string().optional(),activeOnly:z95.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z95.object({totalCredits:z95.number(),totalCostUsd:z95.number(),totalMessages:z95.number(),automatedMessages:z95.number(),avgCostPerMessage:z95.number(),avgCreditsPerMessage:z95.number(),periodStart:z95.string(),periodEnd:z95.string(),creditsChange:z95.number().nullable(),costChange:z95.number().nullable(),messagesChange:z95.number().nullable(),unattributedCredits:z95.number(),unattributedCostUsd:z95.number(),unattributedMessages:z95.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z95.object({date:z95.string(),credits:z95.number(),costUsd:z95.number(),messages:z95.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z95.object({organizationId:z95.string(),organizationName:z95.string(),credits:z95.number(),costUsd:z95.number(),messages:z95.number(),percentage:z95.number(),userCount:z95.number(),projectCount:z95.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z95.object({userId:z95.string(),userName:z95.string().nullable(),userEmail:z95.string().nullable(),userImage:z95.string().nullable(),organizationId:z95.string().nullable(),organizationName:z95.string().nullable(),credits:z95.number(),costUsd:z95.number(),messages:z95.number(),percentage:z95.number(),projectCount:z95.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z95.object({projectId:z95.string(),projectName:z95.string(),projectDisplayName:z95.string().nullable(),organizationId:z95.string(),organizationName:z95.string(),credits:z95.number(),costUsd:z95.number(),messages:z95.number(),percentage:z95.number(),userCount:z95.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z95.object({id:z95.string(),name:z95.string(),value:z95.number(),percentage:z95.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z95.object({day:z95.number(),hour:z95.number(),value:z95.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z95.object({summary:UsageOverviewSummaryDTOSchema,timeline:z95.array(UsageTimelinePointDTOSchema),topOrganizations:z95.array(OrganizationUsageRowDTOSchema),topUsers:z95.array(UserUsageRowDTOSchema),topProjects:z95.array(ProjectUsageRowDTOSchema),creditDistribution:z95.array(UsageDistributionItemDTOSchema),userDistribution:z95.array(UsageDistributionItemDTOSchema),heatmap:z95.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z95.object({page:z95.number(),limit:z95.number(),totalItems:z95.number(),totalPages:z95.number(),hasMore:z95.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z95.object({organizations:z95.array(OrganizationUsageRowDTOSchema),top:z95.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z95.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z95.object({users:z95.array(ExtendedUserUsageRowDTOSchema),top:z95.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z95.string(),ownerName:z95.string().nullable(),ownerEmail:z95.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z95.object({projects:z95.array(ExtendedProjectUsageRowDTOSchema),top:z95.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z95.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z95.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z95.object({credits:z95.number(),costUsd:z95.number(),messages:z95.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z95.object({id:z95.string(),name:z95.string(),createdAt:z95.string(),memberCount:z95.number(),projectCount:z95.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z95.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z95.object({id:z95.string(),name:z95.string().nullable(),email:z95.string(),image:z95.string().nullable(),createdAt:z95.string(),organizationCount:z95.number(),projectCount:z95.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z95.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z95.object({id:z95.string(),name:z95.string(),displayName:z95.string().nullable(),createdAt:z95.string(),organizationId:z95.string(),organizationName:z95.string(),ownerId:z95.string(),ownerName:z95.string().nullable(),ownerEmail:z95.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z95.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z96}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=z96.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z96.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z96.object({command:z96.string().min(1).max(1e4),cwd:z96.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z96.record(z96.string(),z96.string()).optional(),name:z96.string().optional(),waitForCompletion:z96.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=z96.object({identifier:z96.string(),status:SandboxProcessStatusSchema,command:z96.string().optional(),startedAt:z96.string().optional(),exitCode:z96.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z96.object({processes:z96.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z96.object({processId:z96.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z96.object({success:z96.boolean(),message:z96.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z97}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=z97.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z97.object({search:z97.string().trim().max(200).optional(),startDate:z97.coerce.date().optional(),endDate:z97.coerce.date().optional(),states:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(AdminUnclaimedStateSchema).optional()),cliVersions:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(z97.string().max(64)).optional()),page:z97.coerce.number().int().min(1).default(1),pageSize:z97.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z97.object({projectId:z97.string(),displayName:z97.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z97.string().nullable(),createdAt:z97.coerce.date(),expiresAt:z97.coerce.date(),claimedAt:z97.coerce.date().nullable(),claimedOrganizationId:z97.string().nullable(),claimedOrganizationName:z97.string().nullable(),claimedByEmail:z97.string().nullable(),projectExists:z97.boolean(),previewUrl:z97.string().nullable(),hostingCostUsd:z97.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z97.object({projects:z97.array(AdminUnclaimedProjectDTOSchema),page:z97.number(),limit:z97.number(),total:z97.number(),totalPages:z97.number()})),ClaimOutcomesSchema=z97.object({total:z97.number(),claimed:z97.number(),archived:z97.number(),claimRate:z97.number().nullable(),medianTimeToClaimSeconds:z97.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z97.record(AdminUnclaimedStateSchema,z97.number()),averageTimeToClaimSeconds:z97.number().nullable(),byCliVersion:z97.array(ClaimOutcomesSchema.extend({cliVersion:z97.string().nullable()})),granularity:z97.enum(["hour","day"]),series:z97.array(z97.object({at:z97.coerce.date(),states:z97.record(AdminUnclaimedStateSchema,z97.number()),alive:z97.number(),hostingCostUsd:z97.number()})),hostingCostUsd:z97.number(),costPerProjectUsd:z97.number().nullable(),leftovers:z97.object({overdue:z97.number(),claiming:z97.number(),archivedNotDeleted:z97.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z98}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z98.enum(["internal","user-visible"]),SessionSetRetentionSchema=z98.object({additionalDays:z98.number().int().min(1).max(30)}).strict()}});import{z as z99}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=z99.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=z99.object({content:ProjectKnowledgeContentSchema,updatedAt:z99.string().nullable(),updatedBy:z99.string().nullable()}),ProjectKnowledgeUpdateSchema=z99.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z99.object({id:z99.uuid(),status:z99.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z99.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z99.object({idempotencyKey:z99.uuid()})}});import{z as z100}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_args();init_commands();init_references2();init_types();init_chat_block();init_admin_chat_block();init_admin_assistant();init_chat_portrait();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_session_dto();init_agent_proposal_dto();init_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();init_platform()}});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_types2=__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(`
|
|
@@ -41,7 +41,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
41
41
|
`),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path50.basename(filename,path50.extname(filename)),this}executableDir(path51){return path51===void 0?this._executableDir:(this._executableDir=path51,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text=helper.formatHelp(this,helper);return context.hasColors?text:this._outputConfiguration.stripColor(text)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
42
42
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text=="function"?helpStr=text({error:context.error,command:context.command}):helpStr=text,helpStr&&context.write(`${helpStr}
|
|
43
43
|
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";import path2 from"node:path";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function findProjectToken(cfg=loadConfig(),start=process.cwd()){let dir=path2.resolve(start);for(;;){let candidate=path2.join(dir,PROJECT_TOKEN_FILE);if(fs2.existsSync(candidate)){let file=JSON.parse(fs2.readFileSync(candidate,"utf-8"));return normalizeApiUrl(file.apiUrl)===normalizeApiUrl(cfg.apiUrl)?{root:dir,file}:null}let parent=path2.dirname(dir);if(parent===dir)return null;dir=parent}}function writeProjectToken(root,file){let target=path2.join(root,PROJECT_TOKEN_FILE);fs2.mkdirSync(path2.dirname(target),{recursive:!0}),fs2.writeFileSync(target,`${JSON.stringify(file,null,2)}
|
|
44
|
-
`,{mode:384})}function resolveAuth(cfg=loadConfig()){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();if(bearer)return bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer};let tokenFile=findProjectToken(cfg);if(tokenFile)return{kind:"project",token:tokenFile.file.token,tokenFile};let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");__name(resolveAuth,"resolveAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});import{z as z101}from"zod";function createResponseSchema2(dataSchema){return z101.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path50,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path50}?${queryString}`:path50}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z101.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z101.object({items:z101.array(itemSchema),nextCursor:z101.string().nullable(),total:z101.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z101.uuid(),sessionStatusSchema=z101.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z101.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z101.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z101.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z101.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z101.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z101.string().nullable().optional(),goal:z101.string().nullable().optional(),provenance:z101.object({source:z101.enum(["studio","slack","mcp"]),creator:z101.object({kind:z101.enum(["user","slack","agent","oauth","conversation"]),id:z101.string()}),conversationId:z101.string().nullable(),runId:z101.string().nullable()}).nullable().optional(),createdBy:z101.string().optional(),createdAt:z101.iso.datetime().optional(),savedRevision:z101.string().nullable().optional(),targetBranch:z101.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z101.string().min(1)}),workingBranch:z101.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z101.url().nullable(),lastActivityAt:z101.iso.datetime(),expiresAt:z101.iso.datetime().nullable(),retention:z101.enum(["temporary","durable"]).optional(),visibility:z101.enum(["internal","user-visible"]).optional(),onExpire:z101.enum(["discard","keep"]),nextOperations:z101.array(z101.string())}),paginationShape={limit:z101.number().int().min(1).max(100).optional(),cursor:z101.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z101.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z101.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z101.object({data:z101.array(z101.unknown()),meta:z101.object({limit:z101.number().int().positive(),offset:z101.number().int().nonnegative(),total:z101.number().int().nonnegative(),hasMore:z101.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z102}from"zod";var agent,chats,routines,routineRuns,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z102.object({id:uuidSchema,kind:z102.string(),title:z102.string().nullable(),description:z102.string().nullable()}),chats=z102.object({chats:z102.array(agent)}),routines=z102.object({routines:z102.array(z102.object({id:uuidSchema,name:z102.string(),instructions:z102.string(),paused:z102.boolean(),triggers:z102.object({schedule:z102.object({cron:z102.string(),timezone:z102.string()}).nullable(),event:z102.object({text:z102.string()}).nullable()}),nextRunAt:z102.string().nullable(),lastRunAt:z102.string().nullable(),lastOutcome:z102.string().nullable(),outOfAgentHoursUntil:z102.string().nullable()}))}),routineRuns=z102.object({runs:z102.array(z102.object({startedAt:z102.string(),trigger:z102.enum(["schedule","hand","event"]),startedBy:z102.object({kind:z102.enum(["person","agent"]),name:z102.string().nullable()}).nullable(),status:z102.enum(["queued","running","finished","failed","cancelled"]),outcome:z102.string().nullable(),summary:z102.string().nullable(),durationMs:z102.number().nullable()}))}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId})}),"buildRequest")},"agents.routineRuns":{domain:"agents",summary:"Read a routine\u2019s newest runs: when each started, what started it and how it ended.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRuns,buildRequest:__name(({projectId,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId})}),"buildRequest")}}}});import{z as z103}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z103.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z103.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z103.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z103.union([z103.literal(7),z103.literal(30),z103.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z103.object({date:z103.string(),content:z103.string(),updatedAt:z103.string(),updatedByUserId:z103.string()}),analyticsBreakdownSchema=z103.object({key:z103.string(),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative()}),analyticsPageBreakdownSchema=z103.object({path:z103.string(),pageName:z103.string().nullable().optional(),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative()}),analyticsPageviewsSchema=z103.object({range:z103.object({preset:analyticsPresetSchema,requestedFrom:z103.string(),requestedTo:z103.string(),effectiveFrom:z103.string(),effectiveTo:z103.string(),isRetentionLimited:z103.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative(),botPageviews:z103.number().int().nonnegative().default(0),botVisitors:z103.number().int().nonnegative().default(0),bounceRate:z103.number().min(0).max(100),viewsPerVisit:z103.number().nonnegative(),averageVisitDurationSeconds:z103.number().nonnegative(),visitorsSeries:z103.array(z103.object({date:z103.string(),visitors:z103.number().int().nonnegative()})),topPages:z103.array(analyticsPageBreakdownSchema),topBrowsers:z103.array(analyticsBreakdownSchema),topDevices:z103.array(analyticsBreakdownSchema),topBots:z103.array(analyticsBreakdownSchema).default([]),topAiAssistants:z103.array(analyticsBreakdownSchema).default([]),topCountries:z103.array(analyticsBreakdownSchema),topSources:z103.array(analyticsBreakdownSchema),annotations:z103.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z103.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z103.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z103.array(z103.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z103.object({branch:branchNameSchema,annotations:z103.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z103.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,date:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z103.string().max(500)}).strict(),outputSchema:z103.union([analyticsAnnotationResponseSchema,z103.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,date:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z103.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z104}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z104.object({id:z104.string(),name:z104.string()}),AssetDTOSchema2=z104.object({id:z104.string(),name:z104.string(),type:z104.enum(["file","folder"]),originalFileName:z104.string().nullable(),parentId:z104.string().nullable(),mimeType:z104.string().nullable(),fileSize:z104.number().nullable(),url:z104.string().nullable(),storageKey:z104.string().nullable(),slug:z104.string(),tags:z104.array(z104.string()).nullable().optional(),createdAt:z104.string().nullable(),updatedAt:z104.string().nullable(),altText:z104.string().nullable().optional(),caption:z104.string().nullable().optional(),aiCaption:z104.string().nullable().optional(),aiAltText:z104.string().nullable().optional(),aiTags:z104.array(z104.string()).nullable().optional(),aiPrimaryColor:z104.string().nullable().optional(),aiProcessingStatus:z104.string().nullable().optional(),width:z104.number().nullable().optional(),height:z104.number().nullable().optional(),path:z104.array(assetPathItemSchema).optional(),hasChildren:z104.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z104.object({cursor:z104.string().nullable().optional(),query:z104.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z104.object({url:z104.url(),mediaType:z104.string(),filename:z104.string()}),assetReadBaseSchema=z104.object({assetId:z104.uuid(),filename:z104.string(),mediaType:z104.string(),representation:z104.enum(["text","table","document","archive","image","transcript","video","model"]),content:z104.string(),derivedFiles:z104.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z104.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z104.literal("page"),start:z104.number().int().nonnegative(),end:z104.number().int().nonnegative(),total:z104.number().int().nonnegative(),nextCursor:z104.string().nullable(),complete:z104.boolean()}),assetReadBaseSchema.extend({mode:z104.literal("query"),query:z104.string(),source:z104.enum(["original-file","canonical-text","derived-files"]),truncated:z104.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z104.object({jobId:z104.string(),status:z104.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z104.string().nullable().optional(),credits:z104.number().optional(),costUsd:z104.number().optional(),billingMode:z104.enum(["fimo-credits","provider-account"]).optional(),task:z104.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z104.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z104.object({data:z104.object({message:z104.literal("success")})}),assetGenerationInputSchema=z104.object({projectId:uuidSchema,branch:branchNameSchema,task:z104.string().min(1).optional(),model:z104.string().min(1).optional(),options:z104.record(z104.string(),z104.unknown()),name:z104.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z104.string().max(2e3).optional(),caption:z104.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z104.object({projectId:uuidSchema,sessionId:uuidSchema,url:z104.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z104.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z104.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z104.string().max(1024).refine(path50=>path50.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path50=>path50.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z104.string().max(2e3).optional(),caption:z104.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z104.string().max(200).optional(),type:z104.enum(["file","folder"]).optional(),mimePrefix:z104.string().max(50).optional(),sortBy:z104.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z104.enum(["asc","desc"]).optional(),includePath:z104.boolean().optional(),excludeHidden:z104.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,name:z104.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z104.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z105}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z105.object({projectId:uuidSchema,organizationId:z105.string(),balance:z105.object({totalAvailable:z105.number(),nearLimit:z105.boolean(),canUseAi:z105.boolean(),buckets:z105.object({dailyFreeAvailable:z105.number(),monthlyAvailable:z105.number(),purchasedAvailable:z105.number(),awardedAvailable:z105.number()})}),allowances:z105.object({dailyCredits:z105.object({periodCap:z105.number(),dailyGrant:z105.number(),usedThisPeriod:z105.number(),remainingThisPeriod:z105.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z105.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z106}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z106.object({ok:z106.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z106.array(z106.object({surface:backendSurfaceSchema,count:z106.number().int().nonnegative()})),conflicts:z106.array(backendConflictSchema).optional(),summary:z106.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z106.object({mergeId:uuidSchema,conflicts:z106.array(backendConflictSchema),draftResolutions:z106.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z106.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z106.object({data:z106.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z106.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z106.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z106.array(backendSurfaceDeltaSchema).max(6),crossSurface:z106.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z106.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z106.string().min(1),surfaces:z106.array(backendSurfaceDeltaSchema).max(6),crossSurface:z106.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z106.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z106.enum(["provisioning","active","deleted"]),kind:z106.enum(["user","agent-session"]),createdAt:z106.string().optional(),updatedAt:z106.string().optional(),createdBy:z106.string().nullable().optional(),deletedAt:z106.string().nullable().optional()}).passthrough(),branchResponseSchema=z106.object({data:branchSchema}),branchSurfaceStatusSchema=z106.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z106.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z106.iso.datetime(),backendCrossSurfaceFindingSchema=z106.object({id:z106.string(),kind:z106.string(),description:z106.string(),severity:z106.enum(["warning","error"]),source:z106.object({surface:backendSurfaceSchema,key:z106.string()}),target:z106.object({surface:backendSurfaceSchema,key:z106.string()}),actions:z106.array(z106.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z106.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z106.number().int().nonnegative(),conflictCount:z106.number().int().nonnegative(),items:z106.array(z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),origin:z106.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z106.record(z106.string(),z106.unknown()).optional()})).max(1e3).optional(),truncated:z106.boolean().optional(),error:z106.string().optional()}),branchSurfaceSummarySchema=z106.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z106.number().int().nonnegative(),conflictCount:z106.number().int().nonnegative(),error:z106.string().optional(),items:z106.array(z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),origin:z106.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z106.record(z106.string(),z106.unknown()).optional()})).optional(),truncated:z106.boolean().optional()}),branchStatusOutputSchema=z106.object({branch:branchNameSchema,against:branchNameSchema,state:z106.enum(["clean","changed"]),syncState:z106.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z106.array(branchSurfaceSummarySchema).max(6),crossSurface:z106.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),meta:z106.record(z106.string(),z106.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z106.string().min(1),surfaces:z106.array(branchSurfaceSummarySchema.extend({truncated:z106.boolean(),items:z106.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z106.object({path:z106.string(),state:z106.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z106.string(),additions:z106.number().int().nonnegative(),deletions:z106.number().int().nonnegative()}),contentSnapshotSchema=z106.object({id:z106.string(),slug:z106.string(),contentType:z106.string(),data:z106.record(z106.string(),z106.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z106.object({collection:z106.string(),rowId:z106.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z106.object({name:z106.string(),label:z106.string(),isSingleton:z106.boolean(),fields:z106.record(z106.string(),z106.unknown())}),schemaDiffOutputSchema=z106.object({typeName:z106.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z106.object({id:z106.string(),name:z106.string(),type:z106.enum(["file","folder"]),mimeType:z106.string().nullable(),storageKey:z106.string().nullable(),url:z106.string().nullable(),fileSize:z106.number().nullable(),width:z106.number().nullable(),height:z106.number().nullable(),altText:z106.string().nullable(),caption:z106.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z106.object({assetId:z106.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z106.object({locale:z106.string(),key:z106.string(),parent:z106.string().nullable(),child:z106.string().nullable()}),formSnapshotSchema=z106.object({formName:z106.string(),label:z106.string().nullable(),schemaFingerprint:z106.string(),fields:z106.record(z106.string(),z106.unknown())}),formDiffOutputSchema=z106.object({formName:z106.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z106.object({surface:backendSurfaceSchema,key:z106.string(),kind:z106.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z106.string(),parentValue:z106.unknown().optional(),childValue:z106.unknown().optional(),conflictingFields:z106.array(z106.string()).optional(),code:z106.object({path:z106.string(),unresolvable:z106.boolean().optional(),reason:z106.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z106.object({field:z106.string(),choice:z106.enum(["parent","child","pick","ai-pick"]),pickedValue:z106.unknown().optional(),aiSessionId:z106.string().optional()}),conflictResolutionSchema=z106.object({surface:branchSurfaceSchema,key:z106.string(),choice:z106.enum(["parent","child","pick"]),pickedValue:z106.unknown().optional(),fieldPicks:z106.array(fieldPickSchema).optional()}),mergeResultSchema=z106.object({ok:z106.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z106.array(z106.object({surface:branchSurfaceSchema,count:z106.number().int().nonnegative()})),conflicts:z106.array(conflictSchema).optional(),summary:z106.string().optional()}),resolvedMergeStrategySchema=z106.object({engine:z106.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z106.enum(["ff_only","ff_prefer","merge"]),squash:z106.boolean()}),mergeAcceptedSchema=z106.object({mergeId:uuidSchema,streamUrl:z106.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z106.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z106.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z106.string().nullable(),error:z106.string().nullable()}),mergeHydrationSchema=z106.object({mergeId:uuidSchema,conflicts:z106.array(conflictSchema),draftResolutions:z106.array(conflictResolutionSchema),status:z106.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z106.object({content:z106.string(),sha:z106.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z106.object({path:z106.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,includeDeleted:z106.boolean().optional(),includeAgentBranches:z106.boolean().optional()}).strict(),outputSchema:z106.object({data:z106.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z106.object({branch:branchSchema,conflicts:z106.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z106.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z106.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z106.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z106.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z106.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,path:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path50,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path50,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,collection:z106.string().min(1),rowId:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,locale:z106.string().min(1),key:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,formName:z106.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z106.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z106.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId,mergeId})=>({method:"GET",path:managementProjectPath(projectId,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z106.object({ok:z106.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z106.object({ok:z106.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z106.array(conflictResolutionSchema)}).strict(),outputSchema:z106.object({mergeId:uuidSchema,lastEditedAt:z106.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z106.object({mergeId:uuidSchema,lastEditedAt:z106.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z106.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path50})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path50})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z107}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z107.object({id:z107.string(),hostname:z107.string(),status:z107.string(),ssl:z107.record(z107.string(),z107.unknown()),cnameTarget:z107.string(),apexTargets:z107.array(z107.string()),dnsAutoConfigured:z107.boolean(),createdAt:z107.unknown(),provider:z107.enum(["cloudflare","saas_custom_domains"]),domainType:z107.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z107.object({id:uuidSchema,domain:z107.string(),status:z107.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z107.enum(["fimo","external"]),autoRenew:z107.boolean(),paymentStatus:z107.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z107.string().nullable()}).passthrough(),domainSearchResultSchema=z107.object({domain:z107.string(),available:z107.boolean(),premium:z107.boolean(),price:z107.number().nullable(),renewalPrice:z107.number().nullable(),purchaseType:z107.string().nullable()}).passthrough(),domainPricingSchema=z107.object({domain:z107.string(),price:z107.number().nullable(),renewalPrice:z107.number().nullable(),premium:z107.boolean(),allowedYears:z107.array(z107.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z107.object({}).strict(),outputSchema:z107.object({domainPurchaseEnabled:z107.boolean(),publicationDomain:z107.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,slug:z107.string().min(1).max(63)}).strict(),outputSchema:z107.object({subdomain:z107.string(),subdomainUpdatedAt:z107.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,base:z107.string().min(1).max(63).optional(),max:z107.number().int().positive().optional()}).strict(),outputSchema:z107.array(z107.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z107.object({data:z107.object({suggestions:z107.array(z107.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema}).strict(),outputSchema:z107.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,hostname:z107.string().min(1).max(255),redirectToWww:z107.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,domainId:z107.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,domainId:z107.string().min(1)}).strict(),outputSchema:z107.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z107.object({keyword:z107.string().min(1).max(100),tldFilter:z107.array(z107.string().min(1)).optional()}).strict(),outputSchema:z107.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z107.object({domain:z107.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z107.object({organizationId:z107.string().min(1)}).strict(),outputSchema:z107.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z107.object({organizationId:z107.string().min(1),domain:z107.string().min(1).max(255),years:z107.number().int().min(1).max(10).optional(),autoRenew:z107.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z107.object({organizationId:z107.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z108}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z108.object({id:z108.string(),entryId:z108.string(),documentId:z108.string(),slug:z108.string(),locale:z108.string().optional(),createdAt:z108.string(),updatedAt:z108.string(),__fimo:z108.object({contentType:z108.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({limit:z108.number(),offset:z108.number(),total:z108.number(),hasMore:z108.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z108.union([z108.string(),z108.number(),z108.boolean(),z108.null()]),entryWhereOperatorSchema2=z108.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z108.array(entryWhereScalarSchema2).optional(),$nin:z108.array(entryWhereScalarSchema2).optional(),$contains:z108.string().optional(),$startsWith:z108.string().optional(),$null:z108.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z108.record(z108.string(),z108.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z108.record(z108.string(),z108.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z108.object({data:z108.record(z108.string(),z108.unknown()),locale:z108.string().min(1).optional(),documentId:z108.uuid().optional()}),BulkCreateEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({created:z108.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({updated:z108.number().int().nonnegative(),missing:z108.array(z108.string())})}),BulkDeleteEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({deleted:z108.number().int().nonnegative(),missing:z108.array(z108.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z108.string().min(1).max(255),localeSchema=z108.string().min(1),populateSchema=z108.array(z108.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z108.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,search:z108.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z108.string().min(1).max(255),data:entryDataSchema,locale:z108.string().min(1).optional(),documentId:z108.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z108.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z108.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z108.record(z108.string(),z108.unknown())}).strict(),outputSchema:z108.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z108.object({data:z108.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,sql:z108.string().min(1)}).strict(),outputSchema:z108.object({data:z108.array(z108.record(z108.string(),z108.unknown())),meta:z108.object({rowCount:z108.number().int().nonnegative(),truncated:z108.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z108.array(z108.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z108.union([z108.object({ids:z108.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z108.object({where:EntryWhereSchema2}),z108.object({updates:z108.array(z108.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z108.union([z108.object({ids:z108.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z108.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z109}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z109.object({id:z109.literal("production"),projectId:uuidSchema,name:z109.string(),kind:z109.literal("production"),sourceBranch:z109.string().min(1),isPublished:z109.boolean(),url:z109.string().nullable()}),previewEnvironmentSchema=z109.object({id:z109.literal("preview"),projectId:uuidSchema,name:z109.string(),kind:z109.literal("preview"),matchedBranchCount:z109.number().int().nonnegative()}),customEnvironmentSchema=z109.object({id:uuidSchema,projectId:uuidSchema,name:z109.string().min(1).max(64),branchPatterns:z109.array(z109.string().min(1).max(255)).min(1),description:z109.string().max(255).nullable(),kind:z109.literal("custom"),matchedBranchCount:z109.number().int().nonnegative()}),environmentSchema=z109.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z109.string().trim().min(1).max(64),branchPatterns:z109.array(z109.string().min(1).max(255)).min(1),description:z109.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z109.object({projectId:uuidSchema}).strict(),outputSchema:z109.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z109.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,environmentId:z109.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,environmentId:z109.string().min(1)}).strict(),outputSchema:z109.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z109.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z110}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z110.object({data:z110.object({path:z110.string(),content:z110.string(),totalLines:z110.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z110.object({data:z110.object({paths:z110.array(z110.string().min(1)).max(2e3),truncated:z110.boolean()})}),fileGrepOutputSchema=z110.object({data:z110.object({matches:z110.array(z110.object({path:z110.string().min(1),line:z110.number().int().positive(),text:z110.string()})).max(200),truncated:z110.boolean()})}),fileWriteInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z110.boolean().optional()}).strict(),fileEditInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z110.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),created:z110.boolean(),tip:z110.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,files:z110.array(z110.object({path:z110.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files2=>files2.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z110.array(z110.object({path:z110.string(),created:z110.boolean()}).passthrough()),tip:z110.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),replacements:z110.number().int().nonnegative(),tip:z110.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),deleted:z110.literal(!0),tip:z110.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z110.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z110.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path50})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path50})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z110.object({...fileSearchInputShape,pattern:z110.string().min(1).max(300).optional(),limit:z110.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z110.object({...fileSearchInputShape,pattern:z110.string().min(1).max(200),include:z110.string().min(1).max(300).optional(),caseInsensitive:z110.boolean().optional(),maxMatches:z110.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path50,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path50,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path50}}),"buildRequest")}}}});import{z as z111}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z111.object({data:z111.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z111.object({data:z111.array(formSubmissionSchema),total:z111.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z111.object({type:z111.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z111.string(),placeholder:z111.string().optional(),required:z111.boolean().optional(),defaultValue:z111.string().optional(),options:z111.array(z111.string()).optional(),validation:z111.object({minLength:z111.number().optional(),maxLength:z111.number().optional(),min:z111.number().optional(),max:z111.number().optional(),pattern:z111.string().optional(),maxFileSize:z111.number().optional(),accept:z111.array(z111.string()).optional()}).optional()}),FormContentSchema2=z111.object({name:z111.string().min(1).max(255),label:z111.string().min(1).max(255),fields:z111.record(z111.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z111.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z111.record(z111.string(),z111.unknown()).nullable().optional(),createdAt:z111.string(),updatedAt:z111.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z111.object({data:formSchema}),formSubmissionSchema=z111.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z111.record(z111.string(),z111.unknown()),submittedAt:z111.string()}),formSubmissionResponseSchema=z111.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z111.object({data:z111.object({total:z111.number().int().nonnegative(),dailyCounts:z111.array(z111.object({date:z111.string(),count:z111.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z111.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),...paginationShape,searchQuery:z111.string().max(200).optional(),sortDirection:z111.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),submissionId:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),submissionId:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z112}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z112.object({costUsd:z112.number(),credits:z112.number().optional(),billingMode:z112.enum(["fimo-credits","provider-account"]).optional(),confidence:z112.enum(["exact","estimated","metered"]),basis:z112.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,model:z112.string().min(1),options:z112.record(z112.string(),z112.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,branch:branchNameSchema,task:z112.string().min(1),options:z112.record(z112.string(),z112.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z113}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z113.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z113.object({versionId:uuidSchema,commitHash:z113.string(),name:z113.string(),description:z113.string().nullable(),kind:historyKindSchema,createdAt:z113.iso.datetime(),expiresAt:z113.iso.datetime()}),projectVersionPageSchema=z113.object({items:z113.array(projectVersionSchema),nextCursor:z113.string().nullable()}),historySummarySchema=z113.object({usage:z113.object({versionCount:z113.number().int().nonnegative(),snapshotBytes:z113.number().int().nonnegative()}),retentionDays:z113.number().int().positive()}),restoreResultSchema=z113.object({durationMs:z113.number().nonnegative().optional(),warning:z113.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,limit:z113.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,name:z113.string().min(1),description:z113.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z114}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z114.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z114.object({isPublished:z114.boolean(),publishedAt:z114.iso.datetime().nullable(),publishedVersion:z114.string().nullable()}),publicationOutputSchema=z114.object({id:uuidSchema,status:z114.enum(["queued","building","published","failed","canceled"]),label:z114.string().nullable(),notes:z114.string().nullable(),source:z114.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z114.string().nullable(),framework:z114.string().nullable(),commit:z114.string().nullable()}),createdAt:z114.iso.datetime(),finishedAt:z114.iso.datetime().nullable(),url:z114.string().nullable(),failureCode:z114.string().nullable()}),publicationsPageOutputSchema=z114.object({items:z114.array(publicationOutputSchema),nextCursor:z114.string().nullable(),retention:z114.object({scope:z114.literal("publication_attempt_record"),records:z114.literal("project_lifetime")})}),publicationLogsOutputSchema=z114.object({status:z114.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z114.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z114.string().nullable(),items:z114.array(z114.object({timestamp:z114.iso.datetime(),phase:z114.enum(["build","deploy"]),stream:z114.enum(["command","stdout","stderr","status","error"]),message:z114.string()}))}),sandboxLogsOutputSchema=z114.object({status:z114.enum(["ok","unavailable"]),reason:z114.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z114.string().nullable(),items:z114.array(z114.object({id:z114.string(),timestamp:z114.iso.datetime().nullable(),source:z114.enum(["install","dev-server"]),phase:z114.string(),stream:z114.enum(["combined","stdout","stderr"]),message:z114.string()})),nextCursor:z114.string().nullable(),retention:z114.object({scope:z114.literal("sandbox_process_snapshot"),timestamps:z114.literal("process_start"),droppedOldest:z114.boolean(),phases:z114.array(z114.object({phase:z114.string(),source:z114.enum(["install","dev-server"]),status:z114.string(),startedAt:z114.iso.datetime().nullable(),exitCode:z114.number().int().nullable(),events:z114.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z114.object({url:z114.string(),branch:branchNameSchema}),previewOpenOutputSchema=z114.object({url:z114.url(),expiresAt:z114.iso.datetime().nullable()}),publishOutputSchema=z114.object({success:z114.boolean(),message:z114.string().optional(),firstPublish:z114.boolean(),publicationId:z114.string().optional(),url:z114.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,limit:z114.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,publicationId:z114.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,label:z114.string().trim().min(1).max(120).optional(),notes:z114.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,publicationId:z114.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z115}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z115.object({content:z115.string(),updatedAt:z115.string().nullable(),updatedBy:z115.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,content:z115.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z116}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z116.object({key:z116.string(),value:z116.string().optional(),defaultValue:z116.string(),locale:z116.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z116.object({data:z116.array(z116.union([TranslationDTOSchema2,z116.object({key:z116.string(),values:z116.record(z116.string(),z116.string())})]))}),labelUpsertOutputSchema=z116.object({created:z116.number().int().nonnegative(),updated:z116.number().int().nonnegative(),deleted:z116.number().int().nonnegative(),defaultLocale:z116.string(),locales:z116.array(z116.string())}),labelDeleteOutputSchema=z116.object({key:z116.string(),locale:z116.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z116.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,key:z116.string(),value:z116.string(),locale:z116.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,records:z116.array(z116.object({key:z116.string(),value:z116.string(),locale:z116.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:z116.string().optional(),key:z116.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z117}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z117.object({translated:z117.number().int().nonnegative(),total:z117.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z117.object({defaultLocale:z117.string(),locales:z117.array(z117.object({locale:z117.string(),isDefault:z117.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z117.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z117.object({locale:z117.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z117.object({locale:z117.string(),entriesDeleted:z117.number().int().nonnegative(),labelsDeleted:z117.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z118}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z118.object({id:z118.string().min(1),name:z118.string(),slug:z118.string()}),organizationMemberSchema=z118.object({id:z118.string().min(1),role:z118.string(),createdAt:z118.string().optional(),user:z118.object({id:z118.string().min(1),name:z118.string().nullable().optional(),email:z118.string().nullable().optional()}).optional()}),organizationInvitationSchema=z118.object({id:z118.string().min(1),email:z118.email(),role:z118.string(),organizationId:z118.string().min(1),inviterId:z118.string().min(1),status:z118.string(),expiresAt:z118.string(),createdAt:z118.string()}).passthrough(),referralSummarySchema=z118.object({counts:z118.object({signed_up:z118.number().int(),activated:z118.number().int()}),credits:z118.object({total:z118.number().int(),earned:z118.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z118.object({}).strict(),outputSchema:createResponseSchema2(z118.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z118.object({organizationId:z118.string().min(1)}).strict(),outputSchema:z118.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z118.object({members:z118.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z118.object({organizationId:z118.string().min(1),email:z118.email(),role:z118.enum(["owner","admin","member"]),resend:z118.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z118.object({userId:z118.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z119}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z119.object({id:uuidSchema,name:z119.string(),displayName:z119.string().nullable(),organizationId:z119.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z119.string().optional(),appUrl:z119.string().nullable().optional()}).passthrough(),projectResponseSchema=z119.object({data:projectSchema}),transferResultSchema=z119.object({projectId:z119.string(),sourceOrganizationId:z119.string(),targetOrganizationId:z119.string(),movedThreads:z119.number().int().nonnegative(),revokedInvites:z119.number().int().nonnegative(),revokedGrants:z119.number().int().nonnegative(),preservedGrants:z119.number().int().nonnegative(),warnings:z119.array(z119.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z119.object({organizationId:z119.string().min(1).optional()}).strict(),outputSchema:z119.object({data:z119.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z119.object({organizationId:z119.string().min(1),displayName:z119.string().min(1).optional(),origin:z119.enum(["scratch","migration"]).optional(),starter:z119.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,targetOrganizationId:z119.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,email:z119.email(),role:z119.enum(["full","edit","comment","view"])}).strict(),outputSchema:z119.object({id:z119.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z119.object({id:z119.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema}).strict(),outputSchema:z119.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z120}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z120.iso.datetime(),scheduleStatusSchema=z120.enum(["ok","failed"]),runStatusSchema=z120.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z120.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z120.string().min(1),name:z120.string().min(1),cron:z120.string().min(1),command:z120.string().min(1),secretKeys:z120.array(z120.string().min(1)),enabled:z120.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z120.string().nullable(),overPolicyReasons:z120.array(z120.string()).optional()}).passthrough(),usageSchema=z120.object({runCount:z120.number().int().nonnegative(),runsWithOutput:z120.number().int().nonnegative()}),policySchema=z120.object({maxRuns:z120.number().int().positive(),retentionDays:z120.number().int().positive().nullable(),outputRetentionDays:z120.number().int().positive(),maxOutputBytes:z120.number().int().positive()}).passthrough(),planSchema=z120.object({code:z120.enum(["Free","PAYG","Premium","Pro"]),source:z120.enum(["cached_subscription","free_fallback"]),activeSchedules:z120.object({used:z120.number().int().nonnegative(),limit:z120.number().int().positive()}),minCadenceMinutes:z120.number().int().positive(),maxRunMs:z120.number().int().positive(),concurrency:z120.object({used:z120.number().int().nonnegative(),limit:z120.number().int().positive()}),compute:z120.object({settledMs:z120.number().int().nonnegative(),activeMs:z120.number().int().nonnegative(),reservedMs:z120.number().int().nonnegative().optional(),includedMs:z120.number().int().positive(),remainingMs:z120.number().int().nonnegative(),resetsAt:dateSchema}),state:z120.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z120.array(z120.string())}).passthrough(),runSchema=z120.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z120.string().min(1),scheduleName:z120.string().min(1),command:z120.string().min(1),status:runStatusSchema,trigger:z120.enum(["cron","ui","cli"]),triggeredBy:z120.object({id:z120.string().min(1),name:z120.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z120.number().int().nullable(),errorCode:z120.string().nullable(),error:z120.string().nullable(),outputBytes:z120.number().int().nonnegative(),outputTruncated:z120.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z120.string().nullable(),secretSnapshot:z120.object({state:z120.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z120.array(z120.object({key:z120.string().min(1),updatedAt:dateSchema.nullable(),resolution:z120.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z120.object({items:z120.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z120.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z120.object({items:z120.array(runSchema),nextCursor:z120.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z120.string().min(1).max(120),cron:z120.string().min(1).max(120),command:z120.string().min(1).max(500),secretKeys:z120.array(z120.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape}).strict(),outputSchema:z120.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z120.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,...scheduleWriteShape,enabled:z120.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z120.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z120.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z120.object({ok:z120.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z121}from"zod";function projectSchemaDefinition(body){return z121.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z121.object({id:z121.string(),name:z121.string(),label:z121.string(),isSingleton:z121.boolean(),slugUnique:z121.boolean(),i18n:z121.record(z121.string(),z121.unknown()),groups:z121.array(z121.record(z121.string(),z121.unknown())),fields:z121.record(z121.string(),z121.unknown()),createdAt:z121.string(),updatedAt:z121.string()}).passthrough(),schemaListOutputSchema=z121.object({contentTypes:z121.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z121.object({typeName:z121.string().min(1).max(255),generatedPaths:z121.array(z121.string().min(1)).max(1e3),tip:z121.string().min(1)})}),schemaDefinitionInputSchema=z121.record(z121.string(),z121.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z121.array(schemaDefinitionInputSchema).min(1).max(100),operations:z121.array(z121.record(z121.string(),z121.unknown())).optional()}).strict(),outputSchema:z121.array(z121.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z121.object({data:z121.array(z121.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:z121.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z121.object({data:z121.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z121.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z122}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z122.union([z122.literal("production"),z122.literal("preview"),uuidSchema]),secretKindSchema=z122.enum(["variable","secret"]),projectSecretSchema=z122.object({id:z122.string().min(1),projectId:z122.string().min(1),key:z122.string().min(1),kind:secretKindSchema,exposure:z122.enum(["public","private"]),environment:environmentSchema2,value:z122.string().optional(),maskedValue:z122.string().optional(),createdAt:z122.string(),updatedAt:z122.string()}),secretWriteInputSchema=z122.object({projectId:uuidSchema,key:z122.string().min(1).max(255),kind:secretKindSchema,value:z122.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z122.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z122.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z122.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,key:z122.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z122.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,branch:z122.string().min(1)}).strict(),outputSchema:z122.object({branch:z122.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z122.array(z122.object({branch:z122.string().optional(),env:z122.string().optional(),parentBranch:z122.string().nullable().optional(),parentEnv:z122.string().nullable().optional(),resolvedEnvironment:z122.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z123}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z123.object({status:z123.literal("passed")}).passthrough(),sessionConflictSummarySchema=z123.object({surface:surfaceNameSchema,key:z123.string().min(1),kind:z123.string().optional(),description:z123.string(),path:z123.string().optional()}).passthrough(),surfaceDeltaItemSchema=z123.object({verb:z123.enum(["added","removed","changed","conflict"]),key:z123.string(),detail:z123.string().optional(),origin:z123.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z123.record(z123.string(),z123.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z123.object({surface:surfaceNameSchema,status:z123.enum(["ok","timed_out","failed","unchanged"]),durationMs:z123.number().int().nonnegative().optional(),changedCount:z123.number().int().nonnegative(),conflictCount:z123.number().int().nonnegative(),items:z123.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z123.boolean().optional(),error:z123.string().optional()}).passthrough(),sessionChangesSchema=z123.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z123.iso.datetime(),surfaces:z123.array(perSurfaceDeltaSchema),crossSurface:z123.array(crossSurfaceFindingSchema).optional(),fingerprint:z123.string()}).passthrough(),projectScriptStatusSchema=z123.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z123.discriminatedUnion("operation",[z123.object({operation:z123.literal("dependencies_install"),repairedInstallPolicy:z123.boolean(),tip:z123.string()}),z123.object({operation:z123.literal("schemas_sync"),tip:z123.string()}),z123.object({operation:z123.literal("typecheck"),status:projectScriptStatusSchema,output:z123.string()}),z123.object({operation:z123.literal("lint"),status:projectScriptStatusSchema,output:z123.string()})]),conflictSchema2=z123.object({surface:surfaceNameSchema,key:z123.string(),kind:z123.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z123.string(),parentValue:z123.unknown().optional(),childValue:z123.unknown().optional(),conflictingFields:z123.array(z123.string()).optional(),code:z123.object({path:z123.string(),unresolvable:z123.boolean().optional(),reason:z123.string().optional(),targetCommits:z123.array(z123.object({sha:z123.string(),subject:z123.string(),body:z123.string().optional(),author:z123.string(),date:z123.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z123.object({oid:z123.string().optional(),content:z123.string().optional(),truncated:z123.boolean(),binary:z123.boolean()}),codeConflictDetailSchema=z123.object({path:z123.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z123.string(),targetTipSha:z123.string(),mergeBaseSha:z123.string().optional()}),resolutionChoiceSchema=z123.enum(["parent","child","pick"]),conflictResolutionSchema2=z123.object({surface:surfaceNameSchema,key:z123.string().min(1),choice:resolutionChoiceSchema,pickedValue:z123.unknown().optional(),fieldPicks:z123.array(z123.object({field:z123.string().min(1),choice:resolutionChoiceSchema,pickedValue:z123.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z123.string().trim().min(1).max(120).optional(),goal:z123.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z123.object({session:sessionEnvelopeSchema,adopted:z123.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z123.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z123.number().int().min(1).max(100).optional()}).strict(),outputSchema:z123.object({items:z123.array(sessionEnvelopeSchema),nextCursor:z123.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z123.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z123.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z123.object({requested:z123.literal(!0),alreadyRequested:z123.boolean(),reviewId:uuidSchema,reviewUrl:z123.url(),status:z123.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z123.string().min(1),savedRevision:z123.string().min(1),fingerprint:z123.string().min(1),visibility:z123.literal("user-visible"),retention:z123.literal("durable"),expiresAt:z123.null(),merged:z123.literal(!1),published:z123.literal(!1),links:z123.object({preview:z123.url(),changes:z123.url(),conversation:z123.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z123.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z123.literal("temporary"),visibility:z123.enum(["internal","user-visible"]),expiresAt:z123.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z123.string().min(1).max(100),args:z123.record(z123.string(),z123.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,action:z123.enum(["merge","discard"]),message:z123.string().max(1e3).optional(),description:z123.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z123.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z123.boolean(),mergeId:uuidSchema.optional(),conflictCount:z123.number().int().nonnegative().optional(),conflicts:z123.array(sessionConflictSummarySchema).optional(),parentAdvanced:z123.boolean().optional(),code:z123.string().optional(),summary:z123.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z123.number().int().min(1).max(100).optional(),codePath:z123.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z123.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z123.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z123.number().int().nonnegative(),error:z123.string().nullable()}),conflicts:z123.array(conflictSchema2).max(100),nextCursor:z123.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z123.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z123.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z123.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z124}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z125}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z125.object({message:z125.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z125.object({id:uuidSchema,deliveryStatus:z125.enum(["pending","delivered","failed"]),message:z125.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z125.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z126}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z126.record(z126.string(),z126.unknown()),deliveryStatusSchema=z126.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z126.object({id:uuidSchema,projectId:uuidSchema,name:z126.string(),eventType:z126.string().min(1),enabled:z126.boolean(),destination:z126.object({host:z126.string(),maskedUrl:z126.string(),kind:z126.string()}),filter:jsonObjectSchema,headers:z126.array(jsonObjectSchema),bodyTemplate:z126.unknown().nullable(),signingEnabled:z126.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z126.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z126.string().min(1),status:deliveryStatusSchema,attemptCount:z126.number().int().nonnegative(),responseStatus:z126.number().int().nullable(),createdAt:z126.iso.datetime()}).passthrough(),attemptSchema=z126.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z126.number().int().positive(),status:z126.enum(["delivering","succeeded","failed"]),createdAt:z126.iso.datetime()}).passthrough(),deliveriesPageSchema=z126.object({items:z126.array(deliverySchema),pagination:z126.object({page:z126.number().int().positive(),limit:z126.number().int().positive(),total:z126.number().int().nonnegative(),totalPages:z126.number().int().positive(),hasMore:z126.boolean()}),stats:z126.object({total:z126.number().int().nonnegative(),succeeded:z126.number().int().nonnegative(),failed:z126.number().int().nonnegative()})}),eventSchema=z126.object({type:z126.string().min(1),family:z126.string(),description:z126.string(),variables:z126.array(z126.string()),data:z126.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema}).strict(),outputSchema:z126.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z126.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema}).strict(),outputSchema:z126.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z126.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z126.object({webhook:webhookSchema,signingSecret:z126.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z126.object({webhook:webhookSchema,signingSecret:z126.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z126.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z126.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z126.object({signingSecret:z126.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z126.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z126.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z126.object({delivery:deliverySchema,attempts:z126.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z126.object({delivery:deliverySchema,attempts:z126.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z127.object({id:z127.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z127.string().min(1),summary:z127.string().min(1),accessScope:z127.enum(["read","write","code","agents"]),effect:z127.enum(["read","mutation"]),inputJsonSchema:z127.record(z127.string(),z127.unknown()),outputJsonSchema:z127.record(z127.string(),z127.unknown())}).strict(),fimoOperationManifestSchema=z127.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z127.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z127.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.join(root,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path4 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue2=>{let{path:path50,message}=issue2;return`${Array.isArray(path50)&&path50.length>0?`${path50.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path50,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path50}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path50,init={},options={}){let response=await send(path50,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path50,init={}){let response=await send(path50,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path50,status,detail,code2,body){super(`API ${method} ${path50} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path50,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required,this.code=server.code,this.detail=server.detail}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument;exports2.isMap=isMap;exports2.isNode=isNode;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path50){let ctrl=callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visit_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=visit_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path50){let ctrl=await callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visitAsync_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=await visitAsync_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path50){if(typeof visitor=="function")return visitor(key,node,path50);if(identity2.isMap(node))return visitor.Map?.(key,node,path50);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path50);if(identity2.isPair(node))return visitor.Pair?.(key,node,path50);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path50);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path50)}__name(callVisitor,"callVisitor");function replaceNode(key,path50,node){let parent=path50[path50.length-1];if(identity2.isCollection(parent))parent.items[key]=node;else if(identity2.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity2.isDocument(parent))parent.contents=node;else{let pt2=identity2.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
44
|
+
`,{mode:384})}function resolveAuth(cfg=loadConfig()){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();if(bearer)return bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer};let tokenFile=findProjectToken(cfg);if(tokenFile)return{kind:"project",token:tokenFile.file.token,tokenFile};let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");__name(resolveAuth,"resolveAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});import{z as z101}from"zod";function createResponseSchema2(dataSchema){return z101.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path50,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path50}?${queryString}`:path50}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z101.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z101.object({items:z101.array(itemSchema),nextCursor:z101.string().nullable(),total:z101.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z101.uuid(),sessionStatusSchema=z101.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z101.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z101.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z101.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z101.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z101.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z101.string().nullable().optional(),goal:z101.string().nullable().optional(),provenance:z101.object({source:z101.enum(["studio","slack","mcp"]),creator:z101.object({kind:z101.enum(["user","slack","agent","oauth","conversation"]),id:z101.string()}),conversationId:z101.string().nullable(),runId:z101.string().nullable()}).nullable().optional(),createdBy:z101.string().optional(),createdAt:z101.iso.datetime().optional(),savedRevision:z101.string().nullable().optional(),targetBranch:z101.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z101.string().min(1)}),workingBranch:z101.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z101.url().nullable(),lastActivityAt:z101.iso.datetime(),expiresAt:z101.iso.datetime().nullable(),retention:z101.enum(["temporary","durable"]).optional(),visibility:z101.enum(["internal","user-visible"]).optional(),onExpire:z101.enum(["discard","keep"]),nextOperations:z101.array(z101.string())}),paginationShape={limit:z101.number().int().min(1).max(100).optional(),cursor:z101.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z101.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z101.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z101.object({data:z101.array(z101.unknown()),meta:z101.object({limit:z101.number().int().positive(),offset:z101.number().int().nonnegative(),total:z101.number().int().nonnegative(),hasMore:z101.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z102}from"zod";var agent,chats,routines,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z102.object({id:uuidSchema,kind:z102.string(),title:z102.string().nullable(),description:z102.string().nullable()}),chats=z102.object({chats:z102.array(agent)}),routines=z102.object({routines:z102.array(z102.object({id:uuidSchema,name:z102.string(),instructions:z102.string(),paused:z102.boolean(),triggers:z102.object({schedule:z102.object({cron:z102.string(),timezone:z102.string()}).nullable(),event:z102.object({text:z102.string()}).nullable()})}))}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId})}),"buildRequest")}}}});import{z as z103}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z103.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z103.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z103.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z103.union([z103.literal(7),z103.literal(30),z103.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z103.object({date:z103.string(),content:z103.string(),updatedAt:z103.string(),updatedByUserId:z103.string()}),analyticsBreakdownSchema=z103.object({key:z103.string(),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative()}),analyticsPageBreakdownSchema=z103.object({path:z103.string(),pageName:z103.string().nullable().optional(),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative()}),analyticsPageviewsSchema=z103.object({range:z103.object({preset:analyticsPresetSchema,requestedFrom:z103.string(),requestedTo:z103.string(),effectiveFrom:z103.string(),effectiveTo:z103.string(),isRetentionLimited:z103.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z103.number().int().nonnegative(),pageviews:z103.number().int().nonnegative(),botPageviews:z103.number().int().nonnegative().default(0),botVisitors:z103.number().int().nonnegative().default(0),bounceRate:z103.number().min(0).max(100),viewsPerVisit:z103.number().nonnegative(),averageVisitDurationSeconds:z103.number().nonnegative(),visitorsSeries:z103.array(z103.object({date:z103.string(),visitors:z103.number().int().nonnegative()})),topPages:z103.array(analyticsPageBreakdownSchema),topBrowsers:z103.array(analyticsBreakdownSchema),topDevices:z103.array(analyticsBreakdownSchema),topBots:z103.array(analyticsBreakdownSchema).default([]),topAiAssistants:z103.array(analyticsBreakdownSchema).default([]),topCountries:z103.array(analyticsBreakdownSchema),topSources:z103.array(analyticsBreakdownSchema),annotations:z103.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z103.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z103.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z103.array(z103.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z103.object({branch:branchNameSchema,annotations:z103.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z103.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,date:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z103.string().max(500)}).strict(),outputSchema:z103.union([analyticsAnnotationResponseSchema,z103.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,date:z103.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z103.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z104}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z104.object({id:z104.string(),name:z104.string()}),AssetDTOSchema2=z104.object({id:z104.string(),name:z104.string(),type:z104.enum(["file","folder"]),originalFileName:z104.string().nullable(),parentId:z104.string().nullable(),mimeType:z104.string().nullable(),fileSize:z104.number().nullable(),url:z104.string().nullable(),storageKey:z104.string().nullable(),slug:z104.string(),tags:z104.array(z104.string()).nullable().optional(),createdAt:z104.string().nullable(),updatedAt:z104.string().nullable(),altText:z104.string().nullable().optional(),caption:z104.string().nullable().optional(),aiCaption:z104.string().nullable().optional(),aiAltText:z104.string().nullable().optional(),aiTags:z104.array(z104.string()).nullable().optional(),aiPrimaryColor:z104.string().nullable().optional(),aiProcessingStatus:z104.string().nullable().optional(),width:z104.number().nullable().optional(),height:z104.number().nullable().optional(),path:z104.array(assetPathItemSchema).optional(),hasChildren:z104.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z104.object({cursor:z104.string().nullable().optional(),query:z104.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z104.object({url:z104.url(),mediaType:z104.string(),filename:z104.string()}),assetReadBaseSchema=z104.object({assetId:z104.uuid(),filename:z104.string(),mediaType:z104.string(),representation:z104.enum(["text","table","document","archive","image","transcript","video","model"]),content:z104.string(),derivedFiles:z104.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z104.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z104.literal("page"),start:z104.number().int().nonnegative(),end:z104.number().int().nonnegative(),total:z104.number().int().nonnegative(),nextCursor:z104.string().nullable(),complete:z104.boolean()}),assetReadBaseSchema.extend({mode:z104.literal("query"),query:z104.string(),source:z104.enum(["original-file","canonical-text","derived-files"]),truncated:z104.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z104.object({jobId:z104.string(),status:z104.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z104.string().nullable().optional(),credits:z104.number().optional(),costUsd:z104.number().optional(),billingMode:z104.enum(["fimo-credits","provider-account"]).optional(),task:z104.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z104.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z104.object({data:z104.object({message:z104.literal("success")})}),assetGenerationInputSchema=z104.object({projectId:uuidSchema,branch:branchNameSchema,task:z104.string().min(1).optional(),model:z104.string().min(1).optional(),options:z104.record(z104.string(),z104.unknown()),name:z104.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z104.string().max(2e3).optional(),caption:z104.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z104.object({projectId:uuidSchema,sessionId:uuidSchema,url:z104.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z104.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z104.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z104.string().max(1024).refine(path50=>path50.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path50=>path50.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z104.string().max(2e3).optional(),caption:z104.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z104.string().max(200).optional(),type:z104.enum(["file","folder"]).optional(),mimePrefix:z104.string().max(50).optional(),sortBy:z104.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z104.enum(["asc","desc"]).optional(),includePath:z104.boolean().optional(),excludeHidden:z104.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,name:z104.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z104.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z104.record(z104.string(),z104.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z104.object({data:z104.record(z104.string(),z104.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z105}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z105.object({projectId:uuidSchema,organizationId:z105.string(),balance:z105.object({totalAvailable:z105.number(),nearLimit:z105.boolean(),canUseAi:z105.boolean(),buckets:z105.object({dailyFreeAvailable:z105.number(),monthlyAvailable:z105.number(),purchasedAvailable:z105.number(),awardedAvailable:z105.number()})}),allowances:z105.object({dailyCredits:z105.object({periodCap:z105.number(),dailyGrant:z105.number(),usedThisPeriod:z105.number(),remainingThisPeriod:z105.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z105.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z106}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z106.object({ok:z106.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z106.array(z106.object({surface:backendSurfaceSchema,count:z106.number().int().nonnegative()})),conflicts:z106.array(backendConflictSchema).optional(),summary:z106.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z106.object({mergeId:uuidSchema,conflicts:z106.array(backendConflictSchema),draftResolutions:z106.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z106.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z106.object({data:z106.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z106.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z106.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z106.array(backendSurfaceDeltaSchema).max(6),crossSurface:z106.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z106.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z106.string().min(1),surfaces:z106.array(backendSurfaceDeltaSchema).max(6),crossSurface:z106.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z106.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z106.enum(["provisioning","active","deleted"]),kind:z106.enum(["user","agent-session"]),createdAt:z106.string().optional(),updatedAt:z106.string().optional(),createdBy:z106.string().nullable().optional(),deletedAt:z106.string().nullable().optional()}).passthrough(),branchResponseSchema=z106.object({data:branchSchema}),branchSurfaceStatusSchema=z106.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z106.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z106.iso.datetime(),backendCrossSurfaceFindingSchema=z106.object({id:z106.string(),kind:z106.string(),description:z106.string(),severity:z106.enum(["warning","error"]),source:z106.object({surface:backendSurfaceSchema,key:z106.string()}),target:z106.object({surface:backendSurfaceSchema,key:z106.string()}),actions:z106.array(z106.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z106.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z106.number().int().nonnegative(),conflictCount:z106.number().int().nonnegative(),items:z106.array(z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),origin:z106.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z106.record(z106.string(),z106.unknown()).optional()})).max(1e3).optional(),truncated:z106.boolean().optional(),error:z106.string().optional()}),branchSurfaceSummarySchema=z106.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z106.number().int().nonnegative(),conflictCount:z106.number().int().nonnegative(),error:z106.string().optional(),items:z106.array(z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),origin:z106.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z106.record(z106.string(),z106.unknown()).optional()})).optional(),truncated:z106.boolean().optional()}),branchStatusOutputSchema=z106.object({branch:branchNameSchema,against:branchNameSchema,state:z106.enum(["clean","changed"]),syncState:z106.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z106.array(branchSurfaceSummarySchema).max(6),crossSurface:z106.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z106.object({verb:branchDeltaVerbSchema,key:z106.string(),detail:z106.string().optional(),meta:z106.record(z106.string(),z106.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z106.string().min(1),surfaces:z106.array(branchSurfaceSummarySchema.extend({truncated:z106.boolean(),items:z106.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z106.object({path:z106.string(),state:z106.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z106.string(),additions:z106.number().int().nonnegative(),deletions:z106.number().int().nonnegative()}),contentSnapshotSchema=z106.object({id:z106.string(),slug:z106.string(),contentType:z106.string(),data:z106.record(z106.string(),z106.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z106.object({collection:z106.string(),rowId:z106.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z106.object({name:z106.string(),label:z106.string(),isSingleton:z106.boolean(),fields:z106.record(z106.string(),z106.unknown())}),schemaDiffOutputSchema=z106.object({typeName:z106.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z106.object({id:z106.string(),name:z106.string(),type:z106.enum(["file","folder"]),mimeType:z106.string().nullable(),storageKey:z106.string().nullable(),url:z106.string().nullable(),fileSize:z106.number().nullable(),width:z106.number().nullable(),height:z106.number().nullable(),altText:z106.string().nullable(),caption:z106.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z106.object({assetId:z106.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z106.object({locale:z106.string(),key:z106.string(),parent:z106.string().nullable(),child:z106.string().nullable()}),formSnapshotSchema=z106.object({formName:z106.string(),label:z106.string().nullable(),schemaFingerprint:z106.string(),fields:z106.record(z106.string(),z106.unknown())}),formDiffOutputSchema=z106.object({formName:z106.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z106.object({surface:backendSurfaceSchema,key:z106.string(),kind:z106.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z106.string(),parentValue:z106.unknown().optional(),childValue:z106.unknown().optional(),conflictingFields:z106.array(z106.string()).optional(),code:z106.object({path:z106.string(),unresolvable:z106.boolean().optional(),reason:z106.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z106.object({field:z106.string(),choice:z106.enum(["parent","child","pick","ai-pick"]),pickedValue:z106.unknown().optional(),aiSessionId:z106.string().optional()}),conflictResolutionSchema=z106.object({surface:branchSurfaceSchema,key:z106.string(),choice:z106.enum(["parent","child","pick"]),pickedValue:z106.unknown().optional(),fieldPicks:z106.array(fieldPickSchema).optional()}),mergeResultSchema=z106.object({ok:z106.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z106.array(z106.object({surface:branchSurfaceSchema,count:z106.number().int().nonnegative()})),conflicts:z106.array(conflictSchema).optional(),summary:z106.string().optional()}),resolvedMergeStrategySchema=z106.object({engine:z106.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z106.enum(["ff_only","ff_prefer","merge"]),squash:z106.boolean()}),mergeAcceptedSchema=z106.object({mergeId:uuidSchema,streamUrl:z106.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z106.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z106.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z106.string().nullable(),error:z106.string().nullable()}),mergeHydrationSchema=z106.object({mergeId:uuidSchema,conflicts:z106.array(conflictSchema),draftResolutions:z106.array(conflictResolutionSchema),status:z106.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z106.object({content:z106.string(),sha:z106.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z106.object({path:z106.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,includeDeleted:z106.boolean().optional(),includeAgentBranches:z106.boolean().optional()}).strict(),outputSchema:z106.object({data:z106.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z106.object({branch:branchSchema,conflicts:z106.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z106.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z106.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z106.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z106.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z106.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,path:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path50,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path50,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,collection:z106.string().min(1),rowId:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,locale:z106.string().min(1),key:z106.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,formName:z106.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z106.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z106.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId,mergeId})=>({method:"GET",path:managementProjectPath(projectId,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z106.object({ok:z106.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z106.object({ok:z106.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z106.array(conflictResolutionSchema)}).strict(),outputSchema:z106.object({mergeId:uuidSchema,lastEditedAt:z106.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z106.object({mergeId:uuidSchema,lastEditedAt:z106.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z106.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path50})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path50})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z107}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z107.object({id:z107.string(),hostname:z107.string(),status:z107.string(),ssl:z107.record(z107.string(),z107.unknown()),cnameTarget:z107.string(),apexTargets:z107.array(z107.string()),dnsAutoConfigured:z107.boolean(),createdAt:z107.unknown(),provider:z107.enum(["cloudflare","saas_custom_domains"]),domainType:z107.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z107.object({id:uuidSchema,domain:z107.string(),status:z107.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z107.enum(["fimo","external"]),autoRenew:z107.boolean(),paymentStatus:z107.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z107.string().nullable()}).passthrough(),domainSearchResultSchema=z107.object({domain:z107.string(),available:z107.boolean(),premium:z107.boolean(),price:z107.number().nullable(),renewalPrice:z107.number().nullable(),purchaseType:z107.string().nullable()}).passthrough(),domainPricingSchema=z107.object({domain:z107.string(),price:z107.number().nullable(),renewalPrice:z107.number().nullable(),premium:z107.boolean(),allowedYears:z107.array(z107.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z107.object({}).strict(),outputSchema:z107.object({domainPurchaseEnabled:z107.boolean(),publicationDomain:z107.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,slug:z107.string().min(1).max(63)}).strict(),outputSchema:z107.object({subdomain:z107.string(),subdomainUpdatedAt:z107.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,base:z107.string().min(1).max(63).optional(),max:z107.number().int().positive().optional()}).strict(),outputSchema:z107.array(z107.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z107.object({data:z107.object({suggestions:z107.array(z107.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema}).strict(),outputSchema:z107.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,hostname:z107.string().min(1).max(255),redirectToWww:z107.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,domainId:z107.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,domainId:z107.string().min(1)}).strict(),outputSchema:z107.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z107.object({keyword:z107.string().min(1).max(100),tldFilter:z107.array(z107.string().min(1)).optional()}).strict(),outputSchema:z107.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z107.object({domain:z107.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z107.object({organizationId:z107.string().min(1)}).strict(),outputSchema:z107.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z107.object({organizationId:z107.string().min(1),domain:z107.string().min(1).max(255),years:z107.number().int().min(1).max(10).optional(),autoRenew:z107.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z107.object({organizationId:z107.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z108}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z108.object({id:z108.string(),entryId:z108.string(),documentId:z108.string(),slug:z108.string(),locale:z108.string().optional(),createdAt:z108.string(),updatedAt:z108.string(),__fimo:z108.object({contentType:z108.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({limit:z108.number(),offset:z108.number(),total:z108.number(),hasMore:z108.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z108.union([z108.string(),z108.number(),z108.boolean(),z108.null()]),entryWhereOperatorSchema2=z108.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z108.array(entryWhereScalarSchema2).optional(),$nin:z108.array(entryWhereScalarSchema2).optional(),$contains:z108.string().optional(),$startsWith:z108.string().optional(),$null:z108.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z108.record(z108.string(),z108.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z108.record(z108.string(),z108.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z108.object({data:z108.record(z108.string(),z108.unknown()),locale:z108.string().min(1).optional(),documentId:z108.uuid().optional()}),BulkCreateEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({created:z108.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({updated:z108.number().int().nonnegative(),missing:z108.array(z108.string())})}),BulkDeleteEntriesResponseSchema2=z108.object({data:z108.array(EntryDTOSchema2),meta:z108.object({deleted:z108.number().int().nonnegative(),missing:z108.array(z108.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z108.string().min(1).max(255),localeSchema=z108.string().min(1),populateSchema=z108.array(z108.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z108.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,search:z108.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z108.string().min(1).max(255),data:entryDataSchema,locale:z108.string().min(1).optional(),documentId:z108.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z108.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z108.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z108.record(z108.string(),z108.unknown())}).strict(),outputSchema:z108.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z108.object({data:z108.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,sql:z108.string().min(1)}).strict(),outputSchema:z108.object({data:z108.array(z108.record(z108.string(),z108.unknown())),meta:z108.object({rowCount:z108.number().int().nonnegative(),truncated:z108.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z108.array(z108.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z108.union([z108.object({ids:z108.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z108.object({where:EntryWhereSchema2}),z108.object({updates:z108.array(z108.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z108.union([z108.object({ids:z108.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z108.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z109}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z109.object({id:z109.literal("production"),projectId:uuidSchema,name:z109.string(),kind:z109.literal("production"),sourceBranch:z109.string().min(1),isPublished:z109.boolean(),url:z109.string().nullable()}),previewEnvironmentSchema=z109.object({id:z109.literal("preview"),projectId:uuidSchema,name:z109.string(),kind:z109.literal("preview"),matchedBranchCount:z109.number().int().nonnegative()}),customEnvironmentSchema=z109.object({id:uuidSchema,projectId:uuidSchema,name:z109.string().min(1).max(64),branchPatterns:z109.array(z109.string().min(1).max(255)).min(1),description:z109.string().max(255).nullable(),kind:z109.literal("custom"),matchedBranchCount:z109.number().int().nonnegative()}),environmentSchema=z109.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z109.string().trim().min(1).max(64),branchPatterns:z109.array(z109.string().min(1).max(255)).min(1),description:z109.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z109.object({projectId:uuidSchema}).strict(),outputSchema:z109.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z109.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,environmentId:z109.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,environmentId:z109.string().min(1)}).strict(),outputSchema:z109.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z109.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z110}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z110.object({data:z110.object({path:z110.string(),content:z110.string(),totalLines:z110.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z110.object({data:z110.object({paths:z110.array(z110.string().min(1)).max(2e3),truncated:z110.boolean()})}),fileGrepOutputSchema=z110.object({data:z110.object({matches:z110.array(z110.object({path:z110.string().min(1),line:z110.number().int().positive(),text:z110.string()})).max(200),truncated:z110.boolean()})}),fileWriteInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z110.boolean().optional()}).strict(),fileEditInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z110.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),created:z110.boolean(),tip:z110.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z110.object({projectId:uuidSchema,sessionId:uuidSchema,files:z110.array(z110.object({path:z110.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files2=>files2.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z110.array(z110.object({path:z110.string(),created:z110.boolean()}).passthrough()),tip:z110.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),replacements:z110.number().int().nonnegative(),tip:z110.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z110.object({path:z110.string(),deleted:z110.literal(!0),tip:z110.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z110.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z110.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path50})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path50})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z110.object({...fileSearchInputShape,pattern:z110.string().min(1).max(300).optional(),limit:z110.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z110.object({...fileSearchInputShape,pattern:z110.string().min(1).max(200),include:z110.string().min(1).max(300).optional(),caseInsensitive:z110.boolean().optional(),maxMatches:z110.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path50,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path50,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z110.object({projectId:uuidSchema,sessionId:uuidSchema,path:z110.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path50})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path50}}),"buildRequest")}}}});import{z as z111}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z111.object({data:z111.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z111.object({data:z111.array(formSubmissionSchema),total:z111.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z111.object({type:z111.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z111.string(),placeholder:z111.string().optional(),required:z111.boolean().optional(),defaultValue:z111.string().optional(),options:z111.array(z111.string()).optional(),validation:z111.object({minLength:z111.number().optional(),maxLength:z111.number().optional(),min:z111.number().optional(),max:z111.number().optional(),pattern:z111.string().optional(),maxFileSize:z111.number().optional(),accept:z111.array(z111.string()).optional()}).optional()}),FormContentSchema2=z111.object({name:z111.string().min(1).max(255),label:z111.string().min(1).max(255),fields:z111.record(z111.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z111.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z111.record(z111.string(),z111.unknown()).nullable().optional(),createdAt:z111.string(),updatedAt:z111.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z111.object({data:formSchema}),formSubmissionSchema=z111.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z111.record(z111.string(),z111.unknown()),submittedAt:z111.string()}),formSubmissionResponseSchema=z111.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z111.object({data:z111.object({total:z111.number().int().nonnegative(),dailyCounts:z111.array(z111.object({date:z111.string(),count:z111.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z111.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),...paginationShape,searchQuery:z111.string().max(200).optional(),sortDirection:z111.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),submissionId:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,id:z111.string().min(1).max(255),submissionId:z111.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z112}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z112.object({costUsd:z112.number(),credits:z112.number().optional(),billingMode:z112.enum(["fimo-credits","provider-account"]).optional(),confidence:z112.enum(["exact","estimated","metered"]),basis:z112.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,model:z112.string().min(1),options:z112.record(z112.string(),z112.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,branch:branchNameSchema,task:z112.string().min(1),options:z112.record(z112.string(),z112.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z113}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z113.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z113.object({versionId:uuidSchema,commitHash:z113.string(),name:z113.string(),description:z113.string().nullable(),kind:historyKindSchema,createdAt:z113.iso.datetime(),expiresAt:z113.iso.datetime()}),projectVersionPageSchema=z113.object({items:z113.array(projectVersionSchema),nextCursor:z113.string().nullable()}),historySummarySchema=z113.object({usage:z113.object({versionCount:z113.number().int().nonnegative(),snapshotBytes:z113.number().int().nonnegative()}),retentionDays:z113.number().int().positive()}),restoreResultSchema=z113.object({durationMs:z113.number().nonnegative().optional(),warning:z113.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,limit:z113.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,name:z113.string().min(1),description:z113.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z114}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z114.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z114.object({isPublished:z114.boolean(),publishedAt:z114.iso.datetime().nullable(),publishedVersion:z114.string().nullable()}),publicationOutputSchema=z114.object({id:uuidSchema,status:z114.enum(["queued","building","published","failed","canceled"]),label:z114.string().nullable(),notes:z114.string().nullable(),source:z114.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z114.string().nullable(),framework:z114.string().nullable(),commit:z114.string().nullable()}),createdAt:z114.iso.datetime(),finishedAt:z114.iso.datetime().nullable(),url:z114.string().nullable(),failureCode:z114.string().nullable()}),publicationsPageOutputSchema=z114.object({items:z114.array(publicationOutputSchema),nextCursor:z114.string().nullable(),retention:z114.object({scope:z114.literal("publication_attempt_record"),records:z114.literal("project_lifetime")})}),publicationLogsOutputSchema=z114.object({status:z114.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z114.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z114.string().nullable(),items:z114.array(z114.object({timestamp:z114.iso.datetime(),phase:z114.enum(["build","deploy"]),stream:z114.enum(["command","stdout","stderr","status","error"]),message:z114.string()}))}),sandboxLogsOutputSchema=z114.object({status:z114.enum(["ok","unavailable"]),reason:z114.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z114.string().nullable(),items:z114.array(z114.object({id:z114.string(),timestamp:z114.iso.datetime().nullable(),source:z114.enum(["install","dev-server"]),phase:z114.string(),stream:z114.enum(["combined","stdout","stderr"]),message:z114.string()})),nextCursor:z114.string().nullable(),retention:z114.object({scope:z114.literal("sandbox_process_snapshot"),timestamps:z114.literal("process_start"),droppedOldest:z114.boolean(),phases:z114.array(z114.object({phase:z114.string(),source:z114.enum(["install","dev-server"]),status:z114.string(),startedAt:z114.iso.datetime().nullable(),exitCode:z114.number().int().nullable(),events:z114.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z114.object({url:z114.string(),branch:branchNameSchema}),previewOpenOutputSchema=z114.object({url:z114.url(),expiresAt:z114.iso.datetime().nullable()}),publishOutputSchema=z114.object({success:z114.boolean(),message:z114.string().optional(),firstPublish:z114.boolean(),publicationId:z114.string().optional(),url:z114.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,limit:z114.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,publicationId:z114.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,label:z114.string().trim().min(1).max(120).optional(),notes:z114.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,publicationId:z114.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z115}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z115.object({content:z115.string(),updatedAt:z115.string().nullable(),updatedBy:z115.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z115.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,content:z115.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z116}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z116.object({key:z116.string(),value:z116.string().optional(),defaultValue:z116.string(),locale:z116.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z116.object({data:z116.array(z116.union([TranslationDTOSchema2,z116.object({key:z116.string(),values:z116.record(z116.string(),z116.string())})]))}),labelUpsertOutputSchema=z116.object({created:z116.number().int().nonnegative(),updated:z116.number().int().nonnegative(),deleted:z116.number().int().nonnegative(),defaultLocale:z116.string(),locales:z116.array(z116.string())}),labelDeleteOutputSchema=z116.object({key:z116.string(),locale:z116.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z116.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,key:z116.string(),value:z116.string(),locale:z116.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,records:z116.array(z116.object({key:z116.string(),value:z116.string(),locale:z116.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,locale:z116.string().optional(),key:z116.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z117}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z117.object({translated:z117.number().int().nonnegative(),total:z117.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z117.object({defaultLocale:z117.string(),locales:z117.array(z117.object({locale:z117.string(),isDefault:z117.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z117.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z117.object({locale:z117.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z117.object({locale:z117.string(),entriesDeleted:z117.number().int().nonnegative(),labelsDeleted:z117.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z117.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z118}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z118.object({id:z118.string().min(1),name:z118.string(),slug:z118.string()}),organizationMemberSchema=z118.object({id:z118.string().min(1),role:z118.string(),createdAt:z118.string().optional(),user:z118.object({id:z118.string().min(1),name:z118.string().nullable().optional(),email:z118.string().nullable().optional()}).optional()}),organizationInvitationSchema=z118.object({id:z118.string().min(1),email:z118.email(),role:z118.string(),organizationId:z118.string().min(1),inviterId:z118.string().min(1),status:z118.string(),expiresAt:z118.string(),createdAt:z118.string()}).passthrough(),referralSummarySchema=z118.object({counts:z118.object({signed_up:z118.number().int(),activated:z118.number().int()}),credits:z118.object({total:z118.number().int(),earned:z118.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z118.object({}).strict(),outputSchema:createResponseSchema2(z118.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z118.object({organizationId:z118.string().min(1)}).strict(),outputSchema:z118.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z118.object({members:z118.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z118.object({organizationId:z118.string().min(1),email:z118.email(),role:z118.enum(["owner","admin","member"]),resend:z118.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z118.object({userId:z118.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z119}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z119.object({id:uuidSchema,name:z119.string(),displayName:z119.string().nullable(),organizationId:z119.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z119.string().optional(),appUrl:z119.string().nullable().optional()}).passthrough(),projectResponseSchema=z119.object({data:projectSchema}),transferResultSchema=z119.object({projectId:z119.string(),sourceOrganizationId:z119.string(),targetOrganizationId:z119.string(),movedThreads:z119.number().int().nonnegative(),revokedInvites:z119.number().int().nonnegative(),revokedGrants:z119.number().int().nonnegative(),preservedGrants:z119.number().int().nonnegative(),warnings:z119.array(z119.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z119.object({organizationId:z119.string().min(1).optional()}).strict(),outputSchema:z119.object({data:z119.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z119.object({organizationId:z119.string().min(1),displayName:z119.string().min(1).optional(),origin:z119.enum(["scratch","migration"]).optional(),starter:z119.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,targetOrganizationId:z119.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema,email:z119.email(),role:z119.enum(["full","edit","comment","view"])}).strict(),outputSchema:z119.object({id:z119.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z119.object({id:z119.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z119.object({projectId:uuidSchema}).strict(),outputSchema:z119.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z120}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z120.iso.datetime(),scheduleStatusSchema=z120.enum(["ok","failed"]),runStatusSchema=z120.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z120.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z120.string().min(1),name:z120.string().min(1),cron:z120.string().min(1),command:z120.string().min(1),secretKeys:z120.array(z120.string().min(1)),enabled:z120.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z120.string().nullable(),overPolicyReasons:z120.array(z120.string()).optional()}).passthrough(),usageSchema=z120.object({runCount:z120.number().int().nonnegative(),runsWithOutput:z120.number().int().nonnegative()}),policySchema=z120.object({maxRuns:z120.number().int().positive(),retentionDays:z120.number().int().positive().nullable(),outputRetentionDays:z120.number().int().positive(),maxOutputBytes:z120.number().int().positive()}).passthrough(),planSchema=z120.object({code:z120.enum(["Free","PAYG","Premium","Pro"]),source:z120.enum(["cached_subscription","free_fallback"]),activeSchedules:z120.object({used:z120.number().int().nonnegative(),limit:z120.number().int().positive()}),minCadenceMinutes:z120.number().int().positive(),maxRunMs:z120.number().int().positive(),concurrency:z120.object({used:z120.number().int().nonnegative(),limit:z120.number().int().positive()}),compute:z120.object({settledMs:z120.number().int().nonnegative(),activeMs:z120.number().int().nonnegative(),reservedMs:z120.number().int().nonnegative().optional(),includedMs:z120.number().int().positive(),remainingMs:z120.number().int().nonnegative(),resetsAt:dateSchema}),state:z120.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z120.array(z120.string())}).passthrough(),runSchema=z120.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z120.string().min(1),scheduleName:z120.string().min(1),command:z120.string().min(1),status:runStatusSchema,trigger:z120.enum(["cron","ui","cli"]),triggeredBy:z120.object({id:z120.string().min(1),name:z120.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z120.number().int().nullable(),errorCode:z120.string().nullable(),error:z120.string().nullable(),outputBytes:z120.number().int().nonnegative(),outputTruncated:z120.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z120.string().nullable(),secretSnapshot:z120.object({state:z120.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z120.array(z120.object({key:z120.string().min(1),updatedAt:dateSchema.nullable(),resolution:z120.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z120.object({items:z120.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z120.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z120.object({items:z120.array(runSchema),nextCursor:z120.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z120.string().min(1).max(120),cron:z120.string().min(1).max(120),command:z120.string().min(1).max(500),secretKeys:z120.array(z120.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape}).strict(),outputSchema:z120.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z120.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,...scheduleWriteShape,enabled:z120.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z120.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z120.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z120.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z120.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z120.object({ok:z120.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z121}from"zod";function projectSchemaDefinition(body){return z121.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z121.object({id:z121.string(),name:z121.string(),label:z121.string(),isSingleton:z121.boolean(),slugUnique:z121.boolean(),i18n:z121.record(z121.string(),z121.unknown()),groups:z121.array(z121.record(z121.string(),z121.unknown())),fields:z121.record(z121.string(),z121.unknown()),createdAt:z121.string(),updatedAt:z121.string()}).passthrough(),schemaListOutputSchema=z121.object({contentTypes:z121.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z121.object({typeName:z121.string().min(1).max(255),generatedPaths:z121.array(z121.string().min(1)).max(1e3),tip:z121.string().min(1)})}),schemaDefinitionInputSchema=z121.record(z121.string(),z121.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z121.array(schemaDefinitionInputSchema).min(1).max(100),operations:z121.array(z121.record(z121.string(),z121.unknown())).optional()}).strict(),outputSchema:z121.array(z121.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z121.object({data:z121.array(z121.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:z121.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z121.object({data:z121.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z121.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z121.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z121.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z122}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z122.union([z122.literal("production"),z122.literal("preview"),uuidSchema]),secretKindSchema=z122.enum(["variable","secret"]),projectSecretSchema=z122.object({id:z122.string().min(1),projectId:z122.string().min(1),key:z122.string().min(1),kind:secretKindSchema,exposure:z122.enum(["public","private"]),environment:environmentSchema2,value:z122.string().optional(),maskedValue:z122.string().optional(),createdAt:z122.string(),updatedAt:z122.string()}),secretWriteInputSchema=z122.object({projectId:uuidSchema,key:z122.string().min(1).max(255),kind:secretKindSchema,value:z122.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z122.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z122.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z122.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,key:z122.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z122.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,branch:z122.string().min(1)}).strict(),outputSchema:z122.object({branch:z122.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z122.array(z122.object({branch:z122.string().optional(),env:z122.string().optional(),parentBranch:z122.string().nullable().optional(),parentEnv:z122.string().nullable().optional(),resolvedEnvironment:z122.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z123}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z123.object({status:z123.literal("passed")}).passthrough(),sessionConflictSummarySchema=z123.object({surface:surfaceNameSchema,key:z123.string().min(1),kind:z123.string().optional(),description:z123.string(),path:z123.string().optional()}).passthrough(),surfaceDeltaItemSchema=z123.object({verb:z123.enum(["added","removed","changed","conflict"]),key:z123.string(),detail:z123.string().optional(),origin:z123.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z123.record(z123.string(),z123.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z123.object({surface:surfaceNameSchema,status:z123.enum(["ok","timed_out","failed","unchanged"]),durationMs:z123.number().int().nonnegative().optional(),changedCount:z123.number().int().nonnegative(),conflictCount:z123.number().int().nonnegative(),items:z123.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z123.boolean().optional(),error:z123.string().optional()}).passthrough(),sessionChangesSchema=z123.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z123.iso.datetime(),surfaces:z123.array(perSurfaceDeltaSchema),crossSurface:z123.array(crossSurfaceFindingSchema).optional(),fingerprint:z123.string()}).passthrough(),projectScriptStatusSchema=z123.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z123.discriminatedUnion("operation",[z123.object({operation:z123.literal("dependencies_install"),repairedInstallPolicy:z123.boolean(),tip:z123.string()}),z123.object({operation:z123.literal("schemas_sync"),tip:z123.string()}),z123.object({operation:z123.literal("typecheck"),status:projectScriptStatusSchema,output:z123.string()}),z123.object({operation:z123.literal("lint"),status:projectScriptStatusSchema,output:z123.string()})]),conflictSchema2=z123.object({surface:surfaceNameSchema,key:z123.string(),kind:z123.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z123.string(),parentValue:z123.unknown().optional(),childValue:z123.unknown().optional(),conflictingFields:z123.array(z123.string()).optional(),code:z123.object({path:z123.string(),unresolvable:z123.boolean().optional(),reason:z123.string().optional(),targetCommits:z123.array(z123.object({sha:z123.string(),subject:z123.string(),body:z123.string().optional(),author:z123.string(),date:z123.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z123.object({oid:z123.string().optional(),content:z123.string().optional(),truncated:z123.boolean(),binary:z123.boolean()}),codeConflictDetailSchema=z123.object({path:z123.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z123.string(),targetTipSha:z123.string(),mergeBaseSha:z123.string().optional()}),resolutionChoiceSchema=z123.enum(["parent","child","pick"]),conflictResolutionSchema2=z123.object({surface:surfaceNameSchema,key:z123.string().min(1),choice:resolutionChoiceSchema,pickedValue:z123.unknown().optional(),fieldPicks:z123.array(z123.object({field:z123.string().min(1),choice:resolutionChoiceSchema,pickedValue:z123.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z123.string().trim().min(1).max(120).optional(),goal:z123.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z123.object({session:sessionEnvelopeSchema,adopted:z123.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z123.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z123.number().int().min(1).max(100).optional()}).strict(),outputSchema:z123.object({items:z123.array(sessionEnvelopeSchema),nextCursor:z123.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z123.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z123.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z123.object({requested:z123.literal(!0),alreadyRequested:z123.boolean(),reviewId:uuidSchema,reviewUrl:z123.url(),status:z123.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z123.string().min(1),savedRevision:z123.string().min(1),fingerprint:z123.string().min(1),visibility:z123.literal("user-visible"),retention:z123.literal("durable"),expiresAt:z123.null(),merged:z123.literal(!1),published:z123.literal(!1),links:z123.object({preview:z123.url(),changes:z123.url(),conversation:z123.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z123.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z123.literal("temporary"),visibility:z123.enum(["internal","user-visible"]),expiresAt:z123.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z123.string().min(1).max(100),args:z123.record(z123.string(),z123.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,action:z123.enum(["merge","discard"]),message:z123.string().max(1e3).optional(),description:z123.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z123.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z123.boolean(),mergeId:uuidSchema.optional(),conflictCount:z123.number().int().nonnegative().optional(),conflicts:z123.array(sessionConflictSummarySchema).optional(),parentAdvanced:z123.boolean().optional(),code:z123.string().optional(),summary:z123.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z123.number().int().min(1).max(100).optional(),codePath:z123.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z123.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z123.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z123.number().int().nonnegative(),error:z123.string().nullable()}),conflicts:z123.array(conflictSchema2).max(100),nextCursor:z123.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z123.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z123.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z123.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z124}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z124.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z125}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z125.object({message:z125.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z125.object({id:uuidSchema,deliveryStatus:z125.enum(["pending","delivered","failed"]),message:z125.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z125.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z126}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z126.record(z126.string(),z126.unknown()),deliveryStatusSchema=z126.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z126.object({id:uuidSchema,projectId:uuidSchema,name:z126.string(),eventType:z126.string().min(1),enabled:z126.boolean(),destination:z126.object({host:z126.string(),maskedUrl:z126.string(),kind:z126.string()}),filter:jsonObjectSchema,headers:z126.array(jsonObjectSchema),bodyTemplate:z126.unknown().nullable(),signingEnabled:z126.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z126.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z126.string().min(1),status:deliveryStatusSchema,attemptCount:z126.number().int().nonnegative(),responseStatus:z126.number().int().nullable(),createdAt:z126.iso.datetime()}).passthrough(),attemptSchema=z126.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z126.number().int().positive(),status:z126.enum(["delivering","succeeded","failed"]),createdAt:z126.iso.datetime()}).passthrough(),deliveriesPageSchema=z126.object({items:z126.array(deliverySchema),pagination:z126.object({page:z126.number().int().positive(),limit:z126.number().int().positive(),total:z126.number().int().nonnegative(),totalPages:z126.number().int().positive(),hasMore:z126.boolean()}),stats:z126.object({total:z126.number().int().nonnegative(),succeeded:z126.number().int().nonnegative(),failed:z126.number().int().nonnegative()})}),eventSchema=z126.object({type:z126.string().min(1),family:z126.string(),description:z126.string(),variables:z126.array(z126.string()),data:z126.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema}).strict(),outputSchema:z126.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z126.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema}).strict(),outputSchema:z126.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z126.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z126.object({webhook:webhookSchema,signingSecret:z126.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z126.object({webhook:webhookSchema,signingSecret:z126.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z126.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z126.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z126.object({signingSecret:z126.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z126.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z126.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z126.object({delivery:deliverySchema,attempts:z126.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z126.object({delivery:deliverySchema,attempts:z126.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z126.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z127.object({id:z127.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z127.string().min(1),summary:z127.string().min(1),accessScope:z127.enum(["read","write","code","agents"]),effect:z127.enum(["read","mutation"]),inputJsonSchema:z127.record(z127.string(),z127.unknown()),outputJsonSchema:z127.record(z127.string(),z127.unknown())}).strict(),fimoOperationManifestSchema=z127.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z127.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z127.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.join(root,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path4 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue2=>{let{path:path50,message}=issue2;return`${Array.isArray(path50)&&path50.length>0?`${path50.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path50,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path50}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path50,init={},options={}){let response=await send(path50,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path50,init={}){let response=await send(path50,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path50,status,detail,code2,body){super(`API ${method} ${path50} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path50,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required,this.code=server.code,this.detail=server.detail}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument;exports2.isMap=isMap;exports2.isNode=isNode;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path50){let ctrl=callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visit_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=visit_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path50){let ctrl=await callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visitAsync_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=await visitAsync_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path50){if(typeof visitor=="function")return visitor(key,node,path50);if(identity2.isMap(node))return visitor.Map?.(key,node,path50);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path50);if(identity2.isPair(node))return visitor.Pair?.(key,node,path50);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path50);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path50)}__name(callVisitor,"callVisitor");function replaceNode(key,path50,node){let parent=path50[path50.length-1];if(identity2.isCollection(parent))parent.items[key]=node;else if(identity2.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity2.isDocument(parent))parent.contents=node;else{let pt2=identity2.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
45
45
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports2.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/anchors.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}__name(anchorIsValid,"anchorIsValid");function anchorNames(root){let anchors=new Set;return visit2.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}__name(anchorNames,"anchorNames");function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}__name(findNewAnchor,"findNewAnchor");function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:__name(source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},"onAnchor"),setAnchors:__name(()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity2.isScalar(ref.node)||identity2.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},"setAnchors"),sourceObjects}}__name(createNodeAnchors,"createNodeAnchors");exports2.anchorIsValid=anchorIsValid;exports2.anchorNames=anchorNames;exports2.createNodeAnchors=createNodeAnchors;exports2.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/applyReviver.js"(exports2){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val=="object")if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}__name(applyReviver,"applyReviver");exports2.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/toJS.js"(exports2){"use strict";var identity2=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity2.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res2=>{data.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}__name(toJS,"toJS");exports2.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Node.js"(exports2){"use strict";var applyReviver=require_applyReviver(),identity2=require_identity(),toJS=require_toJS(),NodeBase=class{static{__name(this,"NodeBase")}constructor(type){Object.defineProperty(this,identity2.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity2.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports2.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Alias.js"(exports2){"use strict";var anchors=require_anchors(),visit2=require_visit(),identity2=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{static{__name(this,"Alias")}constructor(source){super(identity2.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit2.visit(doc,{Node:__name((_key,node)=>{(identity2.isAlias(node)||identity2.hasAnchor(node))&&nodes.push(node)},"Node")}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors:anchors2,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors2.get(source);if(data||(toJS.toJS(source,null,ctx),data=anchors2.get(source)),data?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc,source,anchors2)),data.count*data.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}return data.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity2.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity2.isCollection(node)){let count=0;for(let item of node.items){let c2=getAliasCount(doc,item,anchors2);c2>count&&(count=c2)}return count}else if(identity2.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}__name(getAliasCount,"getAliasCount");exports2.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Scalar.js"(exports2){"use strict";var identity2=require_identity(),Node=require_Node(),toJS=require_toJS(),isScalarValue=__name(value=>!value||typeof value!="function"&&typeof value!="object","isScalarValue"),Scalar=class extends Node.NodeBase{static{__name(this,"Scalar")}constructor(value){super(identity2.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports2.Scalar=Scalar;exports2.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/createNode.js"(exports2){"use strict";var Alias=require_Alias(),identity2=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t2=>t2.tag===tagName),tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}__name(findTagObject,"findTagObject");function createNode(value,tagName,ctx){if(identity2.isDocument(value)&&(value=value.contents),identity2.isNode(value))return value;if(identity2.isPair(value)){let map=ctx.schema[identity2.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity2.MAP]:Symbol.iterator in Object(value)?schema[identity2.SEQ]:schema[identity2.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}__name(createNode,"createNode");exports2.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Collection.js"(exports2){"use strict";var createNode=require_createNode(),identity2=require_identity(),Node=require_Node();function collectionFromPath(schema,path50,value){let v=value;for(let i=path50.length-1;i>=0;--i){let k=path50[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:__name(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema,sourceObjects:new Map})}__name(collectionFromPath,"collectionFromPath");var isEmptyPath=__name(path50=>path50==null||typeof path50=="object"&&!!path50[Symbol.iterator]().next().done,"isEmptyPath"),Collection=class extends Node.NodeBase{static{__name(this,"Collection")}constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it2=>identity2.isNode(it2)||identity2.isPair(it2)?it2.clone(schema):it2),this.range&&(copy.range=this.range.slice()),copy}addIn(path50,value){if(isEmptyPath(path50))this.add(value);else{let[key,...rest]=path50,node=this.get(key,!0);if(identity2.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path50){let[key,...rest]=path50;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity2.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path50,keepScalar){let[key,...rest]=path50,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity2.isScalar(node)?node.value:node:identity2.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity2.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity2.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path50){let[key,...rest]=path50;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity2.isCollection(node)?node.hasIn(rest):!1}setIn(path50,value){let[key,...rest]=path50;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity2.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports2.Collection=Collection;exports2.collectionFromPath=collectionFromPath;exports2.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyComment.js"(exports2){"use strict";var stringifyComment=__name(str=>str.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}__name(indentComment,"indentComment");var lineComment=__name((str,indent,comment)=>str.endsWith(`
|
|
46
46
|
`)?indentComment(comment,indent):comment.includes(`
|
|
47
47
|
`)?`
|
|
@@ -421,7 +421,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
421
421
|
${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
|
|
422
422
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path50=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path50,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch),git=createGitService(loadConfig(),ctx.branch),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(git,ctx.projectId,ctx.branch,cwd),serverPromise=withSoftTimeout(fimo.execute("branches.status",{projectId:ctx.projectId,branch:ctx.branch,against:options.vs,surfaces:surfaces?.map(surface=>surface==="translations"?"labels":surface)}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let portableServer=serverResult.value,server={branch:portableServer.branch,env:portableServer.branch,vs:portableServer.against,syncState:portableServer.syncState??(portableServer.state==="clean"?"in-sync":"diverged"),generatedAt:portableServer.generatedAt,surfaces:portableServer.surfaces.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),crossSurface:portableServer.crossSurface?.map(finding=>({...finding,source:{...finding.source,surface:finding.source.surface==="labels"?"translations":finding.source.surface},target:{...finding.target,surface:finding.target.surface==="labels"?"translations":finding.target.surface}}))},serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
|
|
423
423
|
|
|
424
|
-
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project2();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_esm();init_dist();import fs48 from"node:fs";import path49 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_config();init_sdk_transport();import{existsSync}from"node:fs";var import_yaml=__toESM(require_dist(),1);import{z as z128}from"zod";var CapabilityTokenSchema=z128.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z128.array(CapabilityTokenSchema);import{z as z129}from"zod";var CronTriggerSchema=z129.object({type:z129.literal("schedule"),cron:z129.string().min(1,"cron expression required"),tz:z129.string().optional()}),ManualTriggerSchema=z129.object({type:z129.literal("manual")}),WebhookTriggerSchema=z129.object({type:z129.literal("webhook"),path:z129.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z129.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z129.object({name:z129.string().min(1),capability_grant:z129.enum(["inherit","explicit"]).optional(),explicit_grants:z129.array(z129.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z129.object({"sub-agents":z129.array(SubAgentRefSchema)}),RuntimeConfigSchema=z129.object({cloud:z129.boolean().optional(),dev:z129.boolean().optional(),max_credits:z129.number().int().min(1).optional(),max_steps:z129.number().int().min(1).optional()}),DataSourceSchema=z129.enum(["main","prod"]),ConfigValueKeySchema=z129.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z129.preprocess(value=>typeof value=="string"?{key:value}:value,z129.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z129.boolean().default(!0),delivery:z129.literal("process_env").default("process_env")})),IntegrationKeySchema=z129.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z129.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z129.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z129.object({enabled:z129.boolean().default(!0),tools:z129.record(IntegrationToolKeySchema,z129.boolean()).optional()})),IntegrationPolicySchema=z129.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z129.object({version:z129.literal(1),description:z129.string().min(1).max(280).optional(),model:z129.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z129.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z129.array(DataSourceSchema).optional(),secrets:z129.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z130}from"zod";var SurfaceGuardPolicySchema=z130.enum(["block","warn","allow"]),ClassificationSchema=z130.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z130.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z130.object({enabled:z130.boolean(),allowed_skills:z130.array(z130.string().min(1)).default([]),allowed_classifications:z130.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z130.enum(["off","daily","weekly"]),NotificationFormatSchema=z130.object({markdown:z130.boolean().default(!0),html:z130.boolean().default(!1)}),NotificationsPolicySchema=z130.object({email_recipients:z130.array(z130.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z130.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z130.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();import{z as z131}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z131.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z131.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"agents.list":"agents:read","agents.routines":"agents:read","agents.routine_runs":"agents:read","knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.site.check":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
|
|
424
|
+
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project2();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_esm();init_dist();import fs48 from"node:fs";import path49 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_config();init_sdk_transport();import{existsSync}from"node:fs";var import_yaml=__toESM(require_dist(),1);import{z as z128}from"zod";var CapabilityTokenSchema=z128.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z128.array(CapabilityTokenSchema);import{z as z129}from"zod";var CronTriggerSchema=z129.object({type:z129.literal("schedule"),cron:z129.string().min(1,"cron expression required"),tz:z129.string().optional()}),ManualTriggerSchema=z129.object({type:z129.literal("manual")}),WebhookTriggerSchema=z129.object({type:z129.literal("webhook"),path:z129.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z129.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z129.object({name:z129.string().min(1),capability_grant:z129.enum(["inherit","explicit"]).optional(),explicit_grants:z129.array(z129.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z129.object({"sub-agents":z129.array(SubAgentRefSchema)}),RuntimeConfigSchema=z129.object({cloud:z129.boolean().optional(),dev:z129.boolean().optional(),max_credits:z129.number().int().min(1).optional(),max_steps:z129.number().int().min(1).optional()}),DataSourceSchema=z129.enum(["main","prod"]),ConfigValueKeySchema=z129.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z129.preprocess(value=>typeof value=="string"?{key:value}:value,z129.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z129.boolean().default(!0),delivery:z129.literal("process_env").default("process_env")})),IntegrationKeySchema=z129.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z129.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z129.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z129.object({enabled:z129.boolean().default(!0),tools:z129.record(IntegrationToolKeySchema,z129.boolean()).optional()})),IntegrationPolicySchema=z129.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z129.object({version:z129.literal(1),description:z129.string().min(1).max(280).optional(),model:z129.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z129.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z129.array(DataSourceSchema).optional(),secrets:z129.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z130}from"zod";var SurfaceGuardPolicySchema=z130.enum(["block","warn","allow"]),ClassificationSchema=z130.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z130.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z130.object({enabled:z130.boolean(),allowed_skills:z130.array(z130.string().min(1)).default([]),allowed_classifications:z130.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z130.enum(["off","daily","weekly"]),NotificationFormatSchema=z130.object({markdown:z130.boolean().default(!0),html:z130.boolean().default(!1)}),NotificationsPolicySchema=z130.object({email_recipients:z130.array(z130.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z130.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z130.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();import{z as z131}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z131.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z131.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"agents.list":"agents:read","agents.routines":"agents:read","knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.site.check":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
|
|
425
425
|
// Every fact is fine, broken, or unknown (could not tell); only broken leads to a finding.
|
|
426
426
|
import { spawn, spawnSync } from 'node:child_process';
|
|
427
427
|
import crypto from 'node:crypto';
|
|
@@ -953,8 +953,7 @@ async function httpFacts(url) {
|
|
|
953
953
|
// Browser sessions that visit pages at once (--parallel): fimo-site, fimo-site-2, ... A session agent-browser fails on
|
|
954
954
|
// twice in a row is closed and the crawl goes on with the others, down to one. One by default: several routines crawl
|
|
955
955
|
// the same sandbox at once after a change, and five sessions each ran its 6 GB out of memory on an 89-page site.
|
|
956
|
-
|
|
957
|
-
const SESSIONS = Array.from({ length: Math.max(1, Math.floor(Number(opt('parallel', HTTP ? 6 : 1))) || 1) }, (_, i) => (i ? SESSION + '-' + (i + 1) : SESSION));
|
|
956
|
+
const SESSIONS = Array.from({ length: Math.max(1, Math.floor(Number(opt('parallel', 1))) || 1) }, (_, i) => (i ? SESSION + '-' + (i + 1) : SESSION));
|
|
958
957
|
const pool = { free: SESSIONS.slice(), live: SESSIONS.slice(), waiting: [], strikes: {}, dropped: [], used: new Set() };
|
|
959
958
|
// A free session, other than avoid while another one lives.
|
|
960
959
|
const fits = (s, avoid) => s !== avoid || pool.live.length === 1;
|
|
@@ -1406,8 +1405,6 @@ async function crawl() {
|
|
|
1406
1405
|
else ['/', ...site.sitemap].forEach(add);
|
|
1407
1406
|
// Pages only llms.txt names are visited to learn whether they exist, like translations nothing links to.
|
|
1408
1407
|
if (!named) for (const p of llmsLinks(site.llms.body).map(toPath).filter(Boolean)) if (!seen.has(p)) { llmsOnly.add(p); add(p); }
|
|
1409
|
-
// --pages: the pages llms.txt names get their status, so a check of named pages settles its links (FIMO-2843).
|
|
1410
|
-
if (named) for (const p of llmsLinks(site.llms.body).map(toPath).filter(Boolean)) aim(p);
|
|
1411
1408
|
const seed = opt('seed');
|
|
1412
1409
|
if (!named && seed && fs.existsSync(seed)) for (const l of fs.readFileSync(seed, 'utf8').split('\n')) if (l.startsWith('/')) add(l.split(' ')[0]);
|
|
1413
1410
|
// What the server and the browser answer for a path; --parallel paths are read at once.
|
|
@@ -1562,7 +1559,7 @@ async function crawl() {
|
|
|
1562
1559
|
fs.writeFileSync(SITE, JSON.stringify(site));
|
|
1563
1560
|
const unknown = Object.values(site.pages).filter((p) => p.state === 'unknown').length;
|
|
1564
1561
|
const counted = named ? 'Read ' + named.length + ' named pages ' + (HTTP ? 'over HTTP' : 'in a browser') + ' and the status of ' + (Object.keys(site.pages).length - named.length + Object.keys(site.assets).length) + ' addresses they link to' : 'Crawled ' + Object.keys(site.pages).length + ' pages';
|
|
1565
|
-
const summary = counted + ' at ' + origin + (pub ? ' (public ' + pub + ')' : '') + ' in ' + site.seconds + ' s; sitemap ' + site.sitemapState + ', ' + site.sitemap.length + ' URLs; ' + urls.length + ' outbound links checked' + (unknown ? '; ' + unknown + ' pages could not be read' : '') + (site.phone ? '; ' + site.phone.opened + ' of ' + site.phone.picked + ' sampled pages opened again ' + site.phone.width + ' px wide' : '') + (site.complete ? '.' :
|
|
1562
|
+
const summary = counted + ' at ' + origin + (pub ? ' (public ' + pub + ')' : '') + ' in ' + site.seconds + ' s; sitemap ' + site.sitemapState + ', ' + site.sitemap.length + ' URLs; ' + urls.length + ' outbound links checked' + (unknown ? '; ' + unknown + ' pages could not be read' : '') + (site.phone ? '; ' + site.phone.opened + ' of ' + site.phone.picked + ' sampled pages opened again ' + site.phone.width + ' px wide' : '') + (site.complete ? '.' : '; stopped early, ' + site.unvisited.length + ' pages not visited.') + (pool.dropped.length ? ' agent-browser failed in ' + pool.dropped.length + ' of ' + SESSIONS.length + ' browser sessions (' + pool.dropped.join(', ') + '): finished with ' + pool.live.length + '.' : '') + skippedLine(site, ' Not crawled, another site: ');
|
|
1566
1563
|
// A dev server that went down cost this crawl something when a page got no answer, or when it no longer answers
|
|
1567
1564
|
// while a page or pass is left unread. Down after every page was read, it cost nothing: the next crawl needs it.
|
|
1568
1565
|
let up = true;
|
|
@@ -1620,7 +1617,7 @@ function findings(site) {
|
|
|
1620
1617
|
if (capped) unsure('broken-links', null, capped + ' outbound links not checked: over the limit (crawl with a higher --max-links)');
|
|
1621
1618
|
if (site.robotsState === 'unknown') unsure('technical', null, '/robots.txt: no clear answer');
|
|
1622
1619
|
if (site.sitemapState === 'unknown' || site.sitemapState === 'partial') unsure('technical', null, 'sitemap ' + (site.sitemapState === 'partial' ? 'not fully read (more than 20 files, or the crawl deadline)' : 'could not be read: ' + site.sitemapError));
|
|
1623
|
-
if (!site.complete) unsure('all', null, 'crawl stopped
|
|
1620
|
+
if (!site.complete) unsure('all', null, 'crawl stopped early: ' + site.unvisited.length + ' pages not visited (' + site.unvisited.slice(0, 3).join(', ') + ')');
|
|
1624
1621
|
const sitemapKnown = site.sitemapState === 'ok' || site.sitemapState === 'missing';
|
|
1625
1622
|
|
|
1626
1623
|
const T = 'technical';
|
|
@@ -1700,16 +1697,12 @@ function findings(site) {
|
|
|
1700
1697
|
if (whole) for (const group of Object.values(byLang)) {
|
|
1701
1698
|
const shared = [tally(group, ENDING), tally(group, BEGINNING)].filter((s) => s && s.n >= 2 && s.n * 2 > group.length).sort((a, b) => b.n - a.n)[0];
|
|
1702
1699
|
if (shared) {
|
|
1703
|
-
// The site's name: the shared text without its separator, and the configured one.
|
|
1704
|
-
const names = [shared.text.replace(/^\s*[-–—|·•:]\s*|\s*[-–—|·•:]\s*$/g, ''), site.siteName].filter(Boolean);
|
|
1705
1700
|
for (const [path, p] of group) {
|
|
1706
1701
|
const t = p.title.toLowerCase();
|
|
1707
1702
|
if (shared.first ? t.startsWith(shared.text.toLowerCase()) : t.endsWith(shared.text.toLowerCase())) continue;
|
|
1708
1703
|
// Adding the brand must not push the title past what Google shows: then the rest needs shortening, a person's call.
|
|
1709
1704
|
const long = !WIDE_SCRIPT.test(p.lang || '') && p.title.length + shared.text.length > SNIPPET.title.max;
|
|
1710
|
-
|
|
1711
|
-
const named = names.find((name) => new RegExp('(^|[^\\p{L}\\p{N}])' + name.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&') + '($|[^\\p{L}\\p{N}])', 'iu').test(p.title));
|
|
1712
|
-
add('title-format', 'meta-tags', PRICE.test(p.title) || long || named ? 'suggest' : 'auto', path, '"' + p.title + '" does not ' + (shared.first ? 'start' : 'end') + ' with "' + shared.text.trim() + '" like ' + shared.n + ' other titles' + (named ? ', and already names "' + named + '": adding it names the site twice, so reword the start' : '') + (long ? '; with it the title is too long, so the rest needs shortening' : ''));
|
|
1705
|
+
add('title-format', 'meta-tags', PRICE.test(p.title) || long ? 'suggest' : 'auto', path, '"' + p.title + '" does not ' + (shared.first ? 'start' : 'end') + ' with "' + shared.text.trim() + '" like ' + shared.n + ' other titles' + (long ? '; with it the title is too long, so the rest needs shortening' : ''));
|
|
1713
1706
|
}
|
|
1714
1707
|
} else if (group.length >= 3) {
|
|
1715
1708
|
const brand = site.siteName || (site.pub ? new URL(site.pub).host.replace(/^www\./, '') : 'the site name');
|
|
@@ -2287,15 +2280,11 @@ else if (cmd === 'diff') diff();
|
|
|
2287
2280
|
else if (cmd === 'text') pageText();
|
|
2288
2281
|
else if (cmd === 'links') links();
|
|
2289
2282
|
else console.log('node site.mjs crawl [origin] [--max 300] [--max-links 300] [--deadline 900] [--parallel 1] [--seed previous.txt] [--preview-host host] [--hosted url] [--quality] [--phone-max 20] [--compliance] [--consent-max 6] [--fresh] [--pages file [--http] [--session name]] | wait | check [--topic t1,t2] [--retired "Old=New;..."] [--today YYYY-MM-DD] | text [/path ...] | links (after crawl --pages) | diff previous.txt (writes snapshot.txt)');
|
|
2290
|
-
`;var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project2();function registerAgentsCommands(program2){let agents=program2.command("agents").description("Read project agents and their routines"),scoped=__name(command=>command.option("--project <id>","Site id (defaults to the linked site)").option("-C, --cwd <dir>","Site directory"),"scoped");scoped(agents).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("list").description("List agents and routine schedules")).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("show <name-or-id>").description("Read an agent and its routine instructions")).action((ref,_options,command)=>agentsCommand(command.optsWithGlobals(),ref,command))
|
|
2283
|
+
`;var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project2();function registerAgentsCommands(program2){let agents=program2.command("agents").description("Read project agents and their routines"),scoped=__name(command=>command.option("--project <id>","Site id (defaults to the linked site)").option("-C, --cwd <dir>","Site directory"),"scoped");scoped(agents).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("list").description("List agents and routine schedules")).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("show <name-or-id>").description("Read an agent and its routine instructions")).action((ref,_options,command)=>agentsCommand(command.optsWithGlobals(),ref,command))}__name(registerAgentsCommands,"registerAgentsCommands");async function agentsCommand(options,ref,command){let cwd=resolveProjectCwd(options.cwd),projectId=options.project??(existsSync(resolveProjectSettingsPath(cwd))?loadProjectSettings(cwd).projectId:process.env.FIMO_PROJECT_ID?.trim());if(!projectId)throw new NotInProjectError;let branch=branchOverrideFromCommand(command)??(process.env.FIMO_ENV?.trim()||DEFAULT_BRANCH);await requireOperation("agents.list",{projectId});let fimo=createCliFimoClient(loadConfig()),{chats:chats2}=await fimo.execute("agents.list",{projectId,branch}),agents=chats2.filter(chat=>chat.kind==="agent");if(ref!==void 0){let byId=agents.find(agent2=>agent2.id===ref);if(agents=byId?[byId]:agents.filter(agent2=>agent2.title===ref),!agents.length)throw new Error(`Agent not found: ${ref}`);if(agents.length>1)throw new Error(`Multiple agents named "${ref}". Use an agent ID from fimo agents.`)}let result=await Promise.all(agents.map(async agent2=>{let{routines:routines2}=await fimo.execute("agents.routines",{projectId,branch,threadId:agent2.id});return{id:agent2.id,name:agent2.title??"Agent",description:ref===void 0?(agent2.description??"").replace(/\s+/g," ").slice(0,60):agent2.description,routines:routines2.map(routine=>({id:routine.id,name:routine.name,schedule:routine.triggers.schedule,event:routine.triggers.event?.text??null,paused:routine.paused,...ref!==void 0?{instructions:routine.instructions}:{}}))}}));ui.result({command:ref===void 0?"agents list":"agents show",data:ref===void 0?{agents:result}:result[0],render:__name(()=>result.length?result.map(agent2=>[`${agent2.name} (${agent2.id})`,...agent2.description?[agent2.description]:[],...agent2.routines.map(routine=>{let schedule=routine.schedule?`${routine.schedule.cron} (${routine.schedule.timezone})`:"manual";return` - ${routine.name}: ${schedule}${routine.event?`; ${routine.event}`:""}${routine.paused?" [paused]":""}${routine.instructions?`
|
|
2291
2284
|
${routine.instructions}`:""}`})].join(`
|
|
2292
2285
|
`)).join(`
|
|
2293
2286
|
|
|
2294
|
-
`):"No agents on this project.","render")})}__name(agentsCommand,"agentsCommand");async function agentRunsCommand(options,agentRef,routineRef,command){let limit=Number(options.limit??"10");if(!Number.isInteger(limit)||limit<1||limit>50)throw new Error("--limit must be a whole number from 1 to 50.");let{projectId,branch,fimo,agents}=await projectScope(options,command,"agents.routine_runs"),agent2=pick(agents,agentRef,candidate=>candidate.title,"Agent"),{routines:routines2}=await fimo.execute("agents.routines",{projectId,branch,threadId:agent2.id}),selected=routineRef===void 0?routines2:[pick(routines2,routineRef,routine=>routine.name,"Routine")],result=await Promise.all(selected.map(async routine=>{let{runs}=await fimo.execute("agents.routineRuns",{projectId,branch,threadId:agent2.id,routineId:routine.id});return{id:routine.id,name:routine.name,nextRunAt:routine.nextRunAt,runs:runs.slice(0,limit)}}));ui.result({command:"agents runs",data:{agent:{id:agent2.id,name:agent2.title??"Agent"},routines:result},render:__name(()=>result.length?result.map(routine=>[`${routine.name} (${routine.id})${routine.nextRunAt?`; next ${routine.nextRunAt}`:""}`,...routine.runs.length?routine.runs.map(run=>{let by=run.startedBy?` by ${run.startedBy.name??run.startedBy.kind}`:"",took=run.durationMs===null?"":` in ${Math.round(run.durationMs/1e3)}s`,line=` - ${run.startedAt} ${run.trigger}${by}: ${run.outcome??run.status}${took}`;return run.summary?`${line}
|
|
2295
|
-
${run.summary.replace(/\s+/g," ")}`:line}):[" No runs yet."]].join(`
|
|
2296
|
-
`)).join(`
|
|
2297
|
-
|
|
2298
|
-
`):`${agent2.title??"This agent"} has no routines.`,"render")})}__name(agentRunsCommand,"agentRunsCommand");init_esm();init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{items,branch}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{branch,dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{annotations:annotations2,branch}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{branch,annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";init_project_context();init_project2();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs7 from"node:fs";import path7 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
2287
|
+
`):"No agents on this project.","render")})}__name(agentsCommand,"agentsCommand");init_esm();init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{items,branch}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{branch,dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{annotations:annotations2,branch}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{branch,annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";init_project_context();init_project2();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs7 from"node:fs";import path7 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
2299
2288
|
`),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
|
|
2300
2289
|
`){escapeUrl&&(returnValue+=wrapAnsiHyperlink(""));let closingCode=escapeCode?getClosingCode(escapeCode):void 0;escapeCode&&closingCode&&(returnValue+=wrapAnsiCode(closingCode))}else character===`
|
|
2301
2290
|
`&&(escapeCode&&getClosingCode(escapeCode)&&(returnValue+=wrapAnsiCode(escapeCode)),escapeUrl&&(returnValue+=wrapAnsiHyperlink(escapeUrl)))}return returnValue},"exec"),CRLF_OR_LF=/\r?\n/;function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
|
|
@@ -2811,11 +2800,11 @@ Output
|
|
|
2811
2800
|
${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
|
|
2812
2801
|
`)}__name(renderFields,"renderFields");function renderTable(headers,rows){if(rows.length===0)return"No results.";let widths=headers.map((header,index)=>Math.max(header.length,...rows.map(row2=>String(row2[index]??"").length)));return[headers,...rows].map(row2=>row2.map((value,index)=>String(value).padEnd(widths[index])).join(" ").trimEnd()).join(`
|
|
2813
2802
|
`)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_esm();init_dist();import fs45 from"node:fs";import path44 from"node:path";import{isDeepStrictEqual}from"node:util";init_sdk_transport();init_project_context();init_project2();var SYSTEM_SCHEMA_FIELDS=new Set(RESERVED_CONTENT_FIELD_NAMES),SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message,options){super(message,options),this.name="SchemaCommandError",this.code=code2}};function isRecord3(value){return!!(value&&typeof value=="object"&&!Array.isArray(value))}__name(isRecord3,"isRecord");function schemaMatches(actual,expected){if(!isRecord3(actual)||!isRecord3(actual.fields))return!1;let userFields=Object.fromEntries(Object.entries(actual.fields).filter(([fieldName])=>!SYSTEM_SCHEMA_FIELDS.has(fieldName)));return actual.name===expected.name&&actual.label===expected.label&&actual.isSingleton===expected.isSingleton&&isDeepStrictEqual(actual.i18n,expected.i18n)&&isDeepStrictEqual(actual.groups??[],expected.groups)&&isDeepStrictEqual(userFields,expected.fields)}__name(schemaMatches,"schemaMatches");async function readBackSchemaBatch(fimo,projectId,branch,schemas3){let checks=await Promise.all(schemas3.map(async schema=>{try{let actual=await fimo.execute("schemas.get",{projectId,branch,typeName:schema.name});return{name:schema.name,actual,state:schemaMatches(actual,schema)?"matched":"mismatched"}}catch(error){if(error instanceof ApiRequestError&&error.status===404)return{name:schema.name,state:"absent"};throw error}})),matched=checks.filter(check=>check.state==="matched"),absent=checks.filter(check=>check.state==="absent"),mismatched=checks.filter(check=>check.state==="mismatched");return matched.length===schemas3.length?{state:"committed",results:matched.map(check=>check.actual)}:absent.length===schemas3.length?{state:"absent"}:{state:"ambiguous",details:[matched.length>0?`matched: ${matched.map(check=>check.name).join(", ")}`:null,absent.length>0?`absent: ${absent.map(check=>check.name).join(", ")}`:null,mismatched.length>0?`mismatched: ${mismatched.map(check=>check.name).join(", ")}`:null].filter(Boolean).join("; ")}}__name(readBackSchemaBatch,"readBackSchemaBatch");async function upsertSchemasWithReconciliation(fimo,projectId,branch,schemas3,operations){let timeout;try{return await fimo.execute("schemas.upsertBatch",{projectId,branch,contentTypes:schemas3,operations:[...operations]})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let firstReadBack=await readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout);if(firstReadBack.state==="committed")return firstReadBack.results;if(firstReadBack.state==="ambiguous")throw ambiguousSchemaPushError(firstReadBack.details,timeout);try{return await fimo.execute("schemas.upsertBatch",{projectId,branch,contentTypes:schemas3,operations:[...operations]})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let secondReadBack=await readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout);if(secondReadBack.state==="committed")return secondReadBack.results;let detail=secondReadBack.state==="absent"?"all requested schemas remain absent after one retry":secondReadBack.details;throw ambiguousSchemaPushError(detail,timeout)}__name(upsertSchemasWithReconciliation,"upsertSchemasWithReconciliation");function ambiguousSchemaPushError(detail,cause){return new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 (${detail}). No further write was attempted; read the schemas back before rerunning.`,{cause})}__name(ambiguousSchemaPushError,"ambiguousSchemaPushError");async function readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout){try{return await readBackSchemaBatch(fimo,projectId,branch,schemas3)}catch(error){let detail=error instanceof Error?error.message:String(error);throw new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 and read-back failed (${detail}). No retry was attempted.`,{cause:timeout})}}__name(readBackAfterTimeout,"readBackAfterTimeout");function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},groups:schema.groups??[],fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue2){if(!issue2||typeof issue2!="object"||Array.isArray(issue2))return!1;let candidate=issue2;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue2=>{let remaining=Math.max(issue2.documentCount-issue2.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue2.contentType,field:issue2.field,value:issue2.value,documents:issue2.documentCount,document_ids:issue2.documentIdsTruncated?[...issue2.documentIds,truncationNote].join(", "):issue2.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.list",{projectId:ctx.projectId,branch:ctx.branch});ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),schemasDir=path44.join(cwd,"src/schemas"),allSchemaFiles=fs45.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files2=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs45.readFileSync(path44.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files2.map(file=>{let filePath=path44.join(schemasDir,file);if(!fs45.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path44.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue2=>`${issue2.file}: ${issue2.message}`).join(`
|
|
2814
|
-
`));return JSON.parse(fs45.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(fimo,ctx.projectId,ctx.branch,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.deleteFromBranch",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("singles.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let input=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),{data:result}=await fimo.execute("singles.update",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,data:input.data});ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");import{spawn as spawn3}from"node:child_process";import{mkdtempSync as mkdtempSync2,rmSync,writeFileSync as writeFileSync6}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path45 from"node:path";init_esm();init_dist();init_config();init_project_services();init_git();init_project_context();init_project2();var PREVIEW_WAIT_MS=9e4,DEV_SERVER_URL="http://localhost:5173",MAX_PAGES=50,DEADLINE_SECONDS=300,SiteCommandError=class extends Error{constructor(message,hint){super(message);this.hint=hint;this.name="SiteCommandError"}static{__name(this,"SiteCommandError")}};function normalizePagePaths(args
|
|
2803
|
+
`));return JSON.parse(fs45.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(fimo,ctx.projectId,ctx.branch,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.deleteFromBranch",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("singles.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let input=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),{data:result}=await fimo.execute("singles.update",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,data:input.data});ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");import{spawn as spawn3}from"node:child_process";import{mkdtempSync as mkdtempSync2,rmSync,writeFileSync as writeFileSync6}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path45 from"node:path";init_esm();init_dist();init_config();init_project_services();init_git();init_project_context();init_project2();var PREVIEW_WAIT_MS=9e4,DEV_SERVER_URL="http://localhost:5173",MAX_PAGES=50,DEADLINE_SECONDS=300,SiteCommandError=class extends Error{constructor(message,hint){super(message);this.hint=hint;this.name="SiteCommandError"}static{__name(this,"SiteCommandError")}};function normalizePagePaths(args){let out=[];for(let raw of args.flatMap(a=>a.split(/\s+/)).filter(Boolean)){let p2;try{let u2=new URL(raw,"http://site.invalid");p2=u2.pathname+u2.search}catch{throw new SiteCommandError(`'${raw}' is not a page path.`,"Name pages by path, for example `/pricing` or `/blog/my-post`.")}out.includes(p2)||out.push(p2)}if(out.length===0)throw new SiteCommandError("Name at least one page.","For example `fimo site check / /pricing`.");if(out.length>MAX_PAGES)throw new SiteCommandError(`${out.length} pages named; this checks at most ${MAX_PAGES} at once.`,"Check the pages the change affects, in batches if needed.");return out}__name(normalizePagePaths,"normalizePagePaths");async function answers(origin){try{return await fetch(origin+"/",{redirect:"manual",signal:AbortSignal.timeout(1e4)}),!0}catch{return!1}}__name(answers,"answers");function previewProblem(wait,branch,waitMs){switch(wait.kind){case"none":return`Branch '${branch}' has no hosted preview`;case"failed":return`the hosted preview of '${branch}' failed to build`;case"pending":return`the hosted preview of '${branch}' is still ${wait.preview.status==="queued"?"waiting to build":"building"} after ${Math.round(waitMs/1e3)} s`;case"no-url":return`the hosted preview of '${branch}' is ready but has no URL`}}__name(previewProblem,"previewProblem");async function resolveSiteTarget(input){if(input.url)try{return{kind:"url",origin:new URL(input.url).origin}}catch{throw new SiteCommandError(`--url '${input.url}' is not a URL.`,"Pass an origin such as http://localhost:5173.")}if(isProductionBranch(input.branch))throw new SiteCommandError(`Branch '${input.branch}' is production and has no hosted preview.`,"Check the live site with --branch main (main's hosted preview), or the published address with --url <origin>.");let wait=await waitForHostedPreview(input.readPreview,input.waitMs??PREVIEW_WAIT_MS,input.sleep);if(wait.kind==="ready")return{kind:"hosted-preview",origin:new URL(wait.url).origin,generation:wait.preview.generation,revision:wait.preview.revision};let why=previewProblem(wait,input.branch,input.waitMs??PREVIEW_WAIT_MS),ownBranch=input.checkoutBranch===input.branch;if(ownBranch&&await(input.devServerAnswers??answers)(DEV_SERVER_URL))return{kind:"dev-server",origin:DEV_SERVER_URL,why};let retry=wait.kind==="pending"?"Run the command again in a minute.":wait.kind==="failed"?"Fix the build (`fimo logs`), then deploy again.":"Deploy a change to ask for a hosted preview (`fimo deploy`).";throw new SiteCommandError(`Cannot check the site: ${why}${ownBranch?`, and no dev server answers at ${DEV_SERVER_URL}`:""}.`,`${retry} Or pass --url <origin> to check another address.`)}__name(resolveSiteTarget,"resolveSiteTarget");function runScript(file,args,cwd,siteDir){return new Promise((resolve10,reject)=>{let child=spawn3(process.execPath,[file,...args],{cwd,env:{...process.env,FIMO_SITE_DIR:siteDir},stdio:["ignore","pipe","pipe"]}),stdout="",stderr="";child.stdout.on("data",d3=>stdout+=d3.toString("utf8")),child.stderr.on("data",d3=>stderr+=d3.toString("utf8")),child.on("error",reject),child.on("close",code2=>resolve10({code:code2??1,stdout:stdout.trim(),stderr:stderr.trim()}))})}__name(runScript,"runScript");async function readPages(input){let dir=mkdtempSync2(path45.join(tmpdir4(),"fimo-site-"));try{let script=path45.join(dir,"site.mjs"),pages2=path45.join(dir,"pages.txt");writeFileSync6(script,SITE_SCRIPT),writeFileSync6(pages2,input.paths.join(`
|
|
2815
2804
|
`)+`
|
|
2816
|
-
`);let crawlArgs=
|
|
2817
|
-
`).filter(Boolean).pop()||read.stderr||"The pages could not be read.",input.browser?"Check that agent-browser is installed (`agent-browser --version`).":`Check that ${input.origin} answers.`);let report2=await runScript(script,[...input.report],input.projectDir,
|
|
2818
|
-
`);ui.result({command,data:{project_id:ctx.projectId,branch:ctx.branch,target:target.origin,target_kind:target.kind,mode:browser?"browser":"http"
|
|
2805
|
+
`);let crawlArgs=["crawl",input.origin,"--pages",pages2,"--deadline",String(DEADLINE_SECONDS),"--fresh"];input.browser?(crawlArgs.push("--parallel","2","--quality"),input.topics.some(t2=>t2==="consent"||t2==="privacy")&&crawlArgs.push("--compliance")):crawlArgs.push("--http");let read=await runScript(script,crawlArgs,input.projectDir,dir);if(read.code!==0)throw new SiteCommandError(read.stdout.split(`
|
|
2806
|
+
`).filter(Boolean).pop()||read.stderr||"The pages could not be read.",input.browser?"Check that agent-browser is installed (`agent-browser --version`).":`Check that ${input.origin} answers.`);let report2=await runScript(script,[...input.report],input.projectDir,dir);if(report2.code!==0)throw new SiteCommandError(report2.stdout||report2.stderr||"The check failed.","Run the command again.");return{read:read.stdout,report:report2.stdout}}finally{rmSync(dir,{recursive:!0,force:!0})}}__name(readPages,"readPages");async function checkoutBranchOf(projectDir){try{let branch=(await currentBranch2(projectDir)).trim();if(branch)return branch}catch{}return process.env.FIMO_ENV?.trim()||null}__name(checkoutBranchOf,"checkoutBranchOf");function targetLine(target,branch){switch(target.kind){case"hosted-preview":return`Hosted preview of '${branch}' (${target.origin}${target.revision?`, revision ${target.revision.slice(0,7)}`:""}).`;case"dev-server":return`Dev server ${target.origin}: ${target.why}.`;case"url":return`${target.origin} (--url).`}}__name(targetLine,"targetLine");async function runSiteCommand(command,pathArgs,options,cmd){try{let paths=normalizePagePaths(pathArgs),{ctx}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.site.check",{projectId:ctx.projectId,branch:ctx.branch});let sandbox=createSandboxService(loadConfig(),ctx.branch),projectDir=resolveProjectCwd(options.cwd),target=await resolveSiteTarget({url:options.url,branch:ctx.branch,checkoutBranch:await checkoutBranchOf(projectDir),readPreview:__name(()=>sandbox.getHostedPreview(ctx.projectId,ctx.branch),"readPreview")}),topics=(options.topic??"").split(",").map(t2=>t2.trim()).filter(Boolean),browser=command==="site check"&&options.browser===!0,{read,report:report2}=await readPages({origin:target.origin,paths,browser,topics,report:command==="site links"?["links"]:["check",...topics.length?["--topic",topics.join(",")]:[]],projectDir}),text=[targetLine(target,ctx.branch),read,report2].filter(Boolean).join(`
|
|
2807
|
+
`);ui.result({command,data:{project_id:ctx.projectId,branch:ctx.branch,target:target.origin,target_kind:target.kind,mode:browser?"browser":"http",pages:paths,...topics.length?{topics}:{},output:text},render:__name(()=>text,"render")})}catch(error){ui.error({command,code:"SITE_CHECK_FAILED",message:error instanceof Error?error.message:String(error),hint:error instanceof SiteCommandError?error.hint:"Run the command again; if it keeps failing, pass --url <origin>."})}}__name(runSiteCommand,"runSiteCommand");function siteCheckCommand(paths,options,cmd){return runSiteCommand("site check",paths,options,cmd)}__name(siteCheckCommand,"siteCheckCommand");function siteLinksCommand(paths,options,cmd){return runSiteCommand("site links",paths,options,cmd)}__name(siteLinksCommand,"siteLinksCommand");function registerSiteCommands(program2){let site=program2.command("site",{hidden:!0}).description("Check named pages of the site: the pages a change affects, not the whole site");site.command("check <paths...>").description("Check named pages of the Branch's hosted preview (SEO, links, images, ...): HTTP by default, a real browser with --browser").option("--topic <topics>","Only these topics, comma-separated (meta-tags, image-seo, broken-links, ...)").option("--browser","Render in a real browser: accessibility, phone layout, consent (slower)").option("--url <origin>","Check this address instead of the hosted preview (for example http://localhost:5173)").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((paths,opts,cmd)=>siteCheckCommand(paths,opts,cmd)),site.command("links <paths...>").description("List the named pages' links with each target's status; every unique target is checked once").option("--url <origin>","Check this address instead of the hosted preview (for example http://localhost:5173)").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((paths,opts,cmd)=>siteLinksCommand(paths,opts,cmd))}__name(registerSiteCommands,"registerSiteCommands");init_status();import{readFileSync as readFileSync12}from"node:fs";import path46 from"node:path";init_dist();init_config();init_sdk_transport();init_project_services();init_project_context();init_version();var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with site and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Site directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
|
|
2819
2808
|
Examples:
|
|
2820
2809
|
fimo support report "Preview deployment fails after validation"
|
|
2821
2810
|
fimo support report --message-file /tmp/fimo-support-report.md --preview --json
|