fimo 2.2.0-staging.4 → 2.2.0-staging.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/fimo-studio/references/preview-and-responsive.md +4 -1
- package/dist/build/astro/config.js +2 -1
- package/dist/build/vite/plugins/preview-health.d.ts +4 -0
- package/dist/build/vite/plugins/preview-health.js +40 -0
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +1 -1
- package/package.json +11 -7
- package/templates/astro/package.json +2 -2
- package/templates/nextjs/package.json +4 -4
- package/templates/react-router/package.json +4 -4
- package/templates/sveltekit/package.json +2 -2
- package/templates/vite/package.json +4 -4
package/dist/cli/index.js
CHANGED
|
@@ -57,7 +57,7 @@ ${block.code}
|
|
|
57
57
|
|
|
58
58
|
`)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&§ions.push(...document.details.map(reportBlockMarkdown)),sections.join(`
|
|
59
59
|
|
|
60
|
-
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),ReportSeriesBlockSchema=z15.object({type:z15.literal("series"),...blockCommon,unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."})}),ReportFindingsBlockSchema=z15.object({type:z15.literal("findings"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema,label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Several ranked problems, risks, or recommendations. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index2)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportImageBlockSchema=z15.object({type:z15.literal("image"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual evidence or a visual deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53){return pageRouteParamNames(path53).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z17}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),previewEnabled:z17.boolean().default(!0),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z22.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z22.object({type:z22.literal("manual")}),ScheduleTriggerSchema=z22.object({type:z22.literal("schedule"),cron:z22.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z22.string().optional()}),WebhookTriggerSchema=z22.object({type:z22.literal("webhook"),path:z22.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z22.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z23}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z23.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z23.object({token:z23.string().min(1),risk:CapabilityRiskTierSchema,description:z23.string()}),AgentSubAgentSummarySchema=z23.object({name:z23.string().min(1),grant:z23.enum(["inherit","explicit"]),effectiveCaps:z23.array(z23.string().min(1))}),AgentInstallSummaryDTOSchema=z23.object({agentName:z23.string().min(1),env:z23.string().min(1),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z23.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z23.array(CapabilitySummaryEntrySchema),criticalCapabilities:z23.array(CapabilitySummaryEntrySchema),subAgents:z23.array(AgentSubAgentSummarySchema),declaresDelegate:z23.boolean(),cycle:z23.array(z23.string()).nullable(),missingSubAgents:z23.array(z23.string()),warnings:z23.array(z23.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z24}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z24.object({kind:TriggerKindSchema,summary:z24.string()}),AgentListItemTriggerStateSchema=z24.object({triggerIndex:z24.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z24.boolean(),wired:z24.boolean(),syncError:z24.string().nullable()}),AgentListItemDTOSchema=z24.object({name:z24.string().min(1),description:z24.string().nullable(),goalFirstLine:z24.string().nullable(),declaredCapabilities:z24.array(CapabilitySummaryEntrySchema),triggers:z24.array(AgentListItemTriggerSchema),triggerStates:z24.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z25.object({args:z25.unknown().optional(),requestId:z25.string().min(1).max(128).optional()}),DispatchSkippedSchema=z25.object({skipped:z25.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z25.object({sessionId:z25.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z25.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z26.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:BranchSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z27.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z27.object({cpuMs:z27.number().nonnegative().default(0),netBytes:z27.number().nonnegative().default(0),walltimeMs:z27.number().nonnegative().default(0),llmTokensIn:z27.number().nonnegative().optional(),llmTokensOut:z27.number().nonnegative().optional(),stepCount:z27.number().int().nonnegative().optional(),toolCallCounts:z27.record(z27.string().min(1).max(120),z27.number().int().nonnegative()).optional(),toolCallOutcomes:z27.array(z27.object({toolName:z27.string().min(1).max(120),success:z27.boolean(),code:z27.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z27.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z27.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z27.object({capturedAt:z27.coerce.date(),fingerprint:z27.string().min(1).max(256),counts:z27.object({code:z27.number().int().nonnegative(),content:z27.number().int().nonnegative(),schemas:z27.number().int().nonnegative(),labels:z27.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z27.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z27.object({diff:DiffReportSchema,code:z27.array(CodeFileDiffSchema.extend({raw:z27.string().max(24576)})).max(200),schemas:z27.array(SchemaTypeDiffSchema).max(200),content:z27.array(z27.object({key:z27.string().min(1).max(512),collection:z27.string().min(1).max(256),slug:z27.string().max(512).optional(),verb:z27.enum(["added","modified","deleted"]),fields:z27.array(z27.object({name:z27.string().min(1).max(256),before:z27.unknown().optional(),after:z27.unknown().optional()})).max(20)})).max(200),labels:z27.array(z27.object({key:z27.string().min(1).max(512),locale:z27.string().min(1).max(64).optional(),before:z27.unknown().nullable(),after:z27.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z27.object({id:z27.uuid(),projectId:z27.uuid(),env:BranchSchema,agentName:z27.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z27.unknown().optional(),capabilities:z27.array(z27.string()).optional(),dataSources:z27.array(z27.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z27.string().nullable(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),cancelledAt:z27.coerce.date().nullable(),costUsd:z27.number().nonnegative(),costCeilingUsd:z27.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z27.boolean(),lastCheckpointId:z27.uuid().nullable(),branchEnvId:z27.uuid().nullable(),parentSessionId:z27.uuid().nullable(),terminalReason:z27.string().nullable(),errorMessage:z27.string().nullable(),reportDocument:ReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z27.object({id:z27.uuid(),sessionId:z27.uuid(),checkpointIdx:z27.number().int().nonnegative(),payloadRef:z27.string(),payloadSizeBytes:z27.number().int().nonnegative(),checksum:z27.string().length(64),createdAt:z27.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z27.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z27.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z27.object({session:AgentSessionDTOSchema,checkpoints:z27.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z27.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z27.object({reason:z27.string().min(1).max(120).optional()})}});import{z as z28}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z28.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z28.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z28.object({id:z28.uuid(),envId:z28.uuid(),sessionId:z28.uuid().nullable(),skillName:z28.string().min(1),classification:AgentBranchClassificationSchema,rationale:z28.string().nullable(),summary:z28.string().nullable(),surfaceDeltas:z28.record(z28.string(),z28.unknown()),createdAt:z28.coerce.date(),decidedAt:z28.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z28.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z28.object({path:z28.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z28.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z28.object({code:z28.literal("merge_conflict"),message:z28.string(),conflicts:z28.record(z28.string(),z28.number().int().nonnegative())})}});import{z as z29}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z29.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z29.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z29.object({description:z29.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z29.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),threadId:z29.uuid(),invocationId:z29.uuid(),agentKey:z29.string().min(1).max(120),anchorEnv:z29.string().min(1).max(64),retainedEnv:z29.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z29.string().min(1).nullable(),continuationInvocationId:z29.uuid().nullable(),askedAt:z29.coerce.date(),expiresAt:z29.coerce.date(),closedAt:z29.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z29.object({questionId:z29.uuid(),invocationId:z29.uuid(),askedAt:z29.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z29.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z29.object({question:AgentQuestionSchema,continuationInvocationId:z29.uuid(),deduped:z29.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z30}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z30.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z30.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z30.enum(["secret_text"]),IntegrationCredentialUsageSchema=z30.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z30.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z30.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z30.object({mode:IntegrationAuthModeSchema,label:z30.string().min(1),description:z30.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z30.object({id:z30.string().min(1),label:z30.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z30.boolean()}),IntegrationToolDefinitionDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),description:z30.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z30.object({title:z30.string().min(1),description:z30.string().min(1),command:z30.string().min(1).optional()}),IntegrationInfoDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),type:z30.enum(["native","mcp"]).optional(),url:z30.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z30.array(IntegrationAuthModeDTOSchema),credentials:z30.array(IntegrationCredentialDefinitionDTOSchema),tools:z30.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z30.enum(["available","unavailable"]).optional(),recipes:z30.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),installed:z30.boolean(),enabled:z30.boolean(),setupState:z30.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z30.string().nullable(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),connectionStatus:z30.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),installedAt:z30.coerce.date().nullable(),updatedAt:z30.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),enabled:z30.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z30.string(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z30.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z30.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z30.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z30.object({value:z30.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z30.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z30.object({id:z30.uuid(),organizationId:z30.string().min(1),integrationKey:z30.string().min(1),alias:z30.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z30.string().min(1),externalAccountName:z30.string().nullable(),externalBotUserId:z30.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z30.array(z30.string()),connectedAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z30.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z30.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z30.record(McpHeaderNameSchema,z30.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z30.object({alias:z30.string().min(1).max(120).optional(),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z30.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),alias:z30.string().min(1).max(120),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}),z30.object({mode:z30.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z30.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z30.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z30.union([z30.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z30.object({type:z30.literal("mcp"),name:z30.string().trim().min(1).max(120),url:z30.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z30.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z30.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z30.object({integrationKey:z30.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z30.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("oauth"),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),ReusableMcpServerAuthKindSchema=z30.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z30.object({id:z30.uuid(),name:z30.string().min(1),host:z30.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z30.string().min(1),availability:z30.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z30.object({query:z30.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z30.object({serverId:z30.uuid()}),StartProjectIntegrationConnectResponseSchema=z30.object({integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),integrationKey:z30.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z30.object({mode:z30.literal("oauth"),integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),BindProjectChannelRequestSchema=z30.object({ref:z30.string().min(1),connectionAlias:z30.string().min(1).optional(),agentName:z30.string().min(1).max(160).nullable().optional(),force:z30.boolean().optional()}),ListProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1)}),SearchProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1),connectionAlias:z30.string().min(1),query:z30.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),connectionId:z30.uuid(),externalWorkspaceId:z30.string().min(1),externalChannelId:z30.string().min(1),externalChannelName:z30.string().nullable(),agentName:z30.string().nullable(),enabled:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z30.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z30.object({id:z30.string().min(1),name:z30.string().min(1),visibility:z30.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z30.string().min(1).nullable(),canMove:z30.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z30.object({markdown:z30.boolean().optional(),summary:z30.boolean().optional(),links:z30.boolean().optional(),branding:z30.boolean().optional(),images:z30.boolean().optional(),html:z30.union([z30.literal("cleaned"),z30.literal("raw"),z30.boolean()]).optional(),json:z30.union([z30.boolean(),z30.object({prompt:z30.string().min(1).max(1e4),schema:z30.record(z30.string(),z30.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z30.object({url:z30.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z30.object({query:z30.string().min(1),maxResults:z30.number().int().positive().max(20).optional(),sources:z30.array(z30.enum(["web","news","images"])).min(1).max(3).optional(),categories:z30.array(z30.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z30.enum(["hour","day","week","month","year"]).optional(),location:z30.string().min(1).max(160).optional(),country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(100).optional(),types:z30.array(z30.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),sources:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),passages:z30.number().int().min(1).max(5).optional(),skills:z30.literal("only").optional(),language:z30.string().min(1).optional(),topic:z30.string().min(1).optional(),license:z30.string().min(1).optional(),minStars:z30.number().int().min(0).optional(),maxStars:z30.number().int().min(0).optional(),archived:z30.boolean().optional(),fork:z30.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(500).optional(),authors:z30.array(z30.string().min(1)).min(1).optional(),categories:z30.array(z30.string().min(1)).min(1).optional(),from:z30.iso.date().optional(),to:z30.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),query:z30.string().min(1).max(500).optional(),maxPassages:z30.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),intent:z30.string().min(1).max(500),mode:z30.enum(["similar","citers","references"]).optional(),maxResults:z30.number().int().min(1).max(500).optional(),rerank:z30.boolean().optional(),anchors:z30.array(z30.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z30.object({url:z30.string().url(),search:z30.string().min(1).optional(),limit:z30.number().int().positive().max(200).optional(),includeSubdomains:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z30.object({url:z30.string().url(),limit:z30.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z30.object({text:z30.string().min(1).max(200).optional(),cron:z30.string().min(1).max(120).optional(),timezone:z30.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z30.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z30.union([z30.object({type:z30.enum(["scrape","crawl"]).default("scrape"),urls:z30.array(z30.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z30.object({type:z30.literal("search"),queries:z30.array(z30.string().min(1).max(256)).min(1).max(12),searchWindow:z30.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z30.number().int().min(1).max(50).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z30.object({name:z30.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),notification:z30.object({email:z30.object({enabled:z30.boolean().default(!0),recipients:z30.array(z30.string().email()).min(1).max(20),includeDiffs:z30.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z30.object({monitorId:z30.string().uuid(),name:z30.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),status:z30.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z30.object({monitorId:z30.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z30.string().uuid()}),RunProjectIntegrationToolRequestSchema=z30.object({tool:z30.string().min(1),input:z30.record(z30.string(),z30.unknown()),connectionAlias:z30.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z30.object({provider:z30.string().min(1),providerCredits:z30.number().nonnegative().optional(),providerCostUsd:z30.number().nonnegative().optional(),requests:z30.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z30.object({credits:z30.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),json:z30.unknown().optional(),branding:z30.record(z30.string(),z30.unknown()).optional(),warning:z30.string().optional()}),FirecrawlSearchToolOutputSchema=z30.object({query:z30.string(),provider:z30.literal("firecrawl"),warning:z30.string().optional(),results:z30.array(z30.object({title:z30.string(),url:z30.string(),snippet:z30.string().optional(),content:z30.string().optional(),score:z30.number().optional(),publishedAt:z30.string().optional()}))}),FirecrawlResearchPaperSchema=z30.object({paperId:z30.string(),primaryId:z30.string().optional(),ids:z30.record(z30.string(),z30.array(z30.string())).optional(),title:z30.string().optional(),abstract:z30.string().optional(),score:z30.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z30.object({text:z30.string(),score:z30.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(z30.object({id:z30.string(),type:z30.string().min(1).optional(),url:z30.string(),title:z30.string().optional(),passages:z30.array(z30.object({text:z30.string()}).passthrough())}).passthrough()),coverage:z30.record(z30.string(),z30.string()).optional(),reranked:z30.boolean().optional(),repos:z30.array(z30.record(z30.string(),z30.unknown())).optional(),sources:z30.array(z30.record(z30.string(),z30.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),paper:z30.record(z30.string(),z30.unknown()),paperId:z30.string().optional(),query:z30.string().optional(),passages:z30.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema),poolSize:z30.number().int().nonnegative(),truncated:z30.boolean(),note:z30.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),count:z30.number(),links:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),description:z30.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),total:z30.number(),pages:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),warning:z30.string().optional()})),warning:z30.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z30.object({cron:z30.string().optional(),text:z30.string().optional(),timezone:z30.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z30.object({id:z30.string().optional(),type:z30.enum(["scrape","crawl","search"]).optional(),urls:z30.array(z30.string()).optional(),queries:z30.array(z30.string()).optional(),searchWindow:z30.string().optional(),maxResults:z30.number().optional(),includeDomains:z30.array(z30.string()).optional(),excludeDomains:z30.array(z30.string()).optional(),scrapeOptions:z30.record(z30.string(),z30.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z30.object({id:z30.string(),name:z30.string(),status:z30.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z30.string().nullable().optional(),lastRunAt:z30.string().nullable().optional(),currentCheckId:z30.string().nullable().optional(),targets:z30.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z30.string().nullable().optional(),judgeEnabled:z30.boolean().optional(),estimatedCreditsPerMonth:z30.number().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z30.object({id:z30.string(),monitorId:z30.string(),scheduledFor:z30.string().nullable().optional(),startedAt:z30.string().nullable().optional(),finishedAt:z30.string().nullable().optional(),estimatedCredits:z30.number().optional(),reservedCredits:z30.number().optional(),actualCredits:z30.number().optional(),billingStatus:z30.string().nullable().optional(),summary:z30.object({totalPages:z30.number().optional(),same:z30.number().optional(),changed:z30.number().optional(),new:z30.number().optional(),removed:z30.number().optional(),error:z30.number().optional()}).passthrough().optional(),error:z30.string().nullable().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitors:z30.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),deleted:z30.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),checks:z30.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),check:FirecrawlMonitorCheckOutputSchema,next:z30.string().optional()}),FirecrawlToolKeySchema=z30.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z30.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),tool:z30.string().min(1),connectionAlias:z30.string().min(1).nullable().optional(),output:z30.record(z30.string(),z30.unknown()),executedAt:z30.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z30.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z30.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z30.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z30.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z30.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z30.array(ProjectChannelCandidateDTOSchema))}});import{z as z31}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z31.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z31.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z31.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z31.object({userId:z31.string().min(1),name:z31.string(),email:z31.string().min(1),subscribed:z31.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z31.object({maxSubscribers:z31.number().int().positive(),subscriberCount:z31.number().int().nonnegative(),effectiveRecipientCount:z31.number().int().nonnegative(),currentUserSubscribed:z31.boolean(),candidates:z31.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z31.object({userIds:z31.array(z31.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z31.object({topic:UserManagedNotificationTopicSchema,enabled:z31.boolean(),source:z31.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z31.object({topics:z31.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z31.object({enabled:z31.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z31.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z31.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z31.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z31.string().nullable(),maskedEmail:z31.string().min(1),applied:z31.boolean(),expiresAt:z31.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z31.object({scheduleId:z31.string().min(1),scheduleName:z31.string(),projectId:z31.string().min(1),projectName:z31.string(),env:z31.string().min(1)}),FollowedSchedulesSchema=z31.object({schedules:z31.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z32}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z32.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z32.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z32.uuid(),env:z32.string().min(1),name:z32.string().min(1),cron:z32.string().min(1),command:z32.string().min(1),secretKeys:z32.array(z32.string().min(1)),enabled:z32.boolean(),lastRunAt:z32.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z32.string().nullable(),overPolicyReasons:z32.array(z32.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120),cron:z32.string().min(1).max(120),command:z32.string().min(1).max(500),secretKeys:z32.array(ProjectSecretKeySchema).default([]),enabled:z32.boolean().optional()}),UpdateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120).optional(),cron:z32.string().min(1).max(120).optional(),command:z32.string().min(1).max(500).optional(),secretKeys:z32.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z32.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z32.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z32.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z32.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z32.object({maxRuns:z32.number().int().positive(),retentionDays:z32.number().int().positive().nullable(),outputRetentionDays:z32.number().int().positive(),maxOutputBytes:z32.number().int().positive()}),SchedulePolicyStateSchema=z32.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z32.object({code:z32.enum(["Free","Premium","Pro"]),source:z32.enum(["cached_subscription","free_fallback"]),activeSchedules:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),concurrency:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),compute:z32.object({settledMs:z32.number().int().nonnegative(),reservedMs:z32.number().int().nonnegative(),includedMs:z32.number().int().positive(),remainingMs:z32.number().int().nonnegative(),resetsAt:z32.coerce.date()}),upgrade:z32.object({code:z32.literal("Pro"),activeSchedulesLimit:z32.number().int().positive(),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),maxConcurrentRuns:z32.number().int().positive(),computeIncludedMs:z32.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z32.array(z32.string())}),ProjectScheduleUsageSchema=z32.object({runCount:z32.number().int().nonnegative(),runsWithOutput:z32.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z32.object({id:z32.uuid(),scheduleId:z32.uuid(),projectId:z32.uuid(),env:z32.string().min(1),scheduleName:z32.string().min(1),command:z32.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z32.object({id:z32.string().min(1),name:z32.string().min(1)}).nullable(),queuedAt:z32.coerce.date(),startedAt:z32.coerce.date().nullable(),finishedAt:z32.coerce.date().nullable(),exitCode:z32.number().int().nullable(),errorCode:z32.string().nullable(),error:z32.string().nullable(),outputBytes:z32.number().int().nonnegative(),outputTruncated:z32.boolean(),outputExpiresAt:z32.coerce.date().nullable(),metadataExpiresAt:z32.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z32.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z32.coerce.date().nullable(),items:z32.array(z32.object({key:z32.string().min(1),updatedAt:z32.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z32.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z32.object({trigger:z32.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z32.object({limit:z32.coerce.number().int().min(1).max(100).default(25),cursor:z32.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z32.object({items:z32.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z32.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z32.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z32.object({items:z32.array(ProjectScheduleRunDTOSchema),nextCursor:z32.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z33}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z33.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z33.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z33.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("user"),userId:z33.string().min(1)}).strict(),z33.object({kind:z33.literal("agent"),agentKey:z33.string().min(1).max(120),agentId:z33.uuid().optional()}).strict(),z33.object({kind:z33.literal("system")}).strict()]),NotificationSummarySchema=z33.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z33.string().trim().min(1).max(120).optional(),brief:ReportBriefSchema.optional()},NotificationRunOutcomeSchema=z33.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z33.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z33.discriminatedUnion("topic",[z33.object({topic:z33.literal("agent_question"),questionId:z33.uuid(),title:z33.string().trim().min(1).max(80),description:z33.string().trim().min(1).max(240)}).strict(),z33.object({topic:z33.literal("agent_run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().optional(),proposalId:z33.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z33.object({id:z33.uuid(),projectId:z33.uuid(),sourceKey:z33.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z33.literal(1),payload:NotificationPayloadSchema,createdAt:z33.coerce.date()}),NotificationRecipientStateSchema=z33.object({id:z33.uuid(),notificationId:z33.uuid(),projectId:z33.uuid(),userId:z33.string().min(1),readAt:z33.coerce.date().nullable(),archivedAt:z33.coerce.date().nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationDeliveryStateSchema=z33.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z33.object({id:z33.uuid(),notificationRecipientId:z33.uuid(),projectId:z33.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z33.number().int().nonnegative(),nextAttemptAt:z33.coerce.date().nullable(),lastAttemptAt:z33.coerce.date().nullable(),sentAt:z33.coerce.date().nullable(),failureCode:z33.string().max(80).nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationPreferenceSchema=z33.object({topic:WorkNotificationTopicSchema,channel:z33.literal("email"),enabled:z33.boolean(),source:z33.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z33.object({topics:z33.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("question"),questionId:z33.uuid()}).strict(),z33.object({kind:z33.literal("run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z33.object({kind:z33.literal("retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().nullable(),proposalId:z33.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z33.object({kind:z33.literal("merge_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().nullable()}).strict()]),NotificationViewSchema=z33.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z33.object({items:z33.array(NotificationViewSchema),nextCursor:z33.string().nullable(),unreadCount:z33.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z33.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z33.string().min(1).max(120).optional(),sourceKey:z33.string().min(1).max(255).optional(),unread:z33.stringbool().optional(),archived:z33.stringbool().optional(),limit:z33.coerce.number().int().min(1).max(100).optional(),cursor:z33.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z33.object({recipient:NotificationRecipientStateSchema,unreadCount:z33.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z33.object({read:z33.boolean().optional(),archived:z33.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z34}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z34.object({id:z34.uuid(),occurredAt:z34.coerce.date(),projectId:z34.uuid().nullable(),env:z34.string().nullable(),actor:z34.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z34.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z34.unknown().optional(),ipAddress:z34.string().nullable().optional(),userAgent:z34.string().nullable().optional(),error:z34.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z34.object({rows:z34.array(AuditLogRowDTOSchema),nextCursor:z34.string().nullable()})),AuditLogQuerySchema=z34.object({env:z34.string().optional(),action:AuditActionSchema.optional(),actor:z34.string().optional(),from:z34.coerce.date().optional(),to:z34.coerce.date().optional(),limit:z34.coerce.number().int().min(1).max(200).optional(),cursor:z34.string().optional()})}});import{z as z35}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z35.object({surface:SurfaceNameSchema,key:z35.string(),label:z35.string()}),InlineSchema=z35.object({text:z35.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z35.discriminatedUnion("type",[z35.object({type:z35.literal("paragraph"),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("preview"),ref:DiffRefSchema,caption:z35.string().optional()}),z35.object({type:z35.literal("code"),code:z35.string(),lang:z35.string().optional(),caption:z35.string().optional()}),z35.object({type:z35.literal("risk"),level:z35.enum(["warning","error"]),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("list"),items:z35.array(z35.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z35.object({headline:z35.string(),blocks:z35.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z35.object({summary:EnvDiffSummarySchema,fingerprint:z35.string(),generatedAt:z35.coerce.date(),cached:z35.boolean().optional(),credits:z35.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z36}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z36.object({date:z36.string(),visitors:z36.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z36.object({key:z36.string(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z36.object({path:z36.string(),pageName:z36.string().nullable().optional(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z36.object({preset:z36.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z36.string(),requestedTo:z36.string(),effectiveFrom:z36.string(),effectiveTo:z36.string(),isRetentionLimited:z36.boolean(),groupBy:z36.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z36.object({date:z36.string(),content:z36.string(),updatedAt:z36.string(),updatedByUserId:z36.string()}),ProjectPageviewAnalyticsDTOSchema=z36.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative(),bounceRate:z36.number().min(0).max(100),viewsPerVisit:z36.number().nonnegative(),averageVisitDurationSeconds:z36.number().nonnegative(),visitorsSeries:z36.array(ProjectDailyVisitorsDTOSchema),topPages:z36.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z36.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z37}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z37.object({id:z37.string(),email:z37.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z37.coerce.date(),createdAt:z37.coerce.date(),inviterUserId:z37.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z37.object({id:z37.string(),token:z37.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z37.object({success:z37.boolean(),projectId:z37.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z38}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z38.object({id:z38.string(),name:z38.string(),image:z38.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z38.object({count:z38.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z38.object({counts:z38.object({signed_up:z38.int(),activated:z38.int()}),credits:z38.object({total:z38.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z38.email(),emailVerified:z38.boolean(),createdAt:z38.coerce.date(),updatedAt:z38.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z39}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z39.object({id:z39.string(),principalType:ProjectPrincipalTypeSchema,principalId:z39.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z39.coerce.date(),expiresAt:z39.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z39.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z39.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z39.record(z39.string(),z39.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z39.object({access:z39.array(ProjectAccessItemDTOSchema),invites:z39.array(ProjectInviteDTOSchema),organization:z39.object({name:z39.string().nullable(),logo:z39.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z39.object({success:z39.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z39.object({success:z39.boolean(),projectId:z39.uuid()}))}});import{z as z40}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z40.object({publicationStatus:PublicationStatusSchema,appUrl:z40.string().nullable(),lastPublishedAt:z40.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z41}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z41.object({url:z41.url(),expiresAt:z41.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z41.object({name:z41.string().min(1),locator:z41.string().min(1).optional(),source:z41.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z41.object({kind:z41.literal("dependency_build_scripts_blocked"),packageManager:z41.enum(["pnpm","yarn","bun"]),packages:z41.array(z41.string()),targets:z41.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z41.string(),approvalKey:z41.string(),command:z41.string().optional(),approval:z41.object({id:z41.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z41.object({code:z41.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z41.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z41.object({approvalId:z41.uuid()}),PreviewInstallPolicyApprovalEventSchema=z41.discriminatedUnion("type",[z41.object({type:z41.literal("progress"),step:z41.enum(["approval","install","restart","readiness"]),message:z41.string()}),z41.object({type:z41.literal("approved")}),z41.object({type:z41.literal("complete")}),z41.object({type:z41.literal("error"),code:z41.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z41.string()})])}});import{z as z42}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z42.string(),slug:z42.string().nullable(),logo:z42.string().nullable(),metadata:z42.record(z42.string(),z42.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),email:z42.email(),image:z42.string().nullable()}),OrganizationMemberDTOSchema=z42.object({id:z42.string(),userId:z42.string(),organizationId:z42.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z42.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z43}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z43.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z43.object({reason:CancellationReasonCodeSchema,details:z43.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z43.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z43.object({offerVersion:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),renewsOn:z43.string()}),PlanMigrationPreviewDTOSchema=z43.object({currency:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),startsAt:z43.string(),renewsAt:z43.string(),nextRenewalAmount:z43.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z43.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z43.object({id:z43.string(),organizationId:z43.string(),legacySubscriptionId:z43.string(),offeredPlanCode:z43.string(),offeredPlanName:z43.string(),offeredPriceAmount:z43.number(),offeredCurrency:z43.string(),offerVersion:z43.string(),state:PlanMigrationStateSchema,checkoutToken:z43.string().nullable(),deadlineAt:z43.string(),transitions:z43.array(z43.object({event:z43.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z43.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z43.object({included:z43.number().optional(),unitPrice:z43.number().optional(),dailyCap:z43.number().nullable().optional()}),EntitlementsDTOSchema=z43.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z43.object({retentionDays:z43.number().int().positive(),canUseExtendedDateRanges:z43.boolean()}).optional(),history:z43.object({retentionDays:z43.number().int().positive()}).optional(),members:z43.object({canInvite:z43.boolean(),maxMembers:z43.number().int().positive().nullable()}).optional(),domains:z43.object({canUseCustomDomains:z43.boolean(),maxDomains:z43.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z43.object({id:z43.string(),external_id:z43.string(),customerId:z43.string(),planId:z43.string(),planCode:z43.union([TemplateCodeSchema,z43.literal("Unknown")]),currentPeriod:z43.object({start:z43.string(),end:z43.string().nullable()}),cancelAt:z43.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z43.string(),nextPaymentAt:z43.string().nullable(),baseAmount:z43.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z43.object({totalCap:z43.number(),dailyCap:z43.number(),usedTotal:z43.number()}),CreditBalanceDTOSchema=z43.object({total:z43.number(),base:z43.number(),dailyBase:z43.number(),purchases:z43.number(),awards:z43.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z43.object({total:z43.number(),nearLimit:z43.boolean(),canChat:z43.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z43.object({dailyFreeAvailable:z43.number(),monthlyAvailable:z43.number(),purchasedAvailable:z43.number(),awardedAvailable:z43.number()}),ProjectDailyCreditAllowanceDTOSchema=z43.object({periodCap:z43.number(),dailyGrant:z43.number(),usedThisPeriod:z43.number(),remainingThisPeriod:z43.number()}),ProjectCreditBalanceDTOSchema=z43.object({projectId:z43.uuid(),organizationId:z43.string(),balance:z43.object({totalAvailable:z43.number(),nearLimit:z43.boolean(),canUseAi:z43.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z43.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z43.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z43.object({planCode:z43.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z43.object({source:z43.enum(["cached_subscription","free_fallback"]),settledMs:z43.number().int().nonnegative(),reservedMs:z43.number().int().nonnegative(),includedMs:z43.number().int().positive(),remainingMs:z43.number().int().nonnegative(),resetsAt:z43.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().nonnegative(),refillAmountUsd:z43.number().nonnegative()}),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().nonnegative().nullable(),refillAmountUsd:z43.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().min(.01).multipleOf(.01),refillAmountUsd:z43.number().min(.01).multipleOf(.01)}).strict(),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z43.object({invoiceId:z43.string(),newBalance:z43.int(),creditCount:z43.int(),amountUsd:z43.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z43.object({url:z43.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z44}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z44.object({brand:z44.string(),last4:z44.string(),exp:z44.string(),isDefault:z44.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z45}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z45.string().superRefine((path53,ctx)=>{let segments=path53.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z45.object({type:z45.literal("renameField"),contentType:z45.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z45.object({enabled:z45.boolean()}).strict(),ContentFieldGroupSchema=z45.object({id:z45.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z45.string().min(1).max(255),default:z45.boolean().optional()}).strict(),ContentTypeDTOSchema=z45.object({id:z45.string(),name:z45.string(),label:z45.string(),isSingleton:z45.boolean(),i18n:ContentTypeI18nSchema,groups:z45.array(ContentFieldGroupSchema).default([]),fields:z45.record(z45.string(),FieldDefinitionSchema),createdAt:z45.string(),updatedAt:z45.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z45.object({contentTypes:z45.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z45.object({id:z45.string(),entryId:z45.string(),documentId:z45.string(),slug:z45.string(),locale:z45.string().optional(),createdAt:z45.string(),updatedAt:z45.string(),__fimo:z45.object({contentType:z45.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({limit:z45.number(),offset:z45.number(),total:z45.number(),hasMore:z45.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z45.object({contentType:z45.string(),count:z45.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z45.object({counts:z45.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z45.object({count:z45.number().int().nonnegative(),sourceLocale:z45.string(),targetLocale:z45.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z45.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z45.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z45.union([z45.string(),z45.number(),z45.boolean(),z45.null()]),entryWhereOperatorSchema=z45.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z45.array(entryWhereScalarSchema).optional(),$nin:z45.array(entryWhereScalarSchema).optional(),$contains:z45.string().optional(),$startsWith:z45.string().optional(),$null:z45.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z45.object({data:z45.record(z45.string(),z45.unknown()),locale:z45.string().min(1).optional(),documentId:z45.uuid().optional()}),entryIdsSchema=z45.array(z45.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z45.object({sql:z45.string().min(1)}),BulkCreateEntriesRequestSchema=z45.object({entries:z45.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z45.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z45.object({updates:z45.array(z45.object({id:z45.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,locale:z45.string().min(1).optional()}),z45.object({where:EntryWhereSchema,locale:z45.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z45.object({data:z45.array(z45.record(z45.string(),z45.unknown())),meta:z45.object({rowCount:z45.number().int().nonnegative(),truncated:z45.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({created:z45.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({updated:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({deleted:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z46}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z46.object({index:z46.number().int().nonnegative(),contentType:z46.string(),field:z46.string(),value:z46.string(),against:z46.enum(["stored","batch"]),ownerDocumentId:z46.uuid().optional(),ownerIndex:z46.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z46.object({code:z46.literal("unique_conflict"),message:z46.string(),conflicts:z46.array(UniqueConflictSchema),truncated:z46.boolean().optional()})}});import{z as z47}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z47.object({kind:z47.literal("unique_conflict"),contentType:z47.string(),field:z47.string(),value:z47.string(),documentCount:z47.number().int().positive(),documentIds:z47.array(z47.uuid()),documentIdsTruncated:z47.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z47.object({code:z47.literal("schema_transition_rejected"),message:z47.string(),issues:z47.array(SchemaTransitionIssueSchema),truncated:z47.boolean().optional()})}});import{z as z48}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z48.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z48.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z48.object({field:CmsFieldNameSchema,direction:z48.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z48.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z48.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z48.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z48.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z48.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z49}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z49.object({id:z49.string(),name:z49.string()}),AssetDTOSchema=z49.object({id:z49.string(),name:z49.string(),type:AssetTypeSchema,originalFileName:z49.string().nullable(),parentId:z49.string().nullable(),mimeType:z49.string().nullable(),fileSize:z49.number().nullable(),url:z49.string().nullable(),storageKey:z49.string().nullable(),createdAt:z49.string(),updatedAt:z49.string(),altText:z49.string().nullable().optional(),caption:z49.string().nullable().optional(),aiCaption:z49.string().nullable().optional(),aiAltText:z49.string().nullable().optional(),aiTags:z49.array(z49.string()).nullable().optional(),aiPrimaryColor:z49.string().nullable().optional(),aiProcessingStatus:z49.string().nullable().optional(),width:z49.number().nullable().optional(),height:z49.number().nullable().optional(),path:z49.array(AssetPathItemSchema).optional(),hasChildren:z49.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z49.lazy(()=>z49.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z49.array(AssetDTOSchema))}});import{z as z50}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z50.object({key:z50.string(),value:z50.string().optional(),defaultValue:z50.string(),locale:z50.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z51}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z51.object({id:z51.string(),name:z51.string(),type:z51.enum(["file","folder"]),path:z51.string(),children:z51.lazy(()=>z51.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z51.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z51.object({path:z51.string(),exists:z51.boolean(),type:z51.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z52}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z52.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z52.object({items:z52.array(ProjectMessagePublicDTOSchema),nextCursor:z52.string().nullable()}),ChatLiveTurnDTOSchema=z52.object({invocationId:z52.string(),step:z52.enum(["preparing","working","compacting","merging"]),startedAt:z52.string()}),ChatLiveTurnStateDTOSchema=z52.object({threadId:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z52.object({id:z52.string(),role:z52.enum(["user","assistant"]),parts:z52.array(z52.unknown()),metadata:z52.record(z52.string(),z52.unknown()).nullable(),versionId:z52.string().nullable().optional(),createdAt:z52.date().transform(value=>value.toISOString()),providerMessageId:z52.string().nullable().optional(),invocationId:z52.string().nullable().optional(),invocationStatus:z52.string().nullable().optional(),invocationTerminalReason:z52.string().nullable().optional()}),ChatAttentionDTOSchema=z52.object({type:z52.literal("merge_conflict"),merge:z52.object({mergeId:z52.string().uuid(),projectId:z52.string(),fromEnv:z52.string(),toEnv:z52.string()}),publishAfterMerge:z52.boolean()}),ChatThreadMessagesPageDTOSchema=z52.object({threadId:z52.string().nullable(),title:z52.string().nullable(),messages:z52.array(ChatThreadMessageDTOSchema),nextCursor:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z52.object({kind:z52.literal("replay"),threadId:z52.string(),userMessageId:z52.string()}),ChatQueuedOutcomeDTOSchema=z52.object({kind:z52.literal("queued"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string()}),ChatBusyOutcomeDTOSchema=z52.object({kind:z52.literal("busy"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string().optional()}),ChatRefusedOutcomeDTOSchema=z52.object({kind:z52.literal("refused"),threadId:z52.string(),userMessageId:z52.string(),refusedInvocationId:z52.string(),terminalReason:z52.string()}),ChatNonStreamingOutcomeDTOSchema=z52.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z52.object({success:z52.boolean(),deletedCount:z52.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z52.object({code:z52.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z52.string()})}});import{z as z53}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z53.object({url:z53.string().url(),key:z53.string(),size:z53.number(),contentType:z53.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z54}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z54.object({canAccess:z54.boolean(),permissions:z54.record(z54.string(),z54.boolean()),role:z54.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z55}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z55.string().trim().default(""),sort:z55.enum(["recent","name","relevance"]).default("recent"),category:z55.string().optional()})}});import{z as z56}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z56.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z56.enum(["fimo","external"]),PaymentStatusSchema=z56.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z56.object({id:z56.string().uuid(),domain:z56.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z56.boolean(),price:z56.number().int().nullable(),renewalPrice:z56.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z56.string().nullable(),failureReason:z56.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z56.object({domain:z56.string(),available:z56.boolean(),premium:z56.boolean(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),purchaseType:z56.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z56.object({domain:z56.string(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),premium:z56.boolean(),allowedYears:z56.array(z56.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z56.object({firstName:z56.string().max(100),lastName:z56.string().max(100),companyName:z56.string().max(100).optional(),address1:z56.string().max(255),address2:z56.string().max(255).optional(),city:z56.string().max(100),state:z56.string().max(100),zip:z56.string().max(20),country:z56.string().max(2),phone:z56.string().max(30),email:z56.union([z56.string().email().max(255),z56.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z56.object({firstName:z56.string().min(1).max(100),lastName:z56.string().min(1).max(100),companyName:z56.string().max(100).optional(),address1:z56.string().min(1).max(255),address2:z56.string().max(255).optional(),city:z56.string().min(1).max(100),state:z56.string().min(1).max(100),zip:z56.string().min(1).max(20),country:z56.string().min(1).max(2),phone:z56.string().min(1).max(30),email:z56.string().email().max(255)}),SearchDomainsRequestSchema=z56.object({keyword:z56.string().min(1).max(100),tldFilter:z56.array(z56.string()).optional()}),CheckAvailabilityRequestSchema=z56.object({domains:z56.array(z56.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z56.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z56.object({domain:DomainNameSchema,years:z56.number().int().min(1).max(10).optional().default(3),autoRenew:z56.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z56.object({autoRenew:z56.boolean().optional()}),RenewDomainRequestSchema=z56.object({years:z56.number().int().min(1).max(10).optional().default(1),autoRenew:z56.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z56.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z56.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z56.object({verified:z56.boolean(),email:z56.string().nullable(),verifyBy:z56.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z57}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z57.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z57.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z57.object({txtName:z57.string().nullable().optional(),txtValue:z57.string().nullable().optional(),httpUrl:z57.string().nullable().optional(),httpBody:z57.string().nullable().optional(),cname:z57.string().nullable().optional(),cnameTarget:z57.string().nullable().optional()}),SSLValidationErrorSchema=z57.object({message:z57.string()}),OwnershipVerificationSchema=z57.object({type:z57.string(),name:z57.string(),value:z57.string()}),ProjectDomainSSLDTOSchema=z57.object({status:z57.string(),method:z57.string().nullable(),type:z57.string().nullable(),validationRecords:z57.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z57.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z57.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z57.enum(["subdomain","apex"]),RedirectConfigSchema=z57.object({type:z57.literal("apex_to_www"),linkedDomainId:z57.string()}).nullable().optional(),ProjectDomainDTOSchema=z57.object({id:z57.string(),hostname:z57.string(),status:z57.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z57.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z57.string(),scdCnameTarget:z57.string().optional(),apexTargets:z57.array(z57.string()),dnsAutoConfigured:z57.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z57.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z57.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z57.object({hostname:z57.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z57.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z57.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z57.object({success:z57.boolean(),hostname:z57.string()}))}});import{z as z58}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z58.object({slug:z58.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z58.object({subdomain:z58.string(),subdomainUpdatedAt:z58.coerce.date()})),SubdomainSuggestionsQuerySchema=z58.object({base:z58.string().max(100).optional(),max:z58.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z58.object({suggestions:z58.array(z58.string())}))}});import{z as z59}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z59.object({translated:z59.number().int().nonnegative(),total:z59.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z59.object({locale:z59.string(),isDefault:z59.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z59.object({defaultLocale:z59.string(),locales:z59.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z59.object({locale:z59.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z59.object({locale:z59.string().min(1).max(40)}),ProjectLocaleMutationSchema=z59.object({locale:z59.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z59.object({locale:z59.string(),entriesDeleted:z59.number().int().nonnegative(),labelsDeleted:z59.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z60}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z60.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z60.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z60.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z60.number(),credits:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),confidence:z60.enum(["exact","estimated","metered"]),basis:z60.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z61}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z61.object({options:z61.record(z61.string(),z61.unknown()),name:z61.string().optional(),parentId:z61.string().nullable().optional(),altText:z61.string().optional(),caption:z61.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z61.string().min(1).optional(),model:z61.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z61.object({jobId:z61.string(),status:z61.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z61.string().nullable().optional(),credits:z61.number().optional(),costUsd:z61.number().optional(),billingMode:z61.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z61.object({error:z61.string(),code:z61.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z61.array(GenerationTaskIdSchema).optional(),availableModels:z61.array(z61.string()).optional(),issues:z61.array(z61.unknown()).optional()})}});import{z as z62}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z62.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z62.object({name:z62.string(),key:z62.string(),description:z62.string(),type:FlagTypeSchema,required:z62.boolean(),defaultValue:z62.unknown().optional(),enumValues:z62.array(z62.string()).optional(),isArray:z62.boolean()}),AssetModelPriceSchema=z62.object({unitPrice:z62.number(),unit:z62.string(),confidence:z62.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z62.object({id:z62.string(),shortName:z62.string(),provider:z62.string(),source:z62.string(),modality:z62.enum(["image","video","audio"]),tags:z62.array(z62.string()),displayName:z62.string(),description:z62.string(),flags:z62.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z62.object({model:z62.string(),costUsd:z62.number(),credits:z62.number(),billingMode:z62.enum(["fimo-credits","provider-account"]),confidence:z62.enum(["exact","estimated","metered"]),basis:z62.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z63}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z63.object({tourId:z63.string(),version:z63.string(),status:z63.string(),completedAt:z63.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z63.array(UserTourDTOSchema))}});import{z as z64}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z64.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z64.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z64.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z64.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z64.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z64.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z64.enum(["user","agent","system"]),SupportReportTagSchema=z64.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z64.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z64.object({organization:z64.object({id:z64.string().trim().min(1).max(255),name:z64.string().trim().max(240).optional()}),project:z64.object({id:z64.uuid(),name:z64.string().trim().max(240).optional(),createdAt:z64.coerce.date().optional()}).optional(),environment:z64.string().trim().max(255).optional(),clientVersion:z64.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z64.string().trim().max(200).optional(),limit:z64.coerce.number().int().min(1).max(100).default(50),offset:z64.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z64.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z64.uuid().nullable().optional(),note:z64.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z64.object({kind:SupportReportLinkKindSchema,label:z64.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z64.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z64.object({kind:SupportReportActorKindSchema,id:z64.string().nullable(),name:z64.string().nullable()}),SupportReportLinkDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportLinkKindSchema,label:z64.string(),url:SupportReportHttpUrlSchema,externalId:z64.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportEventKindSchema,body:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()),actor:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z64.object({id:z64.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z64.array(z64.string()),source:SupportReportSourceSchema,message:z64.string(),reporter:z64.object({id:z64.string().nullable(),name:z64.string().nullable(),email:z64.string().nullable()}),organization:z64.object({id:z64.string().nullable(),name:z64.string()}),project:z64.object({id:z64.uuid().nullable(),name:z64.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z64.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z64.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z64.string().nullable(),deliveredAt:z64.coerce.date().nullable()}).nullable(),duplicateOfReportId:z64.uuid().nullable(),resolvedAt:z64.coerce.date().nullable(),createdAt:z64.coerce.date(),updatedAt:z64.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z64.string().nullable(),clientVersion:z64.string().nullable(),links:z64.array(SupportReportLinkDTOSchema),events:z64.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z64.object({reports:z64.array(SupportReportSummaryDTOSchema),total:z64.number().int().nonnegative(),statusCounts:z64.object({new:z64.number().int().nonnegative(),in_progress:z64.number().int().nonnegative(),waiting:z64.number().int().nonnegative(),resolved:z64.number().int().nonnegative(),duplicate:z64.number().int().nonnegative(),irrelevant:z64.number().int().nonnegative(),ignored:z64.number().int().nonnegative()}),limit:z64.number().int().positive(),offset:z64.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z64.object({id:z64.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z64.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z65}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z65.iso.datetime({offset:!0}).pipe(z65.coerce.date()),OpsRecentChatInputSchema=z65.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z65.string().trim().min(1).max(255).optional(),limit:z65.coerce.number().int().min(1).max(200).default(100),cursor:z65.string().trim().min(1).max(2e3).optional(),slim:z65.boolean().default(!0),reason:z65.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z65.object({id:z65.string(),threadId:z65.string(),providerMessageId:z65.string().nullable(),invocationId:z65.string().nullable(),env:z65.string().nullable(),role:z65.string(),parts:z65.array(z65.record(z65.string(),z65.unknown())),metadata:z65.object({status:z65.string().optional(),traceUrl:z65.string().optional(),externalFileChanges:z65.array(z65.unknown()).optional()}),stats:z65.object({toolCount:z65.number().int().nonnegative(),failedToolCount:z65.number().int().nonnegative()}),createdAt:z65.iso.datetime({offset:!0}),project:z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),organizationId:z65.string().nullable()})}),OpsRecentChatResponseSchema=z65.object({target:z65.object({backendProfile:OpsBackendProfileSchema,projectEnv:z65.string().nullable()}),window:z65.object({from:z65.iso.datetime({offset:!0}),to:z65.iso.datetime({offset:!0})}),messages:z65.object({items:z65.array(OpsRecentChatMessageSchema),nextCursor:z65.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z66}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z66.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z66.literal(!1),reason:z66.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z67}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z67.object({packageManager:z67.string().trim().min(1).max(200).nullable(),trackedLockfiles:z67.array(z67.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z67.string().trim().min(1)}),OpsProjectPackageManagerSchema=z67.object({target:z67.object({backendProfile:OpsBackendProfileSchema,projectId:z67.uuid(),projectEnv:z67.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z68}from"zod";function createAgentRunWebhookEventDataSchema(status){return z68.object({run:z68.object({id:z68.string(),agentName:z68.string(),trigger:z68.string(),status:z68.literal(status),startedAt:z68.string().nullable(),finishedAt:z68.string().nullable(),reason:z68.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z68.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z68.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z68.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z68.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z68.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z68.union([z68.literal(0),z68.literal(5),z68.literal(30),z68.literal(60)]),EntryChangedWebhookEventDataSchema=z68.object({reason:WebhookEntryChangeReasonSchema,operationId:z68.string().optional(),batch:z68.object({index:z68.number().int().positive(),total:z68.number().int().positive()}).optional(),changes:z68.array(z68.object({action:WebhookEntryChangeActionSchema,contentType:z68.string(),id:z68.string(),documentId:z68.string(),locale:z68.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z68.object({form:z68.object({id:z68.string(),label:z68.string()}),submission:z68.object({id:z68.string(),data:z68.record(z68.string(),z68.unknown()),submittedAt:z68.string()})}),PublishStartedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("publishing"),startedAt:z68.string()})}),PublishSucceededWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("published"),url:z68.string(),publishedAt:z68.string(),firstPublish:z68.boolean()})}),PublishFailedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("failed"),reason:z68.string()})}),PublishUnpublishedWebhookEventDataSchema=z68.object({publication:z68.object({previousUrl:z68.string(),unpublishedAt:z68.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),classification:z68.string(),summary:z68.string(),reasons:z68.array(z68.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),resolution:z68.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z68.object({report:z68.object({weekStart:z68.string(),weekEnd:z68.string(),pageviews:z68.number(),visitors:z68.number(),previousPageviews:z68.number(),previousVisitors:z68.number()})}),MediaAssetWebhookEventDataSchema=z68.object({id:z68.string().nullable(),name:z68.string().nullable(),type:z68.string(),mimeType:z68.string().nullable(),fileSize:z68.number().nullable()}),MediaUploadedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["updated","moved","analysis"]),analysis:z68.object({category:z68.string(),status:z68.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("generated"),generation:z68.object({model:z68.string(),mode:z68.string()})}),MediaProcessingFailedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["analysis","generation"]),failure:z68.object({code:z68.string()})}),DomainCreatedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string()})}),LabelChangedWebhookEventDataSchema=z68.object({changes:z68.array(z68.object({action:z68.enum(["created","updated","deleted"]),key:z68.string(),locale:z68.string(),value:z68.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),isDefault:z68.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),previousCode:z68.string()})}),LocaleDeletedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),entriesDeleted:z68.number().int().nonnegative(),labelsDeleted:z68.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z68.object({merge:z68.object({id:z68.string(),from:BranchSchema,to:BranchSchema,applied:z68.array(z68.object({surface:SurfaceNameSchema,count:z68.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema}),version:z68.object({versionId:z68.uuid(),name:z68.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z68.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z68.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z68.discriminatedUnion("source",[z68.object({source:z68.literal("literal"),value:z68.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z68.object({source:z68.literal("secret"),key:z68.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z68.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z68.object({name:z68.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z68.object({name:z68.string(),source:z68.enum(["literal","secret"]),secretKey:z68.string().nullable(),secretPrefix:z68.string().nullable(),configured:z68.literal(!0)}),WebhookFilterSchema=z68.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z68.string().min(1).max(255).optional(),agentName:z68.string().min(1).max(120).optional(),mediaType:z68.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z68.string().min(1).max(255).optional(),locale:z68.string().min(1).max(120).optional()}),JsonValueSchema=z68.lazy(()=>z68.union([z68.string(),z68.number(),z68.boolean(),z68.null(),z68.array(JsonValueSchema),z68.record(z68.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z68.url(),enabled:z68.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z68.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z68.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z68.url().optional(),enabled:z68.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z68.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z68.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z68.object({eventType:WebhookEventTypeSchema.optional(),data:z68.record(z68.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z68.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z68.uuid(),name:z68.string(),eventType:WebhookEventTypeSchema,enabled:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z68.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z68.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z68.coerce.date().nullable(),deliveryStats24h:z68.object({succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z68.uuid(),projectId:z68.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z68.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z68.number().int().positive(),test:z68.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z68.number().int().nonnegative(),responseStatus:z68.number().int().nullable(),lastErrorCode:z68.string().nullable(),lastErrorMessage:z68.string().nullable(),payloadAvailable:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z68.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z68.string().nullable(),qstashMessageId:z68.string().nullable(),deliveredAt:z68.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z68.object({items:z68.array(WebhookDeliveryDTOSchema),pagination:z68.object({page:z68.number().int().positive(),limit:z68.number().int().positive(),total:z68.number().int().nonnegative(),totalPages:z68.number().int().positive(),hasMore:z68.boolean()}),stats:z68.object({total:z68.number().int().nonnegative(),succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z68.object({id:z68.uuid(),deliveryId:z68.uuid(),attempt:z68.number().int().positive(),status:z68.enum(["delivering","succeeded","failed"]),responseStatus:z68.number().int().nullable(),durationMs:z68.number().int().nonnegative(),responseExcerpt:z68.string().nullable(),errorCode:z68.string().nullable(),errorMessage:z68.string().nullable(),createdAt:z68.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z68.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z68.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z69}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z69.object({key:z69.literal("fimo-2"),enabled:z69.boolean(),dismissed:z69.boolean().default(!1),interacted:z69.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z70}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z70.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z70.object({total:z70.number(),base:z70.number(),purchases:z70.number(),awards:z70.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z70.object({id:z70.string(),name:z70.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z70.object({type:z70.string(),brand:z70.string().nullable(),last4:z70.string().nullable(),expirationDate:z70.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z70.object({currency:z70.string(),nextPaymentAmount:z70.number().nullable(),nextPaymentAt:z70.string().nullable(),billingInterval:z70.string().nullable(),totalAmount:z70.number().nullable(),discountAmount:z70.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z70.object({id:z70.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z70.string().nullable(),currentPeriodEndsAt:z70.string().nullable(),renewsAt:z70.string().nullable(),cancelAt:z70.string().nullable(),renewAutomatically:z70.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z70.object({type:z70.enum(["low_balance","critical_balance","approaching_limit"]),message:z70.string(),estimatedPromptsRemaining:z70.number().nullable(),avgCostPerPrompt:z70.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z70.object({monthlyCredits:z70.number().nullable(),usedThisPeriod:z70.number(),remainingThisPeriod:z70.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z70.object({organizationId:z70.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z70.string().nullable(),tenureDays:z70.number().int().nonnegative(),capturedAt:z70.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z70.object({hasSubscription:z70.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z70.number().nullable(),alerts:z70.array(CreditAlertDTOSchema),portalUrl:z70.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z70.object({creditCount:z70.number().int().positive(),expiresAt:z70.string().datetime().nullable().optional(),message:z70.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("free"),amountCents:z70.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("purchase"),amountCents:z70.number().int().positive()}),CreditTopupRequestDTOSchema=z70.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z70.object({success:z70.boolean(),transactionId:z70.string().nullable(),newBalance:z70.number(),creditCount:z70.number(),type:z70.enum(["free","purchase"]),invoiceId:z70.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z71}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),periodStart:z71.string().nullable(),periodEnd:z71.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z71.array(UsageByUserForProjectDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z71.object({summary:UsageSummaryDTOSchema,byProject:z71.array(UsageByProjectDTOSchema),byUser:z71.array(UsageByUserDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z72}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z72.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z72.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z72.object({startDate:z72.string().optional(),endDate:z72.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z72.coerce.number().int().positive().default(1),limit:z72.coerce.number().int().positive().max(100).default(20),sortBy:z72.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z72.string().optional(),activeOnly:z72.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z72.object({totalCredits:z72.number(),totalCostUsd:z72.number(),totalMessages:z72.number(),avgCostPerMessage:z72.number(),avgCreditsPerMessage:z72.number(),periodStart:z72.string(),periodEnd:z72.string(),creditsChange:z72.number().nullable(),costChange:z72.number().nullable(),messagesChange:z72.number().nullable(),unattributedCredits:z72.number(),unattributedCostUsd:z72.number(),unattributedMessages:z72.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z72.object({date:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z72.object({organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number(),projectCount:z72.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z72.object({userId:z72.string(),userName:z72.string().nullable(),userEmail:z72.string().nullable(),userImage:z72.string().nullable(),organizationId:z72.string().nullable(),organizationName:z72.string().nullable(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),projectCount:z72.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z72.object({projectId:z72.string(),projectName:z72.string(),projectDisplayName:z72.string().nullable(),organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z72.object({id:z72.string(),name:z72.string(),value:z72.number(),percentage:z72.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z72.object({day:z72.number(),hour:z72.number(),value:z72.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z72.object({summary:UsageOverviewSummaryDTOSchema,timeline:z72.array(UsageTimelinePointDTOSchema),topOrganizations:z72.array(OrganizationUsageRowDTOSchema),topUsers:z72.array(UserUsageRowDTOSchema),topProjects:z72.array(ProjectUsageRowDTOSchema),creditDistribution:z72.array(UsageDistributionItemDTOSchema),userDistribution:z72.array(UsageDistributionItemDTOSchema),heatmap:z72.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z72.object({page:z72.number(),limit:z72.number(),totalItems:z72.number(),totalPages:z72.number(),hasMore:z72.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z72.object({organizations:z72.array(OrganizationUsageRowDTOSchema),top:z72.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z72.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z72.object({users:z72.array(ExtendedUserUsageRowDTOSchema),top:z72.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z72.object({projects:z72.array(ExtendedProjectUsageRowDTOSchema),top:z72.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z72.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z72.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z72.object({credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),createdAt:z72.string(),memberCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z72.object({id:z72.string(),name:z72.string().nullable(),email:z72.string(),image:z72.string().nullable(),createdAt:z72.string(),organizationCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),displayName:z72.string().nullable(),createdAt:z72.string(),organizationId:z72.string(),organizationName:z72.string(),ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z73}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z73.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z73.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z73.object({command:z73.string().min(1).max(1e4),cwd:z73.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z73.record(z73.string(),z73.string()).optional(),name:z73.string().optional(),waitForCompletion:z73.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=z73.object({identifier:z73.string(),status:SandboxProcessStatusSchema,command:z73.string().optional(),startedAt:z73.string().optional(),exitCode:z73.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z73.object({processes:z73.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z73.object({processId:z73.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z73.object({success:z73.boolean(),message:z73.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z74}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}branch;withBranch(branch){let next2=new _FimoApiClient(this.cfg);return next2.branch=branch,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path53,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch),fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers})}async rawRequest(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path53} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: tenant-scoped call requires a Branch. Use `client.withBranch(branch)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}projectBranchManagementPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: Branch-scoped management call requires a Branch. Use `client.withBranch(branch)` before calling Branch CRUD methods.");return`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectBranchManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listBranches(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentBranches&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/branches${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listBranches(projectId,{includeAgentBranches:!0}),current=branches.find(candidate=>branchNameOf(candidate)===branch),visited=new Set;for(;current&&!visited.has(branchNameOf(current));){if(visited.add(branchNameOf(current)),current.resolvedEnvironment)return current.resolvedEnvironment.id;let parent2=parentBranchOf(current);current=parent2?branches.find(candidate=>branchNameOf(candidate)===parent2):void 0}return PREVIEW_ENVIRONMENT_KEY}async getBranch(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`)).data}async createBranch(projectId,input){return(await this.request(`/api/management/projects/${projectId}/branches`,{method:"POST",body:JSON.stringify(input)})).data}async syncBranch(projectId,branch,input={}){let body=await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sync`,{method:"POST",body:JSON.stringify(input)});return{branch:body.data.branch??body.data.env,conflicts:body.data.conflicts}}async deleteBranch(projectId,branch){await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`,{method:"DELETE"})}async getBranchDiff(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,branch,path53,opts={}){let qs=lazyFetchQs(opts.against,{path:path53});return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,branch,fromBranch,filePath){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,branch,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getSchemaTypeDiff(projectId,branch,typeName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getAssetDiff(projectId,branch,assetId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getTranslationRowDiff(projectId,branch,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getFormSchemaDiff(projectId,branch,formName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async mergeBranch(projectId,branch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,branch,mergeId){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflicts`)).data}async putResolveDraft(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,branch,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.branch&¶ms.set("env",opts.branch),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,branch){let remote=(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,branch);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectBranchManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox`)).data}async getSandboxLogs(projectId,branch,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
60
|
+
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),ReportSeriesBlockSchema=z15.object({type:z15.literal("series"),...blockCommon,unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."})}),ReportFindingsBlockSchema=z15.object({type:z15.literal("findings"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema,label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Several ranked problems, risks, or recommendations. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index2)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportImageBlockSchema=z15.object({type:z15.literal("image"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual evidence or a visual deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53){return pageRouteParamNames(path53).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z17}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),previewEnabled:z17.boolean().default(!0),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z22.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z22.object({type:z22.literal("manual")}),ScheduleTriggerSchema=z22.object({type:z22.literal("schedule"),cron:z22.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z22.string().optional()}),WebhookTriggerSchema=z22.object({type:z22.literal("webhook"),path:z22.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z22.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z23}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z23.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z23.object({token:z23.string().min(1),risk:CapabilityRiskTierSchema,description:z23.string()}),AgentSubAgentSummarySchema=z23.object({name:z23.string().min(1),grant:z23.enum(["inherit","explicit"]),effectiveCaps:z23.array(z23.string().min(1))}),AgentInstallSummaryDTOSchema=z23.object({agentName:z23.string().min(1),env:z23.string().min(1),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z23.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z23.array(CapabilitySummaryEntrySchema),criticalCapabilities:z23.array(CapabilitySummaryEntrySchema),subAgents:z23.array(AgentSubAgentSummarySchema),declaresDelegate:z23.boolean(),cycle:z23.array(z23.string()).nullable(),missingSubAgents:z23.array(z23.string()),warnings:z23.array(z23.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z24}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z24.object({kind:TriggerKindSchema,summary:z24.string()}),AgentListItemTriggerStateSchema=z24.object({triggerIndex:z24.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z24.boolean(),wired:z24.boolean(),syncError:z24.string().nullable()}),AgentListItemDTOSchema=z24.object({name:z24.string().min(1),description:z24.string().nullable(),goalFirstLine:z24.string().nullable(),declaredCapabilities:z24.array(CapabilitySummaryEntrySchema),triggers:z24.array(AgentListItemTriggerSchema),triggerStates:z24.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z25.object({args:z25.unknown().optional(),requestId:z25.string().min(1).max(128).optional()}),DispatchSkippedSchema=z25.object({skipped:z25.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z25.object({sessionId:z25.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z25.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z26.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:BranchSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z27.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z27.object({cpuMs:z27.number().nonnegative().default(0),netBytes:z27.number().nonnegative().default(0),walltimeMs:z27.number().nonnegative().default(0),llmTokensIn:z27.number().nonnegative().optional(),llmTokensOut:z27.number().nonnegative().optional(),stepCount:z27.number().int().nonnegative().optional(),toolCallCounts:z27.record(z27.string().min(1).max(120),z27.number().int().nonnegative()).optional(),toolCallOutcomes:z27.array(z27.object({toolName:z27.string().min(1).max(120),success:z27.boolean(),code:z27.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z27.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z27.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z27.object({capturedAt:z27.coerce.date(),fingerprint:z27.string().min(1).max(256),counts:z27.object({code:z27.number().int().nonnegative(),content:z27.number().int().nonnegative(),schemas:z27.number().int().nonnegative(),labels:z27.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z27.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z27.object({diff:DiffReportSchema,code:z27.array(CodeFileDiffSchema.extend({raw:z27.string().max(24576)})).max(200),schemas:z27.array(SchemaTypeDiffSchema).max(200),content:z27.array(z27.object({key:z27.string().min(1).max(512),collection:z27.string().min(1).max(256),slug:z27.string().max(512).optional(),verb:z27.enum(["added","modified","deleted"]),fields:z27.array(z27.object({name:z27.string().min(1).max(256),before:z27.unknown().optional(),after:z27.unknown().optional()})).max(20)})).max(200),labels:z27.array(z27.object({key:z27.string().min(1).max(512),locale:z27.string().min(1).max(64).optional(),before:z27.unknown().nullable(),after:z27.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z27.object({id:z27.uuid(),projectId:z27.uuid(),env:BranchSchema,agentName:z27.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z27.unknown().optional(),capabilities:z27.array(z27.string()).optional(),dataSources:z27.array(z27.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z27.string().nullable(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),cancelledAt:z27.coerce.date().nullable(),costUsd:z27.number().nonnegative(),costCeilingUsd:z27.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z27.boolean(),lastCheckpointId:z27.uuid().nullable(),branchEnvId:z27.uuid().nullable(),parentSessionId:z27.uuid().nullable(),terminalReason:z27.string().nullable(),errorMessage:z27.string().nullable(),reportDocument:ReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z27.object({id:z27.uuid(),sessionId:z27.uuid(),checkpointIdx:z27.number().int().nonnegative(),payloadRef:z27.string(),payloadSizeBytes:z27.number().int().nonnegative(),checksum:z27.string().length(64),createdAt:z27.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z27.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z27.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z27.object({session:AgentSessionDTOSchema,checkpoints:z27.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z27.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z27.object({reason:z27.string().min(1).max(120).optional()})}});import{z as z28}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z28.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z28.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z28.object({id:z28.uuid(),envId:z28.uuid(),sessionId:z28.uuid().nullable(),skillName:z28.string().min(1),classification:AgentBranchClassificationSchema,rationale:z28.string().nullable(),summary:z28.string().nullable(),surfaceDeltas:z28.record(z28.string(),z28.unknown()),createdAt:z28.coerce.date(),decidedAt:z28.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z28.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z28.object({path:z28.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z28.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z28.object({code:z28.literal("merge_conflict"),message:z28.string(),conflicts:z28.record(z28.string(),z28.number().int().nonnegative())})}});import{z as z29}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z29.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z29.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z29.object({description:z29.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z29.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),threadId:z29.uuid(),invocationId:z29.uuid(),agentKey:z29.string().min(1).max(120),anchorEnv:z29.string().min(1).max(64),retainedEnv:z29.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z29.string().min(1).nullable(),continuationInvocationId:z29.uuid().nullable(),askedAt:z29.coerce.date(),expiresAt:z29.coerce.date(),closedAt:z29.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z29.object({questionId:z29.uuid(),invocationId:z29.uuid(),askedAt:z29.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z29.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z29.object({question:AgentQuestionSchema,continuationInvocationId:z29.uuid(),deduped:z29.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z30}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z30.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z30.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z30.enum(["secret_text"]),IntegrationCredentialUsageSchema=z30.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z30.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z30.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z30.object({mode:IntegrationAuthModeSchema,label:z30.string().min(1),description:z30.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z30.object({id:z30.string().min(1),label:z30.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z30.boolean()}),IntegrationToolDefinitionDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),description:z30.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z30.object({title:z30.string().min(1),description:z30.string().min(1),command:z30.string().min(1).optional()}),IntegrationInfoDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),type:z30.enum(["native","mcp"]).optional(),url:z30.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z30.array(IntegrationAuthModeDTOSchema),credentials:z30.array(IntegrationCredentialDefinitionDTOSchema),tools:z30.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z30.enum(["available","unavailable"]).optional(),recipes:z30.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),installed:z30.boolean(),enabled:z30.boolean(),setupState:z30.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z30.string().nullable(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),connectionStatus:z30.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),installedAt:z30.coerce.date().nullable(),updatedAt:z30.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),enabled:z30.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z30.string(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z30.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z30.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z30.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z30.object({value:z30.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z30.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z30.object({id:z30.uuid(),organizationId:z30.string().min(1),integrationKey:z30.string().min(1),alias:z30.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z30.string().min(1),externalAccountName:z30.string().nullable(),externalBotUserId:z30.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z30.array(z30.string()),connectedAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z30.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z30.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z30.record(McpHeaderNameSchema,z30.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z30.object({alias:z30.string().min(1).max(120).optional(),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z30.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),alias:z30.string().min(1).max(120),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}),z30.object({mode:z30.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z30.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z30.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z30.union([z30.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z30.object({type:z30.literal("mcp"),name:z30.string().trim().min(1).max(120),url:z30.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z30.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z30.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z30.object({integrationKey:z30.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z30.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("oauth"),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),ReusableMcpServerAuthKindSchema=z30.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z30.object({id:z30.uuid(),name:z30.string().min(1),host:z30.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z30.string().min(1),availability:z30.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z30.object({query:z30.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z30.object({serverId:z30.uuid()}),StartProjectIntegrationConnectResponseSchema=z30.object({integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),integrationKey:z30.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z30.object({mode:z30.literal("oauth"),integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),BindProjectChannelRequestSchema=z30.object({ref:z30.string().min(1),connectionAlias:z30.string().min(1).optional(),agentName:z30.string().min(1).max(160).nullable().optional(),force:z30.boolean().optional()}),ListProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1)}),SearchProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1),connectionAlias:z30.string().min(1),query:z30.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),connectionId:z30.uuid(),externalWorkspaceId:z30.string().min(1),externalChannelId:z30.string().min(1),externalChannelName:z30.string().nullable(),agentName:z30.string().nullable(),enabled:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z30.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z30.object({id:z30.string().min(1),name:z30.string().min(1),visibility:z30.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z30.string().min(1).nullable(),canMove:z30.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z30.object({markdown:z30.boolean().optional(),summary:z30.boolean().optional(),links:z30.boolean().optional(),branding:z30.boolean().optional(),images:z30.boolean().optional(),html:z30.union([z30.literal("cleaned"),z30.literal("raw"),z30.boolean()]).optional(),json:z30.union([z30.boolean(),z30.object({prompt:z30.string().min(1).max(1e4),schema:z30.record(z30.string(),z30.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z30.object({url:z30.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z30.object({query:z30.string().min(1),maxResults:z30.number().int().positive().max(20).optional(),sources:z30.array(z30.enum(["web","news","images"])).min(1).max(3).optional(),categories:z30.array(z30.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z30.enum(["hour","day","week","month","year"]).optional(),location:z30.string().min(1).max(160).optional(),country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(100).optional(),types:z30.array(z30.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),sources:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),passages:z30.number().int().min(1).max(5).optional(),skills:z30.literal("only").optional(),language:z30.string().min(1).optional(),topic:z30.string().min(1).optional(),license:z30.string().min(1).optional(),minStars:z30.number().int().min(0).optional(),maxStars:z30.number().int().min(0).optional(),archived:z30.boolean().optional(),fork:z30.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(500).optional(),authors:z30.array(z30.string().min(1)).min(1).optional(),categories:z30.array(z30.string().min(1)).min(1).optional(),from:z30.iso.date().optional(),to:z30.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),query:z30.string().min(1).max(500).optional(),maxPassages:z30.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),intent:z30.string().min(1).max(500),mode:z30.enum(["similar","citers","references"]).optional(),maxResults:z30.number().int().min(1).max(500).optional(),rerank:z30.boolean().optional(),anchors:z30.array(z30.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z30.object({url:z30.string().url(),search:z30.string().min(1).optional(),limit:z30.number().int().positive().max(200).optional(),includeSubdomains:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z30.object({url:z30.string().url(),limit:z30.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z30.object({text:z30.string().min(1).max(200).optional(),cron:z30.string().min(1).max(120).optional(),timezone:z30.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z30.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z30.union([z30.object({type:z30.enum(["scrape","crawl"]).default("scrape"),urls:z30.array(z30.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z30.object({type:z30.literal("search"),queries:z30.array(z30.string().min(1).max(256)).min(1).max(12),searchWindow:z30.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z30.number().int().min(1).max(50).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z30.object({name:z30.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),notification:z30.object({email:z30.object({enabled:z30.boolean().default(!0),recipients:z30.array(z30.string().email()).min(1).max(20),includeDiffs:z30.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z30.object({monitorId:z30.string().uuid(),name:z30.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),status:z30.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z30.object({monitorId:z30.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z30.string().uuid()}),RunProjectIntegrationToolRequestSchema=z30.object({tool:z30.string().min(1),input:z30.record(z30.string(),z30.unknown()),connectionAlias:z30.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z30.object({provider:z30.string().min(1),providerCredits:z30.number().nonnegative().optional(),providerCostUsd:z30.number().nonnegative().optional(),requests:z30.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z30.object({credits:z30.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),json:z30.unknown().optional(),branding:z30.record(z30.string(),z30.unknown()).optional(),warning:z30.string().optional()}),FirecrawlSearchToolOutputSchema=z30.object({query:z30.string(),provider:z30.literal("firecrawl"),warning:z30.string().optional(),results:z30.array(z30.object({title:z30.string(),url:z30.string(),snippet:z30.string().optional(),content:z30.string().optional(),score:z30.number().optional(),publishedAt:z30.string().optional()}))}),FirecrawlResearchPaperSchema=z30.object({paperId:z30.string(),primaryId:z30.string().optional(),ids:z30.record(z30.string(),z30.array(z30.string())).optional(),title:z30.string().optional(),abstract:z30.string().optional(),score:z30.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z30.object({text:z30.string(),score:z30.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(z30.object({id:z30.string(),type:z30.string().min(1).optional(),url:z30.string(),title:z30.string().optional(),passages:z30.array(z30.object({text:z30.string()}).passthrough())}).passthrough()),coverage:z30.record(z30.string(),z30.string()).optional(),reranked:z30.boolean().optional(),repos:z30.array(z30.record(z30.string(),z30.unknown())).optional(),sources:z30.array(z30.record(z30.string(),z30.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),paper:z30.record(z30.string(),z30.unknown()),paperId:z30.string().optional(),query:z30.string().optional(),passages:z30.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema),poolSize:z30.number().int().nonnegative(),truncated:z30.boolean(),note:z30.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),count:z30.number(),links:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),description:z30.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),total:z30.number(),pages:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),warning:z30.string().optional()})),warning:z30.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z30.object({cron:z30.string().optional(),text:z30.string().optional(),timezone:z30.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z30.object({id:z30.string().optional(),type:z30.enum(["scrape","crawl","search"]).optional(),urls:z30.array(z30.string()).optional(),queries:z30.array(z30.string()).optional(),searchWindow:z30.string().optional(),maxResults:z30.number().optional(),includeDomains:z30.array(z30.string()).optional(),excludeDomains:z30.array(z30.string()).optional(),scrapeOptions:z30.record(z30.string(),z30.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z30.object({id:z30.string(),name:z30.string(),status:z30.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z30.string().nullable().optional(),lastRunAt:z30.string().nullable().optional(),currentCheckId:z30.string().nullable().optional(),targets:z30.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z30.string().nullable().optional(),judgeEnabled:z30.boolean().optional(),estimatedCreditsPerMonth:z30.number().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z30.object({id:z30.string(),monitorId:z30.string(),scheduledFor:z30.string().nullable().optional(),startedAt:z30.string().nullable().optional(),finishedAt:z30.string().nullable().optional(),estimatedCredits:z30.number().optional(),reservedCredits:z30.number().optional(),actualCredits:z30.number().optional(),billingStatus:z30.string().nullable().optional(),summary:z30.object({totalPages:z30.number().optional(),same:z30.number().optional(),changed:z30.number().optional(),new:z30.number().optional(),removed:z30.number().optional(),error:z30.number().optional()}).passthrough().optional(),error:z30.string().nullable().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitors:z30.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),deleted:z30.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),checks:z30.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),check:FirecrawlMonitorCheckOutputSchema,next:z30.string().optional()}),FirecrawlToolKeySchema=z30.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z30.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),tool:z30.string().min(1),connectionAlias:z30.string().min(1).nullable().optional(),output:z30.record(z30.string(),z30.unknown()),executedAt:z30.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z30.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z30.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z30.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z30.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z30.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z30.array(ProjectChannelCandidateDTOSchema))}});import{z as z31}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z31.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z31.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z31.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z31.object({userId:z31.string().min(1),name:z31.string(),email:z31.string().min(1),subscribed:z31.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z31.object({maxSubscribers:z31.number().int().positive(),subscriberCount:z31.number().int().nonnegative(),effectiveRecipientCount:z31.number().int().nonnegative(),currentUserSubscribed:z31.boolean(),candidates:z31.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z31.object({userIds:z31.array(z31.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z31.object({topic:UserManagedNotificationTopicSchema,enabled:z31.boolean(),source:z31.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z31.object({topics:z31.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z31.object({enabled:z31.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z31.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z31.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z31.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z31.string().nullable(),maskedEmail:z31.string().min(1),applied:z31.boolean(),expiresAt:z31.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z31.object({scheduleId:z31.string().min(1),scheduleName:z31.string(),projectId:z31.string().min(1),projectName:z31.string(),env:z31.string().min(1)}),FollowedSchedulesSchema=z31.object({schedules:z31.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z32}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z32.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z32.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z32.uuid(),env:z32.string().min(1),name:z32.string().min(1),cron:z32.string().min(1),command:z32.string().min(1),secretKeys:z32.array(z32.string().min(1)),enabled:z32.boolean(),lastRunAt:z32.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z32.string().nullable(),overPolicyReasons:z32.array(z32.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120),cron:z32.string().min(1).max(120),command:z32.string().min(1).max(500),secretKeys:z32.array(ProjectSecretKeySchema).default([]),enabled:z32.boolean().optional()}),UpdateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120).optional(),cron:z32.string().min(1).max(120).optional(),command:z32.string().min(1).max(500).optional(),secretKeys:z32.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z32.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z32.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z32.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z32.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z32.object({maxRuns:z32.number().int().positive(),retentionDays:z32.number().int().positive().nullable(),outputRetentionDays:z32.number().int().positive(),maxOutputBytes:z32.number().int().positive()}),SchedulePolicyStateSchema=z32.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z32.object({code:z32.enum(["Free","Premium","Pro"]),source:z32.enum(["cached_subscription","free_fallback"]),activeSchedules:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),concurrency:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),compute:z32.object({settledMs:z32.number().int().nonnegative(),reservedMs:z32.number().int().nonnegative(),includedMs:z32.number().int().positive(),remainingMs:z32.number().int().nonnegative(),resetsAt:z32.coerce.date()}),upgrade:z32.object({code:z32.literal("Pro"),activeSchedulesLimit:z32.number().int().positive(),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),maxConcurrentRuns:z32.number().int().positive(),computeIncludedMs:z32.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z32.array(z32.string())}),ProjectScheduleUsageSchema=z32.object({runCount:z32.number().int().nonnegative(),runsWithOutput:z32.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z32.object({id:z32.uuid(),scheduleId:z32.uuid(),projectId:z32.uuid(),env:z32.string().min(1),scheduleName:z32.string().min(1),command:z32.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z32.object({id:z32.string().min(1),name:z32.string().min(1)}).nullable(),queuedAt:z32.coerce.date(),startedAt:z32.coerce.date().nullable(),finishedAt:z32.coerce.date().nullable(),exitCode:z32.number().int().nullable(),errorCode:z32.string().nullable(),error:z32.string().nullable(),outputBytes:z32.number().int().nonnegative(),outputTruncated:z32.boolean(),outputExpiresAt:z32.coerce.date().nullable(),metadataExpiresAt:z32.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z32.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z32.coerce.date().nullable(),items:z32.array(z32.object({key:z32.string().min(1),updatedAt:z32.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z32.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z32.object({trigger:z32.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z32.object({limit:z32.coerce.number().int().min(1).max(100).default(25),cursor:z32.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z32.object({items:z32.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z32.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z32.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z32.object({items:z32.array(ProjectScheduleRunDTOSchema),nextCursor:z32.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z33}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z33.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z33.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z33.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("user"),userId:z33.string().min(1)}).strict(),z33.object({kind:z33.literal("agent"),agentKey:z33.string().min(1).max(120),agentId:z33.uuid().optional()}).strict(),z33.object({kind:z33.literal("system")}).strict()]),NotificationSummarySchema=z33.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z33.string().trim().min(1).max(120).optional(),brief:ReportBriefSchema.optional()},NotificationRunOutcomeSchema=z33.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z33.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z33.discriminatedUnion("topic",[z33.object({topic:z33.literal("agent_question"),questionId:z33.uuid(),title:z33.string().trim().min(1).max(80),description:z33.string().trim().min(1).max(240)}).strict(),z33.object({topic:z33.literal("agent_run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().optional(),proposalId:z33.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z33.object({id:z33.uuid(),projectId:z33.uuid(),sourceKey:z33.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z33.literal(1),payload:NotificationPayloadSchema,createdAt:z33.coerce.date()}),NotificationRecipientStateSchema=z33.object({id:z33.uuid(),notificationId:z33.uuid(),projectId:z33.uuid(),userId:z33.string().min(1),readAt:z33.coerce.date().nullable(),archivedAt:z33.coerce.date().nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationDeliveryStateSchema=z33.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z33.object({id:z33.uuid(),notificationRecipientId:z33.uuid(),projectId:z33.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z33.number().int().nonnegative(),nextAttemptAt:z33.coerce.date().nullable(),lastAttemptAt:z33.coerce.date().nullable(),sentAt:z33.coerce.date().nullable(),failureCode:z33.string().max(80).nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationPreferenceSchema=z33.object({topic:WorkNotificationTopicSchema,channel:z33.literal("email"),enabled:z33.boolean(),source:z33.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z33.object({topics:z33.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("question"),questionId:z33.uuid()}).strict(),z33.object({kind:z33.literal("run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z33.object({kind:z33.literal("retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().nullable(),proposalId:z33.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z33.object({kind:z33.literal("merge_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().nullable()}).strict()]),NotificationViewSchema=z33.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z33.object({items:z33.array(NotificationViewSchema),nextCursor:z33.string().nullable(),unreadCount:z33.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z33.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z33.string().min(1).max(120).optional(),sourceKey:z33.string().min(1).max(255).optional(),unread:z33.stringbool().optional(),archived:z33.stringbool().optional(),limit:z33.coerce.number().int().min(1).max(100).optional(),cursor:z33.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z33.object({recipient:NotificationRecipientStateSchema,unreadCount:z33.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z33.object({read:z33.boolean().optional(),archived:z33.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z34}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z34.object({id:z34.uuid(),occurredAt:z34.coerce.date(),projectId:z34.uuid().nullable(),env:z34.string().nullable(),actor:z34.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z34.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z34.unknown().optional(),ipAddress:z34.string().nullable().optional(),userAgent:z34.string().nullable().optional(),error:z34.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z34.object({rows:z34.array(AuditLogRowDTOSchema),nextCursor:z34.string().nullable()})),AuditLogQuerySchema=z34.object({env:z34.string().optional(),action:AuditActionSchema.optional(),actor:z34.string().optional(),from:z34.coerce.date().optional(),to:z34.coerce.date().optional(),limit:z34.coerce.number().int().min(1).max(200).optional(),cursor:z34.string().optional()})}});import{z as z35}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z35.object({surface:SurfaceNameSchema,key:z35.string(),label:z35.string()}),InlineSchema=z35.object({text:z35.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z35.discriminatedUnion("type",[z35.object({type:z35.literal("paragraph"),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("preview"),ref:DiffRefSchema,caption:z35.string().optional()}),z35.object({type:z35.literal("code"),code:z35.string(),lang:z35.string().optional(),caption:z35.string().optional()}),z35.object({type:z35.literal("risk"),level:z35.enum(["warning","error"]),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("list"),items:z35.array(z35.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z35.object({headline:z35.string(),blocks:z35.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z35.object({summary:EnvDiffSummarySchema,fingerprint:z35.string(),generatedAt:z35.coerce.date(),cached:z35.boolean().optional(),credits:z35.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z36}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z36.object({date:z36.string(),visitors:z36.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z36.object({key:z36.string(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z36.object({path:z36.string(),pageName:z36.string().nullable().optional(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z36.object({preset:z36.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z36.string(),requestedTo:z36.string(),effectiveFrom:z36.string(),effectiveTo:z36.string(),isRetentionLimited:z36.boolean(),groupBy:z36.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z36.object({date:z36.string(),content:z36.string(),updatedAt:z36.string(),updatedByUserId:z36.string()}),ProjectPageviewAnalyticsDTOSchema=z36.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative(),bounceRate:z36.number().min(0).max(100),viewsPerVisit:z36.number().nonnegative(),averageVisitDurationSeconds:z36.number().nonnegative(),visitorsSeries:z36.array(ProjectDailyVisitorsDTOSchema),topPages:z36.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z36.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z37}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z37.object({id:z37.string(),email:z37.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z37.coerce.date(),createdAt:z37.coerce.date(),inviterUserId:z37.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z37.object({id:z37.string(),token:z37.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z37.object({success:z37.boolean(),projectId:z37.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z38}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z38.object({id:z38.string(),name:z38.string(),image:z38.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z38.object({count:z38.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z38.object({counts:z38.object({signed_up:z38.int(),activated:z38.int()}),credits:z38.object({total:z38.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z38.email(),emailVerified:z38.boolean(),createdAt:z38.coerce.date(),updatedAt:z38.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z39}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z39.object({id:z39.string(),principalType:ProjectPrincipalTypeSchema,principalId:z39.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z39.coerce.date(),expiresAt:z39.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z39.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z39.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z39.record(z39.string(),z39.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z39.object({access:z39.array(ProjectAccessItemDTOSchema),invites:z39.array(ProjectInviteDTOSchema),organization:z39.object({name:z39.string().nullable(),logo:z39.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z39.object({success:z39.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z39.object({success:z39.boolean(),projectId:z39.uuid()}))}});import{z as z40}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z40.object({publicationStatus:PublicationStatusSchema,appUrl:z40.string().nullable(),lastPublishedAt:z40.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z41}from"zod";var PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewBridgePackageSchema=z41.object({name:z41.string().min(1),version:z41.string().min(1)}),PreviewBridgeCapabilitySchema=z41.object({integrated:z41.boolean(),packages:z41.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z41.object({url:z41.url(),expiresAt:z41.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z41.object({name:z41.string().min(1),locator:z41.string().min(1).optional(),source:z41.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z41.object({kind:z41.literal("dependency_build_scripts_blocked"),packageManager:z41.enum(["pnpm","yarn","bun"]),packages:z41.array(z41.string()),targets:z41.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z41.string(),approvalKey:z41.string(),command:z41.string().optional(),approval:z41.object({id:z41.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z41.object({code:z41.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z41.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z41.object({approvalId:z41.uuid()}),PreviewInstallPolicyApprovalEventSchema=z41.discriminatedUnion("type",[z41.object({type:z41.literal("progress"),step:z41.enum(["approval","install","restart","readiness"]),message:z41.string()}),z41.object({type:z41.literal("approved")}),z41.object({type:z41.literal("complete")}),z41.object({type:z41.literal("error"),code:z41.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z41.string()})])}});import{z as z42}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z42.string(),slug:z42.string().nullable(),logo:z42.string().nullable(),metadata:z42.record(z42.string(),z42.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),email:z42.email(),image:z42.string().nullable()}),OrganizationMemberDTOSchema=z42.object({id:z42.string(),userId:z42.string(),organizationId:z42.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z42.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z43}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z43.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z43.object({reason:CancellationReasonCodeSchema,details:z43.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z43.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z43.object({offerVersion:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),renewsOn:z43.string()}),PlanMigrationPreviewDTOSchema=z43.object({currency:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),startsAt:z43.string(),renewsAt:z43.string(),nextRenewalAmount:z43.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z43.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z43.object({id:z43.string(),organizationId:z43.string(),legacySubscriptionId:z43.string(),offeredPlanCode:z43.string(),offeredPlanName:z43.string(),offeredPriceAmount:z43.number(),offeredCurrency:z43.string(),offerVersion:z43.string(),state:PlanMigrationStateSchema,checkoutToken:z43.string().nullable(),deadlineAt:z43.string(),transitions:z43.array(z43.object({event:z43.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z43.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z43.object({included:z43.number().optional(),unitPrice:z43.number().optional(),dailyCap:z43.number().nullable().optional()}),EntitlementsDTOSchema=z43.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z43.object({retentionDays:z43.number().int().positive(),canUseExtendedDateRanges:z43.boolean()}).optional(),history:z43.object({retentionDays:z43.number().int().positive()}).optional(),members:z43.object({canInvite:z43.boolean(),maxMembers:z43.number().int().positive().nullable()}).optional(),domains:z43.object({canUseCustomDomains:z43.boolean(),maxDomains:z43.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z43.object({id:z43.string(),external_id:z43.string(),customerId:z43.string(),planId:z43.string(),planCode:z43.union([TemplateCodeSchema,z43.literal("Unknown")]),currentPeriod:z43.object({start:z43.string(),end:z43.string().nullable()}),cancelAt:z43.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z43.string(),nextPaymentAt:z43.string().nullable(),baseAmount:z43.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z43.object({totalCap:z43.number(),dailyCap:z43.number(),usedTotal:z43.number()}),CreditBalanceDTOSchema=z43.object({total:z43.number(),base:z43.number(),dailyBase:z43.number(),purchases:z43.number(),awards:z43.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z43.object({total:z43.number(),nearLimit:z43.boolean(),canChat:z43.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z43.object({dailyFreeAvailable:z43.number(),monthlyAvailable:z43.number(),purchasedAvailable:z43.number(),awardedAvailable:z43.number()}),ProjectDailyCreditAllowanceDTOSchema=z43.object({periodCap:z43.number(),dailyGrant:z43.number(),usedThisPeriod:z43.number(),remainingThisPeriod:z43.number()}),ProjectCreditBalanceDTOSchema=z43.object({projectId:z43.uuid(),organizationId:z43.string(),balance:z43.object({totalAvailable:z43.number(),nearLimit:z43.boolean(),canUseAi:z43.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z43.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z43.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z43.object({planCode:z43.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z43.object({source:z43.enum(["cached_subscription","free_fallback"]),settledMs:z43.number().int().nonnegative(),reservedMs:z43.number().int().nonnegative(),includedMs:z43.number().int().positive(),remainingMs:z43.number().int().nonnegative(),resetsAt:z43.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().nonnegative(),refillAmountUsd:z43.number().nonnegative()}),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().nonnegative().nullable(),refillAmountUsd:z43.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().min(.01).multipleOf(.01),refillAmountUsd:z43.number().min(.01).multipleOf(.01)}).strict(),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z43.object({invoiceId:z43.string(),newBalance:z43.int(),creditCount:z43.int(),amountUsd:z43.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z43.object({url:z43.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z44}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z44.object({brand:z44.string(),last4:z44.string(),exp:z44.string(),isDefault:z44.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z45}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z45.string().superRefine((path53,ctx)=>{let segments=path53.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z45.object({type:z45.literal("renameField"),contentType:z45.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z45.object({enabled:z45.boolean()}).strict(),ContentFieldGroupSchema=z45.object({id:z45.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z45.string().min(1).max(255),default:z45.boolean().optional()}).strict(),ContentTypeDTOSchema=z45.object({id:z45.string(),name:z45.string(),label:z45.string(),isSingleton:z45.boolean(),i18n:ContentTypeI18nSchema,groups:z45.array(ContentFieldGroupSchema).default([]),fields:z45.record(z45.string(),FieldDefinitionSchema),createdAt:z45.string(),updatedAt:z45.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z45.object({contentTypes:z45.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z45.object({id:z45.string(),entryId:z45.string(),documentId:z45.string(),slug:z45.string(),locale:z45.string().optional(),createdAt:z45.string(),updatedAt:z45.string(),__fimo:z45.object({contentType:z45.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({limit:z45.number(),offset:z45.number(),total:z45.number(),hasMore:z45.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z45.object({contentType:z45.string(),count:z45.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z45.object({counts:z45.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z45.object({count:z45.number().int().nonnegative(),sourceLocale:z45.string(),targetLocale:z45.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z45.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z45.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z45.union([z45.string(),z45.number(),z45.boolean(),z45.null()]),entryWhereOperatorSchema=z45.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z45.array(entryWhereScalarSchema).optional(),$nin:z45.array(entryWhereScalarSchema).optional(),$contains:z45.string().optional(),$startsWith:z45.string().optional(),$null:z45.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z45.object({data:z45.record(z45.string(),z45.unknown()),locale:z45.string().min(1).optional(),documentId:z45.uuid().optional()}),entryIdsSchema=z45.array(z45.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z45.object({sql:z45.string().min(1)}),BulkCreateEntriesRequestSchema=z45.object({entries:z45.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z45.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z45.object({updates:z45.array(z45.object({id:z45.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,locale:z45.string().min(1).optional()}),z45.object({where:EntryWhereSchema,locale:z45.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z45.object({data:z45.array(z45.record(z45.string(),z45.unknown())),meta:z45.object({rowCount:z45.number().int().nonnegative(),truncated:z45.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({created:z45.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({updated:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({deleted:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z46}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z46.object({index:z46.number().int().nonnegative(),contentType:z46.string(),field:z46.string(),value:z46.string(),against:z46.enum(["stored","batch"]),ownerDocumentId:z46.uuid().optional(),ownerIndex:z46.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z46.object({code:z46.literal("unique_conflict"),message:z46.string(),conflicts:z46.array(UniqueConflictSchema),truncated:z46.boolean().optional()})}});import{z as z47}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z47.object({kind:z47.literal("unique_conflict"),contentType:z47.string(),field:z47.string(),value:z47.string(),documentCount:z47.number().int().positive(),documentIds:z47.array(z47.uuid()),documentIdsTruncated:z47.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z47.object({code:z47.literal("schema_transition_rejected"),message:z47.string(),issues:z47.array(SchemaTransitionIssueSchema),truncated:z47.boolean().optional()})}});import{z as z48}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z48.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z48.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z48.object({field:CmsFieldNameSchema,direction:z48.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z48.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z48.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z48.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z48.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z48.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z49}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z49.object({id:z49.string(),name:z49.string()}),AssetDTOSchema=z49.object({id:z49.string(),name:z49.string(),type:AssetTypeSchema,originalFileName:z49.string().nullable(),parentId:z49.string().nullable(),mimeType:z49.string().nullable(),fileSize:z49.number().nullable(),url:z49.string().nullable(),storageKey:z49.string().nullable(),createdAt:z49.string(),updatedAt:z49.string(),altText:z49.string().nullable().optional(),caption:z49.string().nullable().optional(),aiCaption:z49.string().nullable().optional(),aiAltText:z49.string().nullable().optional(),aiTags:z49.array(z49.string()).nullable().optional(),aiPrimaryColor:z49.string().nullable().optional(),aiProcessingStatus:z49.string().nullable().optional(),width:z49.number().nullable().optional(),height:z49.number().nullable().optional(),path:z49.array(AssetPathItemSchema).optional(),hasChildren:z49.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z49.lazy(()=>z49.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z49.array(AssetDTOSchema))}});import{z as z50}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z50.object({key:z50.string(),value:z50.string().optional(),defaultValue:z50.string(),locale:z50.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z51}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z51.object({id:z51.string(),name:z51.string(),type:z51.enum(["file","folder"]),path:z51.string(),children:z51.lazy(()=>z51.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z51.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z51.object({path:z51.string(),exists:z51.boolean(),type:z51.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z52}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z52.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z52.object({items:z52.array(ProjectMessagePublicDTOSchema),nextCursor:z52.string().nullable()}),ChatLiveTurnDTOSchema=z52.object({invocationId:z52.string(),step:z52.enum(["preparing","working","compacting","merging"]),startedAt:z52.string()}),ChatLiveTurnStateDTOSchema=z52.object({threadId:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z52.object({id:z52.string(),role:z52.enum(["user","assistant"]),parts:z52.array(z52.unknown()),metadata:z52.record(z52.string(),z52.unknown()).nullable(),versionId:z52.string().nullable().optional(),createdAt:z52.date().transform(value=>value.toISOString()),providerMessageId:z52.string().nullable().optional(),invocationId:z52.string().nullable().optional(),invocationStatus:z52.string().nullable().optional(),invocationTerminalReason:z52.string().nullable().optional()}),ChatAttentionDTOSchema=z52.object({type:z52.literal("merge_conflict"),merge:z52.object({mergeId:z52.string().uuid(),projectId:z52.string(),fromEnv:z52.string(),toEnv:z52.string()}),publishAfterMerge:z52.boolean()}),ChatThreadMessagesPageDTOSchema=z52.object({threadId:z52.string().nullable(),title:z52.string().nullable(),messages:z52.array(ChatThreadMessageDTOSchema),nextCursor:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z52.object({kind:z52.literal("replay"),threadId:z52.string(),userMessageId:z52.string()}),ChatQueuedOutcomeDTOSchema=z52.object({kind:z52.literal("queued"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string()}),ChatBusyOutcomeDTOSchema=z52.object({kind:z52.literal("busy"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string().optional()}),ChatRefusedOutcomeDTOSchema=z52.object({kind:z52.literal("refused"),threadId:z52.string(),userMessageId:z52.string(),refusedInvocationId:z52.string(),terminalReason:z52.string()}),ChatNonStreamingOutcomeDTOSchema=z52.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z52.object({success:z52.boolean(),deletedCount:z52.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z52.object({code:z52.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z52.string()})}});import{z as z53}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z53.object({url:z53.string().url(),key:z53.string(),size:z53.number(),contentType:z53.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z54}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z54.object({canAccess:z54.boolean(),permissions:z54.record(z54.string(),z54.boolean()),role:z54.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z55}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z55.string().trim().default(""),sort:z55.enum(["recent","name","relevance"]).default("recent"),category:z55.string().optional()})}});import{z as z56}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z56.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z56.enum(["fimo","external"]),PaymentStatusSchema=z56.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z56.object({id:z56.string().uuid(),domain:z56.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z56.boolean(),price:z56.number().int().nullable(),renewalPrice:z56.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z56.string().nullable(),failureReason:z56.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z56.object({domain:z56.string(),available:z56.boolean(),premium:z56.boolean(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),purchaseType:z56.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z56.object({domain:z56.string(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),premium:z56.boolean(),allowedYears:z56.array(z56.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z56.object({firstName:z56.string().max(100),lastName:z56.string().max(100),companyName:z56.string().max(100).optional(),address1:z56.string().max(255),address2:z56.string().max(255).optional(),city:z56.string().max(100),state:z56.string().max(100),zip:z56.string().max(20),country:z56.string().max(2),phone:z56.string().max(30),email:z56.union([z56.string().email().max(255),z56.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z56.object({firstName:z56.string().min(1).max(100),lastName:z56.string().min(1).max(100),companyName:z56.string().max(100).optional(),address1:z56.string().min(1).max(255),address2:z56.string().max(255).optional(),city:z56.string().min(1).max(100),state:z56.string().min(1).max(100),zip:z56.string().min(1).max(20),country:z56.string().min(1).max(2),phone:z56.string().min(1).max(30),email:z56.string().email().max(255)}),SearchDomainsRequestSchema=z56.object({keyword:z56.string().min(1).max(100),tldFilter:z56.array(z56.string()).optional()}),CheckAvailabilityRequestSchema=z56.object({domains:z56.array(z56.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z56.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z56.object({domain:DomainNameSchema,years:z56.number().int().min(1).max(10).optional().default(3),autoRenew:z56.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z56.object({autoRenew:z56.boolean().optional()}),RenewDomainRequestSchema=z56.object({years:z56.number().int().min(1).max(10).optional().default(1),autoRenew:z56.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z56.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z56.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z56.object({verified:z56.boolean(),email:z56.string().nullable(),verifyBy:z56.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z57}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z57.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z57.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z57.object({txtName:z57.string().nullable().optional(),txtValue:z57.string().nullable().optional(),httpUrl:z57.string().nullable().optional(),httpBody:z57.string().nullable().optional(),cname:z57.string().nullable().optional(),cnameTarget:z57.string().nullable().optional()}),SSLValidationErrorSchema=z57.object({message:z57.string()}),OwnershipVerificationSchema=z57.object({type:z57.string(),name:z57.string(),value:z57.string()}),ProjectDomainSSLDTOSchema=z57.object({status:z57.string(),method:z57.string().nullable(),type:z57.string().nullable(),validationRecords:z57.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z57.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z57.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z57.enum(["subdomain","apex"]),RedirectConfigSchema=z57.object({type:z57.literal("apex_to_www"),linkedDomainId:z57.string()}).nullable().optional(),ProjectDomainDTOSchema=z57.object({id:z57.string(),hostname:z57.string(),status:z57.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z57.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z57.string(),scdCnameTarget:z57.string().optional(),apexTargets:z57.array(z57.string()),dnsAutoConfigured:z57.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z57.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z57.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z57.object({hostname:z57.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z57.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z57.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z57.object({success:z57.boolean(),hostname:z57.string()}))}});import{z as z58}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z58.object({slug:z58.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z58.object({subdomain:z58.string(),subdomainUpdatedAt:z58.coerce.date()})),SubdomainSuggestionsQuerySchema=z58.object({base:z58.string().max(100).optional(),max:z58.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z58.object({suggestions:z58.array(z58.string())}))}});import{z as z59}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z59.object({translated:z59.number().int().nonnegative(),total:z59.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z59.object({locale:z59.string(),isDefault:z59.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z59.object({defaultLocale:z59.string(),locales:z59.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z59.object({locale:z59.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z59.object({locale:z59.string().min(1).max(40)}),ProjectLocaleMutationSchema=z59.object({locale:z59.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z59.object({locale:z59.string(),entriesDeleted:z59.number().int().nonnegative(),labelsDeleted:z59.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z60}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z60.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z60.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z60.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z60.number(),credits:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),confidence:z60.enum(["exact","estimated","metered"]),basis:z60.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z61}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z61.object({options:z61.record(z61.string(),z61.unknown()),name:z61.string().optional(),parentId:z61.string().nullable().optional(),altText:z61.string().optional(),caption:z61.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z61.string().min(1).optional(),model:z61.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z61.object({jobId:z61.string(),status:z61.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z61.string().nullable().optional(),credits:z61.number().optional(),costUsd:z61.number().optional(),billingMode:z61.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z61.object({error:z61.string(),code:z61.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z61.array(GenerationTaskIdSchema).optional(),availableModels:z61.array(z61.string()).optional(),issues:z61.array(z61.unknown()).optional()})}});import{z as z62}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z62.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z62.object({name:z62.string(),key:z62.string(),description:z62.string(),type:FlagTypeSchema,required:z62.boolean(),defaultValue:z62.unknown().optional(),enumValues:z62.array(z62.string()).optional(),isArray:z62.boolean()}),AssetModelPriceSchema=z62.object({unitPrice:z62.number(),unit:z62.string(),confidence:z62.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z62.object({id:z62.string(),shortName:z62.string(),provider:z62.string(),source:z62.string(),modality:z62.enum(["image","video","audio"]),tags:z62.array(z62.string()),displayName:z62.string(),description:z62.string(),flags:z62.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z62.object({model:z62.string(),costUsd:z62.number(),credits:z62.number(),billingMode:z62.enum(["fimo-credits","provider-account"]),confidence:z62.enum(["exact","estimated","metered"]),basis:z62.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z63}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z63.object({tourId:z63.string(),version:z63.string(),status:z63.string(),completedAt:z63.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z63.array(UserTourDTOSchema))}});import{z as z64}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z64.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z64.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z64.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z64.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z64.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z64.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z64.enum(["user","agent","system"]),SupportReportTagSchema=z64.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z64.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z64.object({organization:z64.object({id:z64.string().trim().min(1).max(255),name:z64.string().trim().max(240).optional()}),project:z64.object({id:z64.uuid(),name:z64.string().trim().max(240).optional(),createdAt:z64.coerce.date().optional()}).optional(),environment:z64.string().trim().max(255).optional(),clientVersion:z64.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z64.string().trim().max(200).optional(),limit:z64.coerce.number().int().min(1).max(100).default(50),offset:z64.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z64.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z64.uuid().nullable().optional(),note:z64.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z64.object({kind:SupportReportLinkKindSchema,label:z64.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z64.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z64.object({kind:SupportReportActorKindSchema,id:z64.string().nullable(),name:z64.string().nullable()}),SupportReportLinkDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportLinkKindSchema,label:z64.string(),url:SupportReportHttpUrlSchema,externalId:z64.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportEventKindSchema,body:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()),actor:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z64.object({id:z64.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z64.array(z64.string()),source:SupportReportSourceSchema,message:z64.string(),reporter:z64.object({id:z64.string().nullable(),name:z64.string().nullable(),email:z64.string().nullable()}),organization:z64.object({id:z64.string().nullable(),name:z64.string()}),project:z64.object({id:z64.uuid().nullable(),name:z64.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z64.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z64.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z64.string().nullable(),deliveredAt:z64.coerce.date().nullable()}).nullable(),duplicateOfReportId:z64.uuid().nullable(),resolvedAt:z64.coerce.date().nullable(),createdAt:z64.coerce.date(),updatedAt:z64.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z64.string().nullable(),clientVersion:z64.string().nullable(),links:z64.array(SupportReportLinkDTOSchema),events:z64.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z64.object({reports:z64.array(SupportReportSummaryDTOSchema),total:z64.number().int().nonnegative(),statusCounts:z64.object({new:z64.number().int().nonnegative(),in_progress:z64.number().int().nonnegative(),waiting:z64.number().int().nonnegative(),resolved:z64.number().int().nonnegative(),duplicate:z64.number().int().nonnegative(),irrelevant:z64.number().int().nonnegative(),ignored:z64.number().int().nonnegative()}),limit:z64.number().int().positive(),offset:z64.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z64.object({id:z64.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z64.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z65}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z65.iso.datetime({offset:!0}).pipe(z65.coerce.date()),OpsRecentChatInputSchema=z65.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z65.string().trim().min(1).max(255).optional(),limit:z65.coerce.number().int().min(1).max(200).default(100),cursor:z65.string().trim().min(1).max(2e3).optional(),slim:z65.boolean().default(!0),reason:z65.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z65.object({id:z65.string(),threadId:z65.string(),providerMessageId:z65.string().nullable(),invocationId:z65.string().nullable(),env:z65.string().nullable(),role:z65.string(),parts:z65.array(z65.record(z65.string(),z65.unknown())),metadata:z65.object({status:z65.string().optional(),traceUrl:z65.string().optional(),externalFileChanges:z65.array(z65.unknown()).optional()}),stats:z65.object({toolCount:z65.number().int().nonnegative(),failedToolCount:z65.number().int().nonnegative()}),createdAt:z65.iso.datetime({offset:!0}),project:z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),organizationId:z65.string().nullable()})}),OpsRecentChatResponseSchema=z65.object({target:z65.object({backendProfile:OpsBackendProfileSchema,projectEnv:z65.string().nullable()}),window:z65.object({from:z65.iso.datetime({offset:!0}),to:z65.iso.datetime({offset:!0})}),messages:z65.object({items:z65.array(OpsRecentChatMessageSchema),nextCursor:z65.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z66}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z66.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z66.literal(!1),reason:z66.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z67}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z67.object({packageManager:z67.string().trim().min(1).max(200).nullable(),trackedLockfiles:z67.array(z67.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z67.string().trim().min(1)}),OpsProjectPackageManagerSchema=z67.object({target:z67.object({backendProfile:OpsBackendProfileSchema,projectId:z67.uuid(),projectEnv:z67.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z68}from"zod";function createAgentRunWebhookEventDataSchema(status){return z68.object({run:z68.object({id:z68.string(),agentName:z68.string(),trigger:z68.string(),status:z68.literal(status),startedAt:z68.string().nullable(),finishedAt:z68.string().nullable(),reason:z68.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z68.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z68.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z68.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z68.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z68.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z68.union([z68.literal(0),z68.literal(5),z68.literal(30),z68.literal(60)]),EntryChangedWebhookEventDataSchema=z68.object({reason:WebhookEntryChangeReasonSchema,operationId:z68.string().optional(),batch:z68.object({index:z68.number().int().positive(),total:z68.number().int().positive()}).optional(),changes:z68.array(z68.object({action:WebhookEntryChangeActionSchema,contentType:z68.string(),id:z68.string(),documentId:z68.string(),locale:z68.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z68.object({form:z68.object({id:z68.string(),label:z68.string()}),submission:z68.object({id:z68.string(),data:z68.record(z68.string(),z68.unknown()),submittedAt:z68.string()})}),PublishStartedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("publishing"),startedAt:z68.string()})}),PublishSucceededWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("published"),url:z68.string(),publishedAt:z68.string(),firstPublish:z68.boolean()})}),PublishFailedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("failed"),reason:z68.string()})}),PublishUnpublishedWebhookEventDataSchema=z68.object({publication:z68.object({previousUrl:z68.string(),unpublishedAt:z68.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),classification:z68.string(),summary:z68.string(),reasons:z68.array(z68.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),resolution:z68.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z68.object({report:z68.object({weekStart:z68.string(),weekEnd:z68.string(),pageviews:z68.number(),visitors:z68.number(),previousPageviews:z68.number(),previousVisitors:z68.number()})}),MediaAssetWebhookEventDataSchema=z68.object({id:z68.string().nullable(),name:z68.string().nullable(),type:z68.string(),mimeType:z68.string().nullable(),fileSize:z68.number().nullable()}),MediaUploadedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["updated","moved","analysis"]),analysis:z68.object({category:z68.string(),status:z68.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("generated"),generation:z68.object({model:z68.string(),mode:z68.string()})}),MediaProcessingFailedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["analysis","generation"]),failure:z68.object({code:z68.string()})}),DomainCreatedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string()})}),LabelChangedWebhookEventDataSchema=z68.object({changes:z68.array(z68.object({action:z68.enum(["created","updated","deleted"]),key:z68.string(),locale:z68.string(),value:z68.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),isDefault:z68.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),previousCode:z68.string()})}),LocaleDeletedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),entriesDeleted:z68.number().int().nonnegative(),labelsDeleted:z68.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z68.object({merge:z68.object({id:z68.string(),from:BranchSchema,to:BranchSchema,applied:z68.array(z68.object({surface:SurfaceNameSchema,count:z68.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema}),version:z68.object({versionId:z68.uuid(),name:z68.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z68.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z68.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z68.discriminatedUnion("source",[z68.object({source:z68.literal("literal"),value:z68.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z68.object({source:z68.literal("secret"),key:z68.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z68.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z68.object({name:z68.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z68.object({name:z68.string(),source:z68.enum(["literal","secret"]),secretKey:z68.string().nullable(),secretPrefix:z68.string().nullable(),configured:z68.literal(!0)}),WebhookFilterSchema=z68.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z68.string().min(1).max(255).optional(),agentName:z68.string().min(1).max(120).optional(),mediaType:z68.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z68.string().min(1).max(255).optional(),locale:z68.string().min(1).max(120).optional()}),JsonValueSchema=z68.lazy(()=>z68.union([z68.string(),z68.number(),z68.boolean(),z68.null(),z68.array(JsonValueSchema),z68.record(z68.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z68.url(),enabled:z68.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z68.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z68.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z68.url().optional(),enabled:z68.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z68.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z68.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z68.object({eventType:WebhookEventTypeSchema.optional(),data:z68.record(z68.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z68.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z68.uuid(),name:z68.string(),eventType:WebhookEventTypeSchema,enabled:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z68.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z68.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z68.coerce.date().nullable(),deliveryStats24h:z68.object({succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z68.uuid(),projectId:z68.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z68.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z68.number().int().positive(),test:z68.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z68.number().int().nonnegative(),responseStatus:z68.number().int().nullable(),lastErrorCode:z68.string().nullable(),lastErrorMessage:z68.string().nullable(),payloadAvailable:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z68.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z68.string().nullable(),qstashMessageId:z68.string().nullable(),deliveredAt:z68.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z68.object({items:z68.array(WebhookDeliveryDTOSchema),pagination:z68.object({page:z68.number().int().positive(),limit:z68.number().int().positive(),total:z68.number().int().nonnegative(),totalPages:z68.number().int().positive(),hasMore:z68.boolean()}),stats:z68.object({total:z68.number().int().nonnegative(),succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z68.object({id:z68.uuid(),deliveryId:z68.uuid(),attempt:z68.number().int().positive(),status:z68.enum(["delivering","succeeded","failed"]),responseStatus:z68.number().int().nullable(),durationMs:z68.number().int().nonnegative(),responseExcerpt:z68.string().nullable(),errorCode:z68.string().nullable(),errorMessage:z68.string().nullable(),createdAt:z68.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z68.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z68.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z69}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z69.object({key:z69.literal("fimo-2"),enabled:z69.boolean(),dismissed:z69.boolean().default(!1),interacted:z69.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z70}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z70.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z70.object({total:z70.number(),base:z70.number(),purchases:z70.number(),awards:z70.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z70.object({id:z70.string(),name:z70.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z70.object({type:z70.string(),brand:z70.string().nullable(),last4:z70.string().nullable(),expirationDate:z70.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z70.object({currency:z70.string(),nextPaymentAmount:z70.number().nullable(),nextPaymentAt:z70.string().nullable(),billingInterval:z70.string().nullable(),totalAmount:z70.number().nullable(),discountAmount:z70.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z70.object({id:z70.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z70.string().nullable(),currentPeriodEndsAt:z70.string().nullable(),renewsAt:z70.string().nullable(),cancelAt:z70.string().nullable(),renewAutomatically:z70.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z70.object({type:z70.enum(["low_balance","critical_balance","approaching_limit"]),message:z70.string(),estimatedPromptsRemaining:z70.number().nullable(),avgCostPerPrompt:z70.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z70.object({monthlyCredits:z70.number().nullable(),usedThisPeriod:z70.number(),remainingThisPeriod:z70.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z70.object({organizationId:z70.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z70.string().nullable(),tenureDays:z70.number().int().nonnegative(),capturedAt:z70.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z70.object({hasSubscription:z70.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z70.number().nullable(),alerts:z70.array(CreditAlertDTOSchema),portalUrl:z70.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z70.object({creditCount:z70.number().int().positive(),expiresAt:z70.string().datetime().nullable().optional(),message:z70.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("free"),amountCents:z70.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("purchase"),amountCents:z70.number().int().positive()}),CreditTopupRequestDTOSchema=z70.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z70.object({success:z70.boolean(),transactionId:z70.string().nullable(),newBalance:z70.number(),creditCount:z70.number(),type:z70.enum(["free","purchase"]),invoiceId:z70.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z71}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),periodStart:z71.string().nullable(),periodEnd:z71.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z71.array(UsageByUserForProjectDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z71.object({summary:UsageSummaryDTOSchema,byProject:z71.array(UsageByProjectDTOSchema),byUser:z71.array(UsageByUserDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z72}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z72.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z72.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z72.object({startDate:z72.string().optional(),endDate:z72.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z72.coerce.number().int().positive().default(1),limit:z72.coerce.number().int().positive().max(100).default(20),sortBy:z72.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z72.string().optional(),activeOnly:z72.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z72.object({totalCredits:z72.number(),totalCostUsd:z72.number(),totalMessages:z72.number(),avgCostPerMessage:z72.number(),avgCreditsPerMessage:z72.number(),periodStart:z72.string(),periodEnd:z72.string(),creditsChange:z72.number().nullable(),costChange:z72.number().nullable(),messagesChange:z72.number().nullable(),unattributedCredits:z72.number(),unattributedCostUsd:z72.number(),unattributedMessages:z72.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z72.object({date:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z72.object({organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number(),projectCount:z72.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z72.object({userId:z72.string(),userName:z72.string().nullable(),userEmail:z72.string().nullable(),userImage:z72.string().nullable(),organizationId:z72.string().nullable(),organizationName:z72.string().nullable(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),projectCount:z72.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z72.object({projectId:z72.string(),projectName:z72.string(),projectDisplayName:z72.string().nullable(),organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z72.object({id:z72.string(),name:z72.string(),value:z72.number(),percentage:z72.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z72.object({day:z72.number(),hour:z72.number(),value:z72.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z72.object({summary:UsageOverviewSummaryDTOSchema,timeline:z72.array(UsageTimelinePointDTOSchema),topOrganizations:z72.array(OrganizationUsageRowDTOSchema),topUsers:z72.array(UserUsageRowDTOSchema),topProjects:z72.array(ProjectUsageRowDTOSchema),creditDistribution:z72.array(UsageDistributionItemDTOSchema),userDistribution:z72.array(UsageDistributionItemDTOSchema),heatmap:z72.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z72.object({page:z72.number(),limit:z72.number(),totalItems:z72.number(),totalPages:z72.number(),hasMore:z72.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z72.object({organizations:z72.array(OrganizationUsageRowDTOSchema),top:z72.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z72.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z72.object({users:z72.array(ExtendedUserUsageRowDTOSchema),top:z72.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z72.object({projects:z72.array(ExtendedProjectUsageRowDTOSchema),top:z72.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z72.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z72.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z72.object({credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),createdAt:z72.string(),memberCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z72.object({id:z72.string(),name:z72.string().nullable(),email:z72.string(),image:z72.string().nullable(),createdAt:z72.string(),organizationCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),displayName:z72.string().nullable(),createdAt:z72.string(),organizationId:z72.string(),organizationName:z72.string(),ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z73}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z73.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z73.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z73.object({command:z73.string().min(1).max(1e4),cwd:z73.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z73.record(z73.string(),z73.string()).optional(),name:z73.string().optional(),waitForCompletion:z73.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=z73.object({identifier:z73.string(),status:SandboxProcessStatusSchema,command:z73.string().optional(),startedAt:z73.string().optional(),exitCode:z73.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z73.object({processes:z73.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z73.object({processId:z73.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z73.object({success:z73.boolean(),message:z73.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z74}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}branch;withBranch(branch){let next2=new _FimoApiClient(this.cfg);return next2.branch=branch,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path53,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch),fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers})}async rawRequest(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path53} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: tenant-scoped call requires a Branch. Use `client.withBranch(branch)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}projectBranchManagementPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: Branch-scoped management call requires a Branch. Use `client.withBranch(branch)` before calling Branch CRUD methods.");return`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectBranchManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listBranches(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentBranches&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/branches${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listBranches(projectId,{includeAgentBranches:!0}),current=branches.find(candidate=>branchNameOf(candidate)===branch),visited=new Set;for(;current&&!visited.has(branchNameOf(current));){if(visited.add(branchNameOf(current)),current.resolvedEnvironment)return current.resolvedEnvironment.id;let parent2=parentBranchOf(current);current=parent2?branches.find(candidate=>branchNameOf(candidate)===parent2):void 0}return PREVIEW_ENVIRONMENT_KEY}async getBranch(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`)).data}async createBranch(projectId,input){return(await this.request(`/api/management/projects/${projectId}/branches`,{method:"POST",body:JSON.stringify(input)})).data}async syncBranch(projectId,branch,input={}){let body=await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sync`,{method:"POST",body:JSON.stringify(input)});return{branch:body.data.branch??body.data.env,conflicts:body.data.conflicts}}async deleteBranch(projectId,branch){await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`,{method:"DELETE"})}async getBranchDiff(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,branch,path53,opts={}){let qs=lazyFetchQs(opts.against,{path:path53});return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,branch,fromBranch,filePath){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,branch,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getSchemaTypeDiff(projectId,branch,typeName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getAssetDiff(projectId,branch,assetId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getTranslationRowDiff(projectId,branch,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getFormSchemaDiff(projectId,branch,formName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async mergeBranch(projectId,branch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,branch,mergeId){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflicts`)).data}async putResolveDraft(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,branch,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.branch&¶ms.set("env",opts.branch),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,branch){let remote=(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,branch);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectBranchManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox`)).data}async getSandboxLogs(projectId,branch,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
61
61
|
|
|
62
62
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
63
63
|
|