fimo 2.3.0 → 2.3.1-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -205,7 +205,7 @@ ${block.code}
205
205
 
206
206
  `)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&&sections.push(...document.details.map(reportBlockMarkdown)),sections.join(`
207
207
 
208
- `)}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,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.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=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index2)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index2,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.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.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.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=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}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=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.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:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.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")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,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_common2();init_env();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.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}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_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.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=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}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=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}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=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}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=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.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:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}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=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}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=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema)}});import{z as z57}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=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}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=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,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=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),longRunning:z59.boolean(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}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=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index2)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index2],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}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=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.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=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}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=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z62.object({value:z62.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.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=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.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=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.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=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.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=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().optional(),reservedCredits:z62.number().optional(),actualCredits:z62.number().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.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=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}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_common2();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=z64.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=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,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=z65.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),ListNotificationsQuerySchema=z65.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.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=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}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=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}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=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}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_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}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_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.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=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}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=z73.object({name:z73.string().min(1),version:z73.string().min(1)}),PreviewBridgeCapabilitySchema=z73.object({integrated:z73.boolean(),packages:z73.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z73.object({url:z73.url(),expiresAt:z73.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z73.object({name:z73.string().min(1),locator:z73.string().min(1).optional(),source:z73.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z73.object({kind:z73.literal("dependency_build_scripts_blocked"),packageManager:z73.enum(["pnpm","yarn","bun"]),packages:z73.array(z73.string()),targets:z73.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z73.string(),approvalKey:z73.string(),command:z73.string().optional(),approval:z73.object({id:z73.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z73.object({code:z73.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z73.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z73.object({approvalId:z73.uuid()}),PreviewInstallPolicyApprovalEventSchema=z73.discriminatedUnion("type",[z73.object({type:z73.literal("progress"),step:z73.enum(["approval","install","restart","readiness"]),message:z73.string()}),z73.object({type:z73.literal("approved")}),z73.object({type:z73.literal("complete")}),z73.object({type:z73.literal("error"),code:z73.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z73.string()})])}});import{z as z74}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z74.string(),slug:z74.string().nullable(),logo:z74.string().nullable(),metadata:z74.record(z74.string(),z74.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z74.object({id:z74.string(),name:z74.string(),email:z74.email(),image:z74.string().nullable()}),OrganizationMemberDTOSchema=z74.object({id:z74.string(),userId:z74.string(),organizationId:z74.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z74.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z75}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,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_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z75.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z75.object({reason:CancellationReasonCodeSchema,details:z75.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z75.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z75.object({offerVersion:z75.string().trim().min(1),unusedPremiumCreditAmount:z75.number().int().nonnegative(),amountDueNow:z75.number().int().nonnegative(),renewsOn:z75.string()}),PlanMigrationPreviewDTOSchema=z75.object({currency:z75.string().trim().min(1),unusedPremiumCreditAmount:z75.number().int().nonnegative(),amountDueNow:z75.number().int().nonnegative(),startsAt:z75.string(),renewsAt:z75.string(),nextRenewalAmount:z75.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z75.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z75.object({id:z75.string(),organizationId:z75.string(),legacySubscriptionId:z75.string(),offeredPlanCode:z75.string(),offeredPlanName:z75.string(),offeredPriceAmount:z75.number(),offeredCurrency:z75.string(),offerVersion:z75.string(),state:PlanMigrationStateSchema,checkoutToken:z75.string().nullable(),deadlineAt:z75.string(),transitions:z75.array(z75.object({event:z75.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z75.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z75.object({included:z75.number().optional(),unitPrice:z75.number().optional(),dailyCap:z75.number().nullable().optional()}),EntitlementsDTOSchema=z75.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z75.object({retentionDays:z75.number().int().positive(),canUseExtendedDateRanges:z75.boolean()}).optional(),history:z75.object({retentionDays:z75.number().int().positive()}).optional(),members:z75.object({canInvite:z75.boolean(),maxMembers:z75.number().int().positive().nullable()}).optional(),projects:z75.object({maxProjects:z75.number().int().positive().nullable()}).optional(),domains:z75.object({canUseCustomDomains:z75.boolean(),maxDomains:z75.number().int().nonnegative().nullable()}).optional(),media_storage:z75.object({limitBytes:z75.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z75.object({usedBytes:z75.number().int().nonnegative().nullable(),limitBytes:z75.number().int().nonnegative().nullable(),state:z75.enum(["ready","unavailable"]),measuredAt:z75.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z75.object({toPlanCode:TemplateCodeSchema,effectiveAt:z75.string(),scheduledAt:z75.string().nullable()}),HostingOverageStatusDTOSchema=z75.object({state:z75.enum(["ready","unavailable"]),planCode:z75.string(),overageAvailable:z75.boolean(),overageEnabled:z75.boolean(),monthlyCapUsd:z75.number().int().positive().nullable(),periodStart:z75.iso.datetime().nullable(),periodEnd:z75.iso.datetime().nullable(),usedBytes:z75.number().nonnegative().nullable(),includedBytes:z75.number().nonnegative().nullable(),overageBytes:z75.number().nonnegative(),currentOverageAmountMicros:z75.number().nonnegative().nullable(),currency:z75.string().nullable(),status:z75.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z75.object({enabled:z75.boolean(),monthlyCapUsd:z75.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling overages requires a monthly cap"}),SubscriptionDTOSchema=z75.object({id:z75.string(),external_id:z75.string(),customerId:z75.string(),planId:z75.string(),planCode:z75.union([TemplateCodeSchema,z75.literal("Unknown")]),currentPeriod:z75.object({start:z75.string(),end:z75.string().nullable()}),cancelAt:z75.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z75.string(),nextPaymentAt:z75.string().nullable(),baseAmount:z75.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z75.object({totalCap:z75.number(),dailyCap:z75.number(),usedTotal:z75.number()}),CreditBalanceDTOSchema=z75.object({total:z75.number(),base:z75.number(),dailyBase:z75.number(),purchases:z75.number(),awards:z75.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z75.object({total:z75.number(),nearLimit:z75.boolean(),canChat:z75.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z75.object({dailyFreeAvailable:z75.number(),monthlyAvailable:z75.number(),purchasedAvailable:z75.number(),awardedAvailable:z75.number()}),ProjectDailyCreditAllowanceDTOSchema=z75.object({periodCap:z75.number(),dailyGrant:z75.number(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),ProjectCreditBalanceDTOSchema=z75.object({projectId:z75.uuid(),organizationId:z75.string(),balance:z75.object({totalAvailable:z75.number(),nearLimit:z75.boolean(),canUseAi:z75.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z75.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z75.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z75.object({planCode:z75.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z75.object({source:z75.enum(["cached_subscription","free_fallback"]),settledMs:z75.number().int().nonnegative(),activeMs:z75.number().int().nonnegative(),reservedMs:z75.number().int().nonnegative().optional(),includedMs:z75.number().int().positive(),remainingMs:z75.number().int().nonnegative(),resetsAt:z75.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z75.discriminatedUnion("enabled",[z75.object({enabled:z75.literal(!0),thresholdUsd:z75.number().nonnegative(),refillAmountUsd:z75.number().nonnegative()}),z75.object({enabled:z75.literal(!1),thresholdUsd:z75.number().nonnegative().nullable(),refillAmountUsd:z75.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z75.discriminatedUnion("enabled",[z75.object({enabled:z75.literal(!0),thresholdUsd:z75.number().min(.01).multipleOf(.01),refillAmountUsd:z75.number().min(.01).multipleOf(.01)}).strict(),z75.object({enabled:z75.literal(!1),thresholdUsd:z75.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z75.object({invoiceId:z75.string(),newBalance:z75.int(),creditCount:z75.int(),amountUsd:z75.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z75.object({url:z75.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema2(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema2(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema2(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema2(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema2(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema2(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema2(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema2(PortalDTOSchema)}});import{z as z76}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=z76.object({brand:z76.string(),last4:z76.string(),exp:z76.string(),isDefault:z76.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z77}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z77.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=z77.object({type:z77.literal("renameField"),contentType:z77.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z77.object({enabled:z77.boolean()}).strict(),ContentFieldGroupSchema=z77.object({id:z77.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z77.string().min(1).max(255),default:z77.boolean().optional()}).strict(),ContentTypeDTOSchema=z77.object({id:z77.string(),name:z77.string(),label:z77.string(),isSingleton:z77.boolean(),i18n:ContentTypeI18nSchema,groups:z77.array(ContentFieldGroupSchema).default([]),fields:z77.record(z77.string(),FieldDefinitionSchema),createdAt:z77.string(),updatedAt:z77.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z77.object({contentTypes:z77.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z77.object({id:z77.string(),entryId:z77.string(),documentId:z77.string(),slug:z77.string(),locale:z77.string().optional(),createdAt:z77.string(),updatedAt:z77.string(),__fimo:z77.object({contentType:z77.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({limit:z77.number(),offset:z77.number(),total:z77.number(),hasMore:z77.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z77.object({contentType:z77.string(),count:z77.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z77.object({counts:z77.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z77.object({count:z77.number().int().nonnegative(),sourceLocale:z77.string(),targetLocale:z77.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z77.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z77.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z77.union([z77.string(),z77.number(),z77.boolean(),z77.null()]),entryWhereOperatorSchema2=z77.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z77.array(entryWhereScalarSchema2).optional(),$nin:z77.array(entryWhereScalarSchema2).optional(),$contains:z77.string().optional(),$startsWith:z77.string().optional(),$null:z77.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z77.record(z77.string(),z77.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z77.record(z77.string(),z77.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z77.object({data:z77.record(z77.string(),z77.unknown()),locale:z77.string().min(1).optional(),documentId:z77.uuid().optional()}),entryIdsSchema=z77.array(z77.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z77.object({sql:z77.string().min(1)}),BulkCreateEntriesRequestSchema=z77.object({entries:z77.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z77.union([z77.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z77.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z77.object({updates:z77.array(z77.object({id:z77.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z77.union([z77.object({ids:entryIdsSchema,locale:z77.string().min(1).optional()}),z77.object({where:EntryWhereSchema2,locale:z77.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z77.object({data:z77.array(z77.record(z77.string(),z77.unknown())),meta:z77.object({rowCount:z77.number().int().nonnegative(),truncated:z77.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({created:z77.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({updated:z77.number().int().nonnegative(),missing:z77.array(z77.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({deleted:z77.number().int().nonnegative(),missing:z77.array(z77.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z78}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z78.object({index:z78.number().int().nonnegative(),contentType:z78.string(),field:z78.string(),value:z78.string(),against:z78.enum(["stored","batch"]),ownerDocumentId:z78.uuid().optional(),ownerIndex:z78.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z78.object({code:z78.literal("unique_conflict"),message:z78.string(),conflicts:z78.array(UniqueConflictSchema),truncated:z78.boolean().optional()})}});import{z as z79}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=z79.object({kind:z79.literal("unique_conflict"),contentType:z79.string(),field:z79.string(),value:z79.string(),documentCount:z79.number().int().positive(),documentIds:z79.array(z79.uuid()),documentIdsTruncated:z79.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z79.object({code:z79.literal("schema_transition_rejected"),message:z79.string(),issues:z79.array(SchemaTransitionIssueSchema),truncated:z79.boolean().optional()})}});import{z as z80}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_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z80.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z80.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z80.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z80.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z80.object({field:CmsFieldNameSchema,direction:z80.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z80.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z80.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z80.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z80.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z80.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z81}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z81.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z82}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z82.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z82.object({event:ClientTrackedEventSchema,properties:z82.record(z82.string(),z82.unknown()).default({})})}});import{z as z83}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z83.object({id:z83.string(),name:z83.string()}),AssetDTOSchema2=z83.object({id:z83.string(),name:z83.string(),type:AssetTypeSchema,originalFileName:z83.string().nullable(),parentId:z83.string().nullable(),mimeType:z83.string().nullable(),fileSize:z83.number().nullable(),url:z83.string().nullable(),storageKey:z83.string().nullable(),createdAt:z83.string(),updatedAt:z83.string(),altText:z83.string().nullable().optional(),caption:z83.string().nullable().optional(),aiCaption:z83.string().nullable().optional(),aiAltText:z83.string().nullable().optional(),aiTags:z83.array(z83.string()).nullable().optional(),aiPrimaryColor:z83.string().nullable().optional(),aiProcessingStatus:z83.string().nullable().optional(),width:z83.number().nullable().optional(),height:z83.number().nullable().optional(),path:z83.array(AssetPathItemSchema).optional(),hasChildren:z83.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z83.lazy(()=>z83.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z83.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z83.object({error:z83.string(),code:z83.literal("media_storage_limit_exceeded"),usedBytes:z83.number().int().nonnegative(),limitBytes:z83.number().int().positive(),incomingBytes:z83.number().int().nonnegative()}),AssetReferenceScopeSchema=z83.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z83.object({assetIds:z83.array(z83.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z83.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z83.object({totalFiles:z83.number().int().nonnegative(),checkedFiles:z83.number().int().nonnegative(),limit:z83.number().int().positive()}),AssetReferenceFindingDTOSchema=z83.object({assetId:z83.uuid(),entryId:z83.string(),documentId:z83.string(),contentType:z83.string(),locale:z83.string().nullable(),slug:z83.string(),fieldPath:z83.string()}),AssetReferenceScopeResultDTOSchema=z83.object({scope:AssetReferenceScopeSchema,label:z83.string(),state:z83.enum(["available","not-published","failed"]),coverage:z83.enum(["complete","partial","failed"]),referenceCount:z83.number().int().nonnegative().optional(),codeReferenceCount:z83.number().int().nonnegative().optional(),referencedAssetIds:z83.array(z83.uuid()).optional(),references:z83.array(AssetReferenceFindingDTOSchema),reason:z83.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z83.discriminatedUnion("type",[z83.object({type:z83.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z83.object({type:z83.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z83.object({type:z83.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z83.object({replacementAssetId:z83.uuid()}),AssetReferenceReplacementResultSchema=z83.object({referencesReplaced:z83.number().int().nonnegative(),entriesChanged:z83.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z83.object({referencesReplaced:z83.number().int().nonnegative(),filesChanged:z83.number().int().nonnegative(),commitSha:z83.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z83.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z83.object({error:z83.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z83.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z83.object({intent:AssetRemovalIntentSchema,assetIds:z83.array(z83.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z83.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z83.object({id:z83.uuid(),intent:AssetRemovalIntentSchema,assetIds:z83.array(z83.uuid()),replacementAssetId:z83.uuid().nullable(),expiresAt:z83.iso.datetime(),undoable:z83.boolean(),requestedByMe:z83.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z83.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z83.object({error:z83.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z84}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z84.object({key:z84.string(),value:z84.string().optional(),defaultValue:z84.string(),locale:z84.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z85}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=z85.object({id:z85.string(),name:z85.string(),type:z85.enum(["file","folder"]),path:z85.string(),children:z85.lazy(()=>z85.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z85.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z85.object({path:z85.string(),exists:z85.boolean(),type:z85.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z86}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z86.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z86.object({minLength:z86.number().optional(),maxLength:z86.number().optional(),min:z86.number().optional(),max:z86.number().optional(),pattern:z86.string().optional(),maxFileSize:z86.number().optional(),accept:z86.array(z86.string()).optional()}),FormFieldSchema=z86.object({type:FormFieldTypeSchema,label:z86.string(),placeholder:z86.string().optional(),required:z86.boolean().optional(),defaultValue:z86.string().optional(),options:z86.array(z86.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z86.record(z86.string(),FormFieldSchema),FormContentSchema2=z86.object({name:z86.string().min(1).max(255),label:z86.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update2=>update2.name!==void 0||update2.label!==void 0||update2.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z87}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=z87.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z87.object({items:z87.array(ProjectMessagePublicDTOSchema),nextCursor:z87.string().nullable()}),ChatLiveTurnDTOSchema=z87.object({invocationId:z87.string(),step:z87.enum(["preparing","working","compacting","merging"]),startedAt:z87.string()}),ChatLiveTurnStateDTOSchema=z87.object({threadId:z87.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z87.object({id:z87.string(),role:z87.enum(["user","assistant"]),parts:z87.array(z87.unknown()),metadata:z87.record(z87.string(),z87.unknown()).nullable(),versionId:z87.string().nullable().optional(),createdAt:z87.date().transform(value=>value.toISOString()),providerMessageId:z87.string().nullable().optional(),invocationId:z87.string().nullable().optional(),invocationStatus:z87.string().nullable().optional(),invocationTerminalReason:z87.string().nullable().optional()}),ChatAttentionDTOSchema=z87.object({type:z87.literal("merge_conflict"),merge:z87.object({mergeId:z87.string().uuid(),projectId:z87.string(),fromBranch:z87.string(),toBranch:z87.string()}),publishAfterMerge:z87.boolean()}),ChatThreadMessagesPageDTOSchema=z87.object({threadId:z87.string().nullable(),title:z87.string().nullable(),messages:z87.array(ChatThreadMessageDTOSchema),nextCursor:z87.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z87.object({kind:z87.literal("replay"),threadId:z87.string(),userMessageId:z87.string()}),ChatQueuedOutcomeDTOSchema=z87.object({kind:z87.literal("queued"),threadId:z87.string(),userMessageId:z87.string(),blockingRootId:z87.string()}),ChatBusyOutcomeDTOSchema=z87.object({kind:z87.literal("busy"),threadId:z87.string(),userMessageId:z87.string(),blockingRootId:z87.string().optional()}),ChatRefusedOutcomeDTOSchema=z87.object({kind:z87.literal("refused"),threadId:z87.string(),userMessageId:z87.string(),refusedInvocationId:z87.string(),terminalReason:z87.string()}),ChatNonStreamingOutcomeDTOSchema=z87.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z87.object({success:z87.boolean(),deletedCount:z87.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z87.object({code:z87.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z87.string()})}});import{z as z88}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z88.object({url:z88.string().url(),key:z88.string(),size:z88.number(),contentType:z88.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z89}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=z89.object({canAccess:z89.boolean(),permissions:z89.record(z89.string(),z89.boolean()),role:z89.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z90}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:z90.string().trim().default(""),sort:z90.enum(["recent","name","relevance"]).default("recent"),category:z90.string().optional()})}});import{z as z91}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_common2();init_create_dto();init_response();DomainStatusSchema=z91.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z91.enum(["fimo","external"]),PaymentStatusSchema=z91.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z91.object({id:z91.string().uuid(),domain:z91.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z91.boolean(),price:z91.number().int().nullable(),renewalPrice:z91.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z91.string().nullable(),failureReason:z91.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z91.object({domain:z91.string(),available:z91.boolean(),premium:z91.boolean(),price:z91.number().nullable(),renewalPrice:z91.number().nullable(),purchaseType:z91.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z91.object({domain:z91.string(),price:z91.number().nullable(),renewalPrice:z91.number().nullable(),premium:z91.boolean(),allowedYears:z91.array(z91.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z91.object({firstName:z91.string().max(100),lastName:z91.string().max(100),companyName:z91.string().max(100).optional(),address1:z91.string().max(255),address2:z91.string().max(255).optional(),city:z91.string().max(100),state:z91.string().max(100),zip:z91.string().max(20),country:z91.string().max(2),phone:z91.string().max(30),email:z91.union([z91.string().email().max(255),z91.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z91.object({firstName:z91.string().min(1).max(100),lastName:z91.string().min(1).max(100),companyName:z91.string().max(100).optional(),address1:z91.string().min(1).max(255),address2:z91.string().max(255).optional(),city:z91.string().min(1).max(100),state:z91.string().min(1).max(100),zip:z91.string().min(1).max(20),country:z91.string().min(1).max(2),phone:z91.string().min(1).max(30),email:z91.string().email().max(255)}),SearchDomainsRequestSchema=z91.object({keyword:z91.string().min(1).max(100),tldFilter:z91.array(z91.string()).optional()}),CheckAvailabilityRequestSchema=z91.object({domains:z91.array(z91.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=z91.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z91.object({domain:DomainNameSchema,years:z91.number().int().min(1).max(10).optional().default(3),autoRenew:z91.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z91.object({autoRenew:z91.boolean().optional()}),RenewDomainRequestSchema=z91.object({years:z91.number().int().min(1).max(10).optional().default(1),autoRenew:z91.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z91.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z91.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z91.object({verified:z91.boolean(),email:z91.string().nullable(),verifyBy:z91.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z92}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_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z92.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=z92.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=z92.object({txtName:z92.string().nullable().optional(),txtValue:z92.string().nullable().optional(),httpUrl:z92.string().nullable().optional(),httpBody:z92.string().nullable().optional(),cname:z92.string().nullable().optional(),cnameTarget:z92.string().nullable().optional()}),SSLValidationErrorSchema=z92.object({message:z92.string()}),OwnershipVerificationSchema=z92.object({type:z92.string(),name:z92.string(),value:z92.string()}),ProjectDomainSSLDTOSchema=z92.object({status:z92.string(),method:z92.string().nullable(),type:z92.string().nullable(),validationRecords:z92.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z92.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z92.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z92.enum(["subdomain","apex"]),RedirectConfigSchema=z92.object({type:z92.literal("apex_to_www"),linkedDomainId:z92.string()}).nullable().optional(),ProjectDomainDTOSchema=z92.object({id:z92.string(),hostname:z92.string(),status:z92.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z92.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z92.string(),scdCnameTarget:z92.string().optional(),apexTargets:z92.array(z92.string()),dnsAutoConfigured:z92.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z92.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z92.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z92.object({hostname:z92.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:z92.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z92.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z92.object({available:z92.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z92.object({success:z92.boolean(),hostname:z92.string()}))}});import{z as z93}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=z93.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z93.object({slug:z93.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z93.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z93.object({subdomain:z93.string(),subdomainUpdatedAt:z93.coerce.date()})),SubdomainSuggestionsQuerySchema=z93.object({base:z93.string().max(100).optional(),max:z93.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z93.object({suggestions:z93.array(z93.string())}))}});import{z as z94}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","org_agent_registry_reference","source_registered_domain"],ProjectTransferBlockerCodeSchema=z94.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z94.object({code:ProjectTransferBlockerCodeSchema,message:z94.string(),count:z94.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z94.object({targetOrganizationId:z94.string().min(1)}),ProjectTransferResultDTO=createDTO(z94.object({projectId:z94.string(),sourceOrganizationId:z94.string(),targetOrganizationId:z94.string(),movedThreads:z94.number().int().nonnegative(),revokedInvites:z94.number().int().nonnegative(),revokedGrants:z94.number().int().nonnegative(),preservedGrants:z94.number().int().nonnegative(),warnings:z94.array(z94.string())}))}});import{z as z95}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z95.object({translated:z95.number().int().nonnegative(),total:z95.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z95.object({locale:z95.string(),isDefault:z95.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z95.object({defaultLocale:z95.string(),locales:z95.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z95.object({locale:z95.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z95.object({locale:z95.string().min(1).max(40)}),ProjectLocaleMutationSchema=z95.object({locale:z95.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z95.object({locale:z95.string(),entriesDeleted:z95.number().int().nonnegative(),labelsDeleted:z95.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z96}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z96.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z96.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z96.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z96.number(),credits:z96.number().optional(),billingMode:z96.enum(["fimo-credits","provider-account"]).optional(),confidence:z96.enum(["exact","estimated","metered"]),basis:z96.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z97}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z97.object({options:z97.record(z97.string(),z97.unknown()),name:z97.string().optional(),parentId:z97.string().nullable().optional(),altText:z97.string().optional(),caption:z97.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z97.string().min(1).optional(),model:z97.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z97.object({jobId:z97.string(),status:z97.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z97.string().nullable().optional(),credits:z97.number().optional(),costUsd:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z97.object({error:z97.string(),code:z97.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z97.array(GenerationTaskIdSchema).optional(),availableModels:z97.array(z97.string()).optional(),issues:z97.array(z97.unknown()).optional()})}});import{z as z98}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z98.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z98.object({name:z98.string(),key:z98.string(),description:z98.string(),type:FlagTypeSchema,required:z98.boolean(),defaultValue:z98.unknown().optional(),enumValues:z98.array(z98.string()).optional(),isArray:z98.boolean()}),AssetModelPriceSchema=z98.object({unitPrice:z98.number(),unit:z98.string(),confidence:z98.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z98.object({id:z98.string(),shortName:z98.string(),provider:z98.string(),source:z98.string(),modality:z98.enum(["image","video","audio"]),tags:z98.array(z98.string()),displayName:z98.string(),description:z98.string(),flags:z98.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z98.object({model:z98.string(),costUsd:z98.number(),credits:z98.number(),billingMode:z98.enum(["fimo-credits","provider-account"]),confidence:z98.enum(["exact","estimated","metered"]),basis:z98.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z99}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z99.object({tourId:z99.string(),version:z99.string(),status:z99.string(),completedAt:z99.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z99.array(UserTourDTOSchema))}});import{z as z100}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=z100.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z100.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z100.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z100.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z100.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z100.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z100.enum(["user","agent","system"]),SupportReportTagSchema=z100.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z100.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z100.object({organization:z100.object({id:z100.string().trim().min(1).max(255),name:z100.string().trim().max(240).optional()}),project:z100.object({id:z100.uuid(),name:z100.string().trim().max(240).optional(),createdAt:z100.coerce.date().optional()}).optional(),environment:z100.string().trim().max(255).optional(),clientVersion:z100.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z100.object({message:z100.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z100.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z100.string().trim().max(200).optional(),limit:z100.coerce.number().int().min(1).max(100).default(50),offset:z100.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z100.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z100.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z100.uuid().nullable().optional(),note:z100.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=z100.object({message:z100.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z100.object({kind:SupportReportLinkKindSchema,label:z100.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z100.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z100.object({kind:SupportReportActorKindSchema,id:z100.string().nullable(),name:z100.string().nullable()}),SupportReportLinkDTOSchema=z100.object({id:z100.uuid(),kind:SupportReportLinkKindSchema,label:z100.string(),url:SupportReportHttpUrlSchema,externalId:z100.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z100.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z100.object({id:z100.uuid(),kind:SupportReportEventKindSchema,body:z100.string().nullable(),metadata:z100.record(z100.string(),z100.unknown()),actor:SupportReportActorDTOSchema,createdAt:z100.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z100.object({id:z100.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z100.array(z100.string()),source:SupportReportSourceSchema,message:z100.string(),reporter:z100.object({id:z100.string().nullable(),name:z100.string().nullable(),email:z100.string().nullable()}),organization:z100.object({id:z100.string().nullable(),name:z100.string()}),project:z100.object({id:z100.uuid().nullable(),name:z100.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z100.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z100.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z100.string().nullable(),deliveredAt:z100.coerce.date().nullable()}).nullable(),duplicateOfReportId:z100.uuid().nullable(),resolvedAt:z100.coerce.date().nullable(),createdAt:z100.coerce.date(),updatedAt:z100.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z100.string().nullable(),clientVersion:z100.string().nullable(),links:z100.array(SupportReportLinkDTOSchema),events:z100.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z100.object({reports:z100.array(SupportReportSummaryDTOSchema),total:z100.number().int().nonnegative(),statusCounts:z100.object({new:z100.number().int().nonnegative(),in_progress:z100.number().int().nonnegative(),waiting:z100.number().int().nonnegative(),resolved:z100.number().int().nonnegative(),duplicate:z100.number().int().nonnegative(),irrelevant:z100.number().int().nonnegative(),ignored:z100.number().int().nonnegative()}),limit:z100.number().int().positive(),offset:z100.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z100.object({id:z100.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z100.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z101}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=z101.iso.datetime({offset:!0}).pipe(z101.coerce.date()),OpsRecentChatInputSchema=z101.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z101.string().trim().min(1).max(255).optional(),limit:z101.coerce.number().int().min(1).max(200).default(100),cursor:z101.string().trim().min(1).max(2e3).optional(),slim:z101.boolean().default(!0),reason:z101.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=z101.object({id:z101.string(),threadId:z101.string(),providerMessageId:z101.string().nullable(),invocationId:z101.string().nullable(),env:z101.string().nullable(),role:z101.string(),parts:z101.array(z101.record(z101.string(),z101.unknown())),metadata:z101.object({status:z101.string().optional(),traceUrl:z101.string().optional(),externalFileChanges:z101.array(z101.unknown()).optional()}),stats:z101.object({toolCount:z101.number().int().nonnegative(),failedToolCount:z101.number().int().nonnegative()}),createdAt:z101.iso.datetime({offset:!0}),project:z101.object({id:z101.string(),name:z101.string(),displayName:z101.string().nullable(),organizationId:z101.string().nullable()})}),OpsRecentChatResponseSchema=z101.object({target:z101.object({backendProfile:OpsBackendProfileSchema,projectEnv:z101.string().nullable()}),window:z101.object({from:z101.iso.datetime({offset:!0}),to:z101.iso.datetime({offset:!0})}),messages:z101.object({items:z101.array(OpsRecentChatMessageSchema),nextCursor:z101.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z102}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=z102.object({backendProfile:OpsBackendProfileSchema,provider:z102.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z102.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z102.object({backendProfile:OpsBackendProfileSchema,provider:z102.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z102.literal(!1),reason:z102.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z103}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=z103.object({packageManager:z103.string().trim().min(1).max(200).nullable(),trackedLockfiles:z103.array(z103.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z103.string().trim().min(1)}),OpsProjectPackageManagerSchema=z103.object({target:z103.object({backendProfile:OpsBackendProfileSchema,projectId:z103.uuid(),projectEnv:z103.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z104}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z104.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchDiscardPlanInputSchema=z104.object({branches:OpsAgentBranchAllowlistSchema,reason:z104.string().trim().min(1).max(1e3)}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.extend({planHash:z104.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants"],OpsAgentBranchDiscardBlockerSchema=z104.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z105}from"zod";function createAgentRunWebhookEventDataSchema(status){return z105.object({run:z105.object({id:z105.string(),agentName:z105.string(),trigger:z105.string(),status:z105.literal(status),startedAt:z105.string().nullable(),finishedAt:z105.string().nullable(),reason:z105.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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_common2();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","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z105.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z105.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z105.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z105.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z105.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z105.object({reason:WebhookEntryChangeReasonSchema,operationId:z105.string().optional(),batch:z105.object({index:z105.number().int().positive(),total:z105.number().int().positive()}).optional(),changes:z105.array(z105.object({action:WebhookEntryChangeActionSchema,contentType:z105.string(),id:z105.string(),documentId:z105.string(),locale:z105.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z105.object({form:z105.object({id:z105.string(),label:z105.string()}),submission:z105.object({id:z105.string(),data:z105.record(z105.string(),z105.unknown()),submittedAt:z105.string()})}),PublishStartedWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("publishing"),startedAt:z105.string()})}),PublishSucceededWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("published"),url:z105.string(),publishedAt:z105.string(),firstPublish:z105.boolean()})}),PublishFailedWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("failed"),reason:z105.string()})}),PublishUnpublishedWebhookEventDataSchema=z105.object({publication:z105.object({previousUrl:z105.string(),unpublishedAt:z105.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z105.object({review:z105.object({id:z105.string(),runId:z105.string(),agentName:z105.string(),classification:z105.string(),summary:z105.string(),reasons:z105.array(z105.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z105.object({review:z105.object({id:z105.string(),runId:z105.string(),agentName:z105.string(),resolution:z105.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z105.object({report:z105.object({weekStart:z105.string(),weekEnd:z105.string(),pageviews:z105.number(),visitors:z105.number(),previousPageviews:z105.number(),previousVisitors:z105.number()})}),MediaAssetWebhookEventDataSchema=z105.object({id:z105.string().nullable(),name:z105.string().nullable(),type:z105.string(),mimeType:z105.string().nullable(),fileSize:z105.number().nullable()}),MediaUploadedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("updated")}),MediaDeletedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z105.object({domain:z105.object({id:z105.string(),hostname:z105.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z105.object({domain:z105.object({id:z105.string(),hostname:z105.string()})}),LabelChangedWebhookEventDataSchema=z105.object({changes:z105.array(z105.object({action:z105.enum(["created","updated","deleted"]),key:z105.string(),locale:z105.string(),value:z105.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),isDefault:z105.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),previousCode:z105.string()})}),LocaleDeletedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),entriesDeleted:z105.number().int().nonnegative(),labelsDeleted:z105.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z105.object({environment:z105.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z105.object({environment:z105.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z105.object({merge:z105.object({id:z105.string(),from:BranchSchema,to:BranchSchema,applied:z105.array(z105.object({surface:SurfaceNameSchema,count:z105.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z105.object({branch:z105.object({name:BranchSchema}),version:z105.object({versionId:z105.uuid(),name:z105.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,"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,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z105.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z105.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z105.discriminatedUnion("source",[z105.object({source:z105.literal("literal"),value:z105.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z105.object({source:z105.literal("secret"),key:z105.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z105.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z105.object({name:z105.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z105.object({name:z105.string(),source:z105.enum(["literal","secret"]),secretKey:z105.string().nullable(),secretPrefix:z105.string().nullable(),configured:z105.literal(!0)}),WebhookFilterSchema=z105.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z105.string().min(1).max(255).optional(),agentName:z105.string().min(1).max(120).optional(),mediaType:z105.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z105.string().min(1).max(255).optional(),locale:z105.string().min(1).max(120).optional()}),JsonValueSchema=z105.lazy(()=>z105.union([z105.string(),z105.number(),z105.boolean(),z105.null(),z105.array(JsonValueSchema),z105.record(z105.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z105.object({name:z105.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z105.url(),enabled:z105.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z105.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z105.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z105.object({name:z105.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z105.url().optional(),enabled:z105.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z105.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z105.boolean().optional()}),TestProjectWebhookRequestSchema=z105.object({eventType:WebhookEventTypeSchema.optional(),data:z105.record(z105.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z105.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z105.uuid(),name:z105.string(),eventType:WebhookEventTypeSchema,enabled:z105.boolean(),destination:z105.object({host:z105.string(),maskedUrl:z105.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z105.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z105.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z105.coerce.date().nullable(),deliveryStats24h:z105.object({succeeded:z105.number().int().nonnegative(),failed:z105.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z105.uuid(),projectId:z105.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z105.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z105.number().int().positive(),test:z105.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z105.number().int().nonnegative(),responseStatus:z105.number().int().nullable(),lastErrorCode:z105.string().nullable(),lastErrorMessage:z105.string().nullable(),payloadAvailable:z105.boolean(),destination:z105.object({host:z105.string(),maskedUrl:z105.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z105.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z105.string().nullable(),qstashMessageId:z105.string().nullable(),deliveredAt:z105.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z105.object({items:z105.array(WebhookDeliveryDTOSchema),pagination:z105.object({page:z105.number().int().positive(),limit:z105.number().int().positive(),total:z105.number().int().nonnegative(),totalPages:z105.number().int().positive(),hasMore:z105.boolean()}),stats:z105.object({total:z105.number().int().nonnegative(),succeeded:z105.number().int().nonnegative(),failed:z105.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z105.object({id:z105.uuid(),deliveryId:z105.uuid(),attempt:z105.number().int().positive(),status:z105.enum(["delivering","succeeded","failed"]),responseStatus:z105.number().int().nullable(),durationMs:z105.number().int().nonnegative(),responseExcerpt:z105.string().nullable(),errorCode:z105.string().nullable(),errorMessage:z105.string().nullable(),createdAt:z105.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z105.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z105.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z106}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=z106.object({key:z106.literal("fimo-2"),enabled:z106.boolean(),dismissed:z106.boolean().default(!1),interacted:z106.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z107}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_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z107.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z107.object({total:z107.number(),base:z107.number(),purchases:z107.number(),awards:z107.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z107.object({id:z107.string(),name:z107.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z107.object({type:z107.string(),brand:z107.string().nullable(),last4:z107.string().nullable(),expirationDate:z107.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z107.object({currency:z107.string(),nextPaymentAmount:z107.number().nullable(),nextPaymentAt:z107.string().nullable(),billingInterval:z107.string().nullable(),totalAmount:z107.number().nullable(),discountAmount:z107.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z107.object({id:z107.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z107.string().nullable(),currentPeriodEndsAt:z107.string().nullable(),renewsAt:z107.string().nullable(),cancelAt:z107.string().nullable(),renewAutomatically:z107.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z107.object({type:z107.enum(["low_balance","critical_balance","approaching_limit"]),message:z107.string(),estimatedPromptsRemaining:z107.number().nullable(),avgCostPerPrompt:z107.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z107.object({monthlyCredits:z107.number().nullable(),usedThisPeriod:z107.number(),remainingThisPeriod:z107.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z107.object({organizationId:z107.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z107.string().nullable(),tenureDays:z107.number().int().nonnegative(),capturedAt:z107.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z107.object({hasSubscription:z107.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z107.number().nullable(),alerts:z107.array(CreditAlertDTOSchema),portalUrl:z107.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z107.object({creditCount:z107.number().int().positive(),expiresAt:z107.string().datetime().nullable().optional(),message:z107.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z107.literal("free"),amountCents:z107.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z107.literal("purchase"),amountCents:z107.number().int().positive()}),CreditTopupRequestDTOSchema=z107.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z107.object({success:z107.boolean(),transactionId:z107.string().nullable(),newBalance:z107.number(),creditCount:z107.number(),type:z107.enum(["free","purchase"]),invoiceId:z107.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z108}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=z108.object({totalCredits:z108.number(),totalCostUsd:z108.number(),totalMessages:z108.number(),avgCostPerMessage:z108.number(),periodStart:z108.string().nullable(),periodEnd:z108.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z108.object({projectId:z108.string(),projectName:z108.string(),projectDisplayName:z108.string().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z108.object({userId:z108.string(),userName:z108.string().nullable(),userEmail:z108.string().email().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z108.object({date:z108.string(),credits:z108.number(),costUsd:z108.number(),messages:z108.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z108.object({userId:z108.string(),userName:z108.string().nullable(),userEmail:z108.string().email().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z108.object({projectId:z108.string(),projectName:z108.string(),projectDisplayName:z108.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z108.array(UsageByUserForProjectDTOSchema),timeline:z108.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z108.object({summary:UsageSummaryDTOSchema,byProject:z108.array(UsageByProjectDTOSchema),byUser:z108.array(UsageByUserDTOSchema),timeline:z108.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z109}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=z109.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z109.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z109.object({startDate:z109.string().optional(),endDate:z109.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z109.coerce.number().int().positive().default(1),limit:z109.coerce.number().int().positive().max(100).default(20),sortBy:z109.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z109.string().optional(),activeOnly:z109.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),avgCreditsPerMessage:z109.number(),periodStart:z109.string(),periodEnd:z109.string(),creditsChange:z109.number().nullable(),costChange:z109.number().nullable(),messagesChange:z109.number().nullable(),unattributedCredits:z109.number(),unattributedCostUsd:z109.number(),unattributedMessages:z109.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z109.object({organizationId:z109.string(),organizationName:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),userCount:z109.number(),projectCount:z109.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().nullable(),userImage:z109.string().nullable(),organizationId:z109.string().nullable(),organizationName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),projectCount:z109.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),organizationId:z109.string(),organizationName:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),userCount:z109.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z109.object({id:z109.string(),name:z109.string(),value:z109.number(),percentage:z109.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z109.object({day:z109.number(),hour:z109.number(),value:z109.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z109.object({summary:UsageOverviewSummaryDTOSchema,timeline:z109.array(UsageTimelinePointDTOSchema),topOrganizations:z109.array(OrganizationUsageRowDTOSchema),topUsers:z109.array(UserUsageRowDTOSchema),topProjects:z109.array(ProjectUsageRowDTOSchema),creditDistribution:z109.array(UsageDistributionItemDTOSchema),userDistribution:z109.array(UsageDistributionItemDTOSchema),heatmap:z109.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z109.object({page:z109.number(),limit:z109.number(),totalItems:z109.number(),totalPages:z109.number(),hasMore:z109.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z109.object({organizations:z109.array(OrganizationUsageRowDTOSchema),top:z109.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z109.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z109.object({users:z109.array(ExtendedUserUsageRowDTOSchema),top:z109.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z109.string(),ownerName:z109.string().nullable(),ownerEmail:z109.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z109.object({projects:z109.array(ExtendedProjectUsageRowDTOSchema),top:z109.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z109.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z109.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z109.object({credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z109.object({id:z109.string(),name:z109.string(),createdAt:z109.string(),memberCount:z109.number(),projectCount:z109.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z109.object({id:z109.string(),name:z109.string().nullable(),email:z109.string(),image:z109.string().nullable(),createdAt:z109.string(),organizationCount:z109.number(),projectCount:z109.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z109.object({id:z109.string(),name:z109.string(),displayName:z109.string().nullable(),createdAt:z109.string(),organizationId:z109.string(),organizationName:z109.string(),ownerId:z109.string(),ownerName:z109.string().nullable(),ownerEmail:z109.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z110}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=z110.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z110.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z110.object({command:z110.string().min(1).max(1e4),cwd:z110.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z110.record(z110.string(),z110.string()).optional(),name:z110.string().optional(),waitForCompletion:z110.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=z110.object({identifier:z110.string(),status:SandboxProcessStatusSchema,command:z110.string().optional(),startedAt:z110.string().optional(),exitCode:z110.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z110.object({processes:z110.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z110.object({processId:z110.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z110.object({success:z110.boolean(),message:z110.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z111}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();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_files();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_control_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_notification_preference_catalog_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch:null}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment();if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
208
+ `)}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,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.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=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index2)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index2,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.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.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.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=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}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=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.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:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.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")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,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_common2();init_env();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.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}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_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.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=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}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=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}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=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}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=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.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:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}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=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}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=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema)}});import{z as z57}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=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}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=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,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=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),longRunning:z59.boolean(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}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=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index2)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index2],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}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=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.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=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}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,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,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=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),connectionCapabilities:z62.object({customIdentityCreation:z62.boolean()}).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z62.object({value:z62.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),registrationId:z62.uuid().nullable(),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z62.boolean(),isDefault:z62.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.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=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z62.object({displayName:z62.string().trim().min(1).max(35),backgroundColor:z62.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z62.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.boolean().optional(),registrationId:z62.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.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=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),LinearOAuthApplicationDistributionSchema=z62.enum(["private","public"]),OrganizationLinearAppDTOSchema=z62.object({id:z62.uuid(),displayName:z62.string().min(1),description:z62.string().nullable(),iconUrl:z62.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z62.enum(["active","revoked"]),connectionIds:z62.array(z62.uuid()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z62.object({appName:z62.string().trim().min(2).max(80),description:z62.string().trim().max(1e3).optional(),iconUrl:z62.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.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=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().optional(),reservedCredits:z62.number().optional(),actualCredits:z62.number().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.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=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}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_common2();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=z64.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=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,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=z65.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),ListNotificationsQuerySchema=z65.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.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=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}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=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}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=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}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_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}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_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.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=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}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=z73.object({name:z73.string().min(1),version:z73.string().min(1)}),PreviewBridgeCapabilitySchema=z73.object({integrated:z73.boolean(),packages:z73.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z73.object({url:z73.url(),expiresAt:z73.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z73.object({name:z73.string().min(1),locator:z73.string().min(1).optional(),source:z73.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z73.object({kind:z73.literal("dependency_build_scripts_blocked"),packageManager:z73.enum(["pnpm","yarn","bun"]),packages:z73.array(z73.string()),targets:z73.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z73.string(),approvalKey:z73.string(),command:z73.string().optional(),approval:z73.object({id:z73.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z73.object({code:z73.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z73.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z73.object({approvalId:z73.uuid()}),PreviewInstallPolicyApprovalEventSchema=z73.discriminatedUnion("type",[z73.object({type:z73.literal("progress"),step:z73.enum(["approval","install","restart","readiness"]),message:z73.string()}),z73.object({type:z73.literal("approved")}),z73.object({type:z73.literal("complete")}),z73.object({type:z73.literal("error"),code:z73.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z73.string()})])}});import{z as z74}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z74.string(),slug:z74.string().nullable(),logo:z74.string().nullable(),metadata:z74.record(z74.string(),z74.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z74.object({id:z74.string(),name:z74.string(),email:z74.email(),image:z74.string().nullable()}),OrganizationMemberDTOSchema=z74.object({id:z74.string(),userId:z74.string(),organizationId:z74.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z74.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z75}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,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_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z75.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z75.object({reason:CancellationReasonCodeSchema,details:z75.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z75.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z75.object({offerVersion:z75.string().trim().min(1),unusedPremiumCreditAmount:z75.number().int().nonnegative(),amountDueNow:z75.number().int().nonnegative(),renewsOn:z75.string()}),PlanMigrationPreviewDTOSchema=z75.object({currency:z75.string().trim().min(1),unusedPremiumCreditAmount:z75.number().int().nonnegative(),amountDueNow:z75.number().int().nonnegative(),startsAt:z75.string(),renewsAt:z75.string(),nextRenewalAmount:z75.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z75.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z75.object({id:z75.string(),organizationId:z75.string(),legacySubscriptionId:z75.string(),offeredPlanCode:z75.string(),offeredPlanName:z75.string(),offeredPriceAmount:z75.number(),offeredCurrency:z75.string(),offerVersion:z75.string(),state:PlanMigrationStateSchema,checkoutToken:z75.string().nullable(),deadlineAt:z75.string(),transitions:z75.array(z75.object({event:z75.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z75.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z75.object({included:z75.number().optional(),unitPrice:z75.number().optional(),dailyCap:z75.number().nullable().optional()}),EntitlementsDTOSchema=z75.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z75.object({retentionDays:z75.number().int().positive(),canUseExtendedDateRanges:z75.boolean()}).optional(),history:z75.object({retentionDays:z75.number().int().positive()}).optional(),members:z75.object({canInvite:z75.boolean(),maxMembers:z75.number().int().positive().nullable()}).optional(),projects:z75.object({maxProjects:z75.number().int().positive().nullable()}).optional(),domains:z75.object({canUseCustomDomains:z75.boolean(),maxDomains:z75.number().int().nonnegative().nullable()}).optional(),media_storage:z75.object({limitBytes:z75.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z75.object({usedBytes:z75.number().int().nonnegative().nullable(),limitBytes:z75.number().int().nonnegative().nullable(),state:z75.enum(["ready","unavailable"]),measuredAt:z75.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z75.object({toPlanCode:TemplateCodeSchema,effectiveAt:z75.string(),scheduledAt:z75.string().nullable()}),HostingOverageStatusDTOSchema=z75.object({state:z75.enum(["ready","unavailable"]),planCode:z75.string(),overageAvailable:z75.boolean(),overageEnabled:z75.boolean(),monthlyCapUsd:z75.number().int().positive().nullable(),periodStart:z75.iso.datetime().nullable(),periodEnd:z75.iso.datetime().nullable(),usedBytes:z75.number().nonnegative().nullable(),includedBytes:z75.number().nonnegative().nullable(),overageBytes:z75.number().nonnegative(),currentOverageAmountMicros:z75.number().nonnegative().nullable(),currency:z75.string().nullable(),status:z75.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z75.object({enabled:z75.boolean(),monthlyCapUsd:z75.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling overages requires a monthly cap"}),SubscriptionDTOSchema=z75.object({id:z75.string(),external_id:z75.string(),customerId:z75.string(),planId:z75.string(),planCode:z75.union([TemplateCodeSchema,z75.literal("Unknown")]),currentPeriod:z75.object({start:z75.string(),end:z75.string().nullable()}),cancelAt:z75.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z75.string(),nextPaymentAt:z75.string().nullable(),baseAmount:z75.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z75.object({totalCap:z75.number(),dailyCap:z75.number(),usedTotal:z75.number()}),CreditBalanceDTOSchema=z75.object({total:z75.number(),base:z75.number(),dailyBase:z75.number(),purchases:z75.number(),awards:z75.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z75.object({total:z75.number(),nearLimit:z75.boolean(),canChat:z75.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z75.object({dailyFreeAvailable:z75.number(),monthlyAvailable:z75.number(),purchasedAvailable:z75.number(),awardedAvailable:z75.number()}),ProjectDailyCreditAllowanceDTOSchema=z75.object({periodCap:z75.number(),dailyGrant:z75.number(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),ProjectCreditBalanceDTOSchema=z75.object({projectId:z75.uuid(),organizationId:z75.string(),balance:z75.object({totalAvailable:z75.number(),nearLimit:z75.boolean(),canUseAi:z75.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z75.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z75.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z75.object({planCode:z75.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z75.object({source:z75.enum(["cached_subscription","free_fallback"]),settledMs:z75.number().int().nonnegative(),activeMs:z75.number().int().nonnegative(),reservedMs:z75.number().int().nonnegative().optional(),includedMs:z75.number().int().positive(),remainingMs:z75.number().int().nonnegative(),resetsAt:z75.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z75.discriminatedUnion("enabled",[z75.object({enabled:z75.literal(!0),thresholdUsd:z75.number().nonnegative(),refillAmountUsd:z75.number().nonnegative()}),z75.object({enabled:z75.literal(!1),thresholdUsd:z75.number().nonnegative().nullable(),refillAmountUsd:z75.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z75.discriminatedUnion("enabled",[z75.object({enabled:z75.literal(!0),thresholdUsd:z75.number().min(.01).multipleOf(.01),refillAmountUsd:z75.number().min(.01).multipleOf(.01)}).strict(),z75.object({enabled:z75.literal(!1),thresholdUsd:z75.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z75.object({invoiceId:z75.string(),newBalance:z75.int(),creditCount:z75.int(),amountUsd:z75.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z75.object({url:z75.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema2(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema2(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema2(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema2(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema2(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema2(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema2(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema2(PortalDTOSchema)}});import{z as z76}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=z76.object({brand:z76.string(),last4:z76.string(),exp:z76.string(),isDefault:z76.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z77}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z77.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=z77.object({type:z77.literal("renameField"),contentType:z77.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z77.object({enabled:z77.boolean()}).strict(),ContentFieldGroupSchema=z77.object({id:z77.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z77.string().min(1).max(255),default:z77.boolean().optional()}).strict(),ContentTypeDTOSchema=z77.object({id:z77.string(),name:z77.string(),label:z77.string(),isSingleton:z77.boolean(),i18n:ContentTypeI18nSchema,groups:z77.array(ContentFieldGroupSchema).default([]),fields:z77.record(z77.string(),FieldDefinitionSchema),createdAt:z77.string(),updatedAt:z77.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z77.object({contentTypes:z77.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z77.object({id:z77.string(),entryId:z77.string(),documentId:z77.string(),slug:z77.string(),locale:z77.string().optional(),createdAt:z77.string(),updatedAt:z77.string(),__fimo:z77.object({contentType:z77.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({limit:z77.number(),offset:z77.number(),total:z77.number(),hasMore:z77.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z77.object({contentType:z77.string(),count:z77.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z77.object({counts:z77.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z77.object({count:z77.number().int().nonnegative(),sourceLocale:z77.string(),targetLocale:z77.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z77.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z77.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z77.union([z77.string(),z77.number(),z77.boolean(),z77.null()]),entryWhereOperatorSchema2=z77.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z77.array(entryWhereScalarSchema2).optional(),$nin:z77.array(entryWhereScalarSchema2).optional(),$contains:z77.string().optional(),$startsWith:z77.string().optional(),$null:z77.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z77.record(z77.string(),z77.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z77.record(z77.string(),z77.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z77.object({data:z77.record(z77.string(),z77.unknown()),locale:z77.string().min(1).optional(),documentId:z77.uuid().optional()}),entryIdsSchema=z77.array(z77.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z77.object({sql:z77.string().min(1)}),BulkCreateEntriesRequestSchema=z77.object({entries:z77.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z77.union([z77.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z77.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z77.object({updates:z77.array(z77.object({id:z77.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z77.union([z77.object({ids:entryIdsSchema,locale:z77.string().min(1).optional()}),z77.object({where:EntryWhereSchema2,locale:z77.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z77.object({data:z77.array(z77.record(z77.string(),z77.unknown())),meta:z77.object({rowCount:z77.number().int().nonnegative(),truncated:z77.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({created:z77.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({updated:z77.number().int().nonnegative(),missing:z77.array(z77.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z77.object({data:z77.array(EntryDTOSchema2),meta:z77.object({deleted:z77.number().int().nonnegative(),missing:z77.array(z77.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z78}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z78.object({index:z78.number().int().nonnegative(),contentType:z78.string(),field:z78.string(),value:z78.string(),against:z78.enum(["stored","batch"]),ownerDocumentId:z78.uuid().optional(),ownerIndex:z78.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z78.object({code:z78.literal("unique_conflict"),message:z78.string(),conflicts:z78.array(UniqueConflictSchema),truncated:z78.boolean().optional()})}});import{z as z79}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=z79.object({kind:z79.literal("unique_conflict"),contentType:z79.string(),field:z79.string(),value:z79.string(),documentCount:z79.number().int().positive(),documentIds:z79.array(z79.uuid()),documentIdsTruncated:z79.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z79.object({code:z79.literal("schema_transition_rejected"),message:z79.string(),issues:z79.array(SchemaTransitionIssueSchema),truncated:z79.boolean().optional()})}});import{z as z80}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_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z80.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z80.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z80.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z80.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z80.object({field:CmsFieldNameSchema,direction:z80.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z80.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z80.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z80.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z80.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z80.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z81}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z81.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z82}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z82.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z82.object({event:ClientTrackedEventSchema,properties:z82.record(z82.string(),z82.unknown()).default({})})}});import{z as z83}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z83.object({id:z83.string(),name:z83.string()}),AssetDTOSchema2=z83.object({id:z83.string(),name:z83.string(),type:AssetTypeSchema,originalFileName:z83.string().nullable(),parentId:z83.string().nullable(),mimeType:z83.string().nullable(),fileSize:z83.number().nullable(),url:z83.string().nullable(),storageKey:z83.string().nullable(),createdAt:z83.string(),updatedAt:z83.string(),altText:z83.string().nullable().optional(),caption:z83.string().nullable().optional(),aiCaption:z83.string().nullable().optional(),aiAltText:z83.string().nullable().optional(),aiTags:z83.array(z83.string()).nullable().optional(),aiPrimaryColor:z83.string().nullable().optional(),aiProcessingStatus:z83.string().nullable().optional(),width:z83.number().nullable().optional(),height:z83.number().nullable().optional(),path:z83.array(AssetPathItemSchema).optional(),hasChildren:z83.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z83.lazy(()=>z83.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z83.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z83.object({error:z83.string(),code:z83.literal("media_storage_limit_exceeded"),usedBytes:z83.number().int().nonnegative(),limitBytes:z83.number().int().positive(),incomingBytes:z83.number().int().nonnegative()}),AssetReferenceScopeSchema=z83.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z83.object({assetIds:z83.array(z83.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z83.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z83.object({totalFiles:z83.number().int().nonnegative(),checkedFiles:z83.number().int().nonnegative(),limit:z83.number().int().positive()}),AssetReferenceFindingDTOSchema=z83.object({assetId:z83.uuid(),entryId:z83.string(),documentId:z83.string(),contentType:z83.string(),locale:z83.string().nullable(),slug:z83.string(),fieldPath:z83.string()}),AssetReferenceScopeResultDTOSchema=z83.object({scope:AssetReferenceScopeSchema,label:z83.string(),state:z83.enum(["available","not-published","failed"]),coverage:z83.enum(["complete","partial","failed"]),referenceCount:z83.number().int().nonnegative().optional(),codeReferenceCount:z83.number().int().nonnegative().optional(),referencedAssetIds:z83.array(z83.uuid()).optional(),references:z83.array(AssetReferenceFindingDTOSchema),reason:z83.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z83.discriminatedUnion("type",[z83.object({type:z83.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z83.object({type:z83.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z83.object({type:z83.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z83.object({replacementAssetId:z83.uuid()}),AssetReferenceReplacementResultSchema=z83.object({referencesReplaced:z83.number().int().nonnegative(),entriesChanged:z83.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z83.object({referencesReplaced:z83.number().int().nonnegative(),filesChanged:z83.number().int().nonnegative(),commitSha:z83.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z83.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z83.object({error:z83.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z83.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z83.object({intent:AssetRemovalIntentSchema,assetIds:z83.array(z83.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z83.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z83.object({id:z83.uuid(),intent:AssetRemovalIntentSchema,assetIds:z83.array(z83.uuid()),replacementAssetId:z83.uuid().nullable(),expiresAt:z83.iso.datetime(),undoable:z83.boolean(),requestedByMe:z83.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z83.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z83.object({error:z83.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z84}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z84.object({key:z84.string(),value:z84.string().optional(),defaultValue:z84.string(),locale:z84.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z85}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=z85.object({id:z85.string(),name:z85.string(),type:z85.enum(["file","folder"]),path:z85.string(),children:z85.lazy(()=>z85.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z85.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z85.object({path:z85.string(),exists:z85.boolean(),type:z85.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z86}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z86.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z86.object({minLength:z86.number().optional(),maxLength:z86.number().optional(),min:z86.number().optional(),max:z86.number().optional(),pattern:z86.string().optional(),maxFileSize:z86.number().optional(),accept:z86.array(z86.string()).optional()}),FormFieldSchema=z86.object({type:FormFieldTypeSchema,label:z86.string(),placeholder:z86.string().optional(),required:z86.boolean().optional(),defaultValue:z86.string().optional(),options:z86.array(z86.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z86.record(z86.string(),FormFieldSchema),FormContentSchema2=z86.object({name:z86.string().min(1).max(255),label:z86.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update2=>update2.name!==void 0||update2.label!==void 0||update2.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z87}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=z87.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z87.object({items:z87.array(ProjectMessagePublicDTOSchema),nextCursor:z87.string().nullable()}),ChatLiveTurnDTOSchema=z87.object({invocationId:z87.string(),step:z87.enum(["preparing","working","compacting","merging"]),startedAt:z87.string()}),ChatLiveTurnStateDTOSchema=z87.object({threadId:z87.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z87.object({id:z87.string(),role:z87.enum(["user","assistant"]),parts:z87.array(z87.unknown()),metadata:z87.record(z87.string(),z87.unknown()).nullable(),versionId:z87.string().nullable().optional(),createdAt:z87.date().transform(value=>value.toISOString()),providerMessageId:z87.string().nullable().optional(),invocationId:z87.string().nullable().optional(),invocationStatus:z87.string().nullable().optional(),invocationTerminalReason:z87.string().nullable().optional()}),ChatAttentionDTOSchema=z87.object({type:z87.literal("merge_conflict"),merge:z87.object({mergeId:z87.string().uuid(),projectId:z87.string(),fromBranch:z87.string(),toBranch:z87.string()}),publishAfterMerge:z87.boolean()}),ChatThreadMessagesPageDTOSchema=z87.object({threadId:z87.string().nullable(),title:z87.string().nullable(),messages:z87.array(ChatThreadMessageDTOSchema),nextCursor:z87.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z87.object({kind:z87.literal("replay"),threadId:z87.string(),userMessageId:z87.string()}),ChatQueuedOutcomeDTOSchema=z87.object({kind:z87.literal("queued"),threadId:z87.string(),userMessageId:z87.string(),blockingRootId:z87.string()}),ChatBusyOutcomeDTOSchema=z87.object({kind:z87.literal("busy"),threadId:z87.string(),userMessageId:z87.string(),blockingRootId:z87.string().optional()}),ChatRefusedOutcomeDTOSchema=z87.object({kind:z87.literal("refused"),threadId:z87.string(),userMessageId:z87.string(),refusedInvocationId:z87.string(),terminalReason:z87.string()}),ChatNonStreamingOutcomeDTOSchema=z87.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z87.object({success:z87.boolean(),deletedCount:z87.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z87.object({code:z87.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z87.string()})}});import{z as z88}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z88.object({url:z88.string().url(),key:z88.string(),size:z88.number(),contentType:z88.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z89}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=z89.object({canAccess:z89.boolean(),permissions:z89.record(z89.string(),z89.boolean()),role:z89.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z90}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:z90.string().trim().default(""),sort:z90.enum(["recent","name","relevance"]).default("recent"),category:z90.string().optional()})}});import{z as z91}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_common2();init_create_dto();init_response();DomainStatusSchema=z91.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z91.enum(["fimo","external"]),PaymentStatusSchema=z91.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z91.object({id:z91.string().uuid(),domain:z91.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z91.boolean(),price:z91.number().int().nullable(),renewalPrice:z91.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z91.string().nullable(),failureReason:z91.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z91.object({domain:z91.string(),available:z91.boolean(),premium:z91.boolean(),price:z91.number().nullable(),renewalPrice:z91.number().nullable(),purchaseType:z91.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z91.object({domain:z91.string(),price:z91.number().nullable(),renewalPrice:z91.number().nullable(),premium:z91.boolean(),allowedYears:z91.array(z91.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z91.object({firstName:z91.string().max(100),lastName:z91.string().max(100),companyName:z91.string().max(100).optional(),address1:z91.string().max(255),address2:z91.string().max(255).optional(),city:z91.string().max(100),state:z91.string().max(100),zip:z91.string().max(20),country:z91.string().max(2),phone:z91.string().max(30),email:z91.union([z91.string().email().max(255),z91.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z91.object({firstName:z91.string().min(1).max(100),lastName:z91.string().min(1).max(100),companyName:z91.string().max(100).optional(),address1:z91.string().min(1).max(255),address2:z91.string().max(255).optional(),city:z91.string().min(1).max(100),state:z91.string().min(1).max(100),zip:z91.string().min(1).max(20),country:z91.string().min(1).max(2),phone:z91.string().min(1).max(30),email:z91.string().email().max(255)}),SearchDomainsRequestSchema=z91.object({keyword:z91.string().min(1).max(100),tldFilter:z91.array(z91.string()).optional()}),CheckAvailabilityRequestSchema=z91.object({domains:z91.array(z91.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=z91.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z91.object({domain:DomainNameSchema,years:z91.number().int().min(1).max(10).optional().default(3),autoRenew:z91.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z91.object({autoRenew:z91.boolean().optional()}),RenewDomainRequestSchema=z91.object({years:z91.number().int().min(1).max(10).optional().default(1),autoRenew:z91.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z91.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z91.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z91.object({verified:z91.boolean(),email:z91.string().nullable(),verifyBy:z91.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z92}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_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z92.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=z92.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=z92.object({txtName:z92.string().nullable().optional(),txtValue:z92.string().nullable().optional(),httpUrl:z92.string().nullable().optional(),httpBody:z92.string().nullable().optional(),cname:z92.string().nullable().optional(),cnameTarget:z92.string().nullable().optional()}),SSLValidationErrorSchema=z92.object({message:z92.string()}),OwnershipVerificationSchema=z92.object({type:z92.string(),name:z92.string(),value:z92.string()}),ProjectDomainSSLDTOSchema=z92.object({status:z92.string(),method:z92.string().nullable(),type:z92.string().nullable(),validationRecords:z92.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z92.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z92.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z92.enum(["subdomain","apex"]),RedirectConfigSchema=z92.object({type:z92.literal("apex_to_www"),linkedDomainId:z92.string()}).nullable().optional(),ProjectDomainDTOSchema=z92.object({id:z92.string(),hostname:z92.string(),status:z92.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z92.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z92.string(),scdCnameTarget:z92.string().optional(),apexTargets:z92.array(z92.string()),dnsAutoConfigured:z92.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z92.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z92.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z92.object({hostname:z92.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:z92.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z92.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z92.object({available:z92.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z92.object({success:z92.boolean(),hostname:z92.string()}))}});import{z as z93}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=z93.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z93.object({slug:z93.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z93.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z93.object({subdomain:z93.string(),subdomainUpdatedAt:z93.coerce.date()})),SubdomainSuggestionsQuerySchema=z93.object({base:z93.string().max(100).optional(),max:z93.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z93.object({suggestions:z93.array(z93.string())}))}});import{z as z94}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","org_agent_registry_reference","source_registered_domain"],ProjectTransferBlockerCodeSchema=z94.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z94.object({code:ProjectTransferBlockerCodeSchema,message:z94.string(),count:z94.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z94.object({targetOrganizationId:z94.string().min(1)}),ProjectTransferResultDTO=createDTO(z94.object({projectId:z94.string(),sourceOrganizationId:z94.string(),targetOrganizationId:z94.string(),movedThreads:z94.number().int().nonnegative(),revokedInvites:z94.number().int().nonnegative(),revokedGrants:z94.number().int().nonnegative(),preservedGrants:z94.number().int().nonnegative(),warnings:z94.array(z94.string())}))}});import{z as z95}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z95.object({translated:z95.number().int().nonnegative(),total:z95.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z95.object({locale:z95.string(),isDefault:z95.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z95.object({defaultLocale:z95.string(),locales:z95.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z95.object({locale:z95.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z95.object({locale:z95.string().min(1).max(40)}),ProjectLocaleMutationSchema=z95.object({locale:z95.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z95.object({locale:z95.string(),entriesDeleted:z95.number().int().nonnegative(),labelsDeleted:z95.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z96}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z96.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z96.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z96.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z96.number(),credits:z96.number().optional(),billingMode:z96.enum(["fimo-credits","provider-account"]).optional(),confidence:z96.enum(["exact","estimated","metered"]),basis:z96.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z97}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z97.object({options:z97.record(z97.string(),z97.unknown()),name:z97.string().optional(),parentId:z97.string().nullable().optional(),altText:z97.string().optional(),caption:z97.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z97.string().min(1).optional(),model:z97.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z97.object({jobId:z97.string(),status:z97.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z97.string().nullable().optional(),credits:z97.number().optional(),costUsd:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z97.object({error:z97.string(),code:z97.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z97.array(GenerationTaskIdSchema).optional(),availableModels:z97.array(z97.string()).optional(),issues:z97.array(z97.unknown()).optional()})}});import{z as z98}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z98.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z98.object({name:z98.string(),key:z98.string(),description:z98.string(),type:FlagTypeSchema,required:z98.boolean(),defaultValue:z98.unknown().optional(),enumValues:z98.array(z98.string()).optional(),isArray:z98.boolean()}),AssetModelPriceSchema=z98.object({unitPrice:z98.number(),unit:z98.string(),confidence:z98.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z98.object({id:z98.string(),shortName:z98.string(),provider:z98.string(),source:z98.string(),modality:z98.enum(["image","video","audio"]),tags:z98.array(z98.string()),displayName:z98.string(),description:z98.string(),flags:z98.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z98.object({model:z98.string(),costUsd:z98.number(),credits:z98.number(),billingMode:z98.enum(["fimo-credits","provider-account"]),confidence:z98.enum(["exact","estimated","metered"]),basis:z98.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z99}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z99.object({tourId:z99.string(),version:z99.string(),status:z99.string(),completedAt:z99.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z99.array(UserTourDTOSchema))}});import{z as z100}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=z100.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z100.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z100.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z100.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z100.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z100.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z100.enum(["user","agent","system"]),SupportReportTagSchema=z100.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z100.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z100.object({organization:z100.object({id:z100.string().trim().min(1).max(255),name:z100.string().trim().max(240).optional()}),project:z100.object({id:z100.uuid(),name:z100.string().trim().max(240).optional(),createdAt:z100.coerce.date().optional()}).optional(),environment:z100.string().trim().max(255).optional(),clientVersion:z100.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z100.object({message:z100.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z100.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z100.string().trim().max(200).optional(),limit:z100.coerce.number().int().min(1).max(100).default(50),offset:z100.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z100.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z100.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z100.uuid().nullable().optional(),note:z100.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=z100.object({message:z100.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z100.object({kind:SupportReportLinkKindSchema,label:z100.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z100.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z100.object({kind:SupportReportActorKindSchema,id:z100.string().nullable(),name:z100.string().nullable()}),SupportReportLinkDTOSchema=z100.object({id:z100.uuid(),kind:SupportReportLinkKindSchema,label:z100.string(),url:SupportReportHttpUrlSchema,externalId:z100.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z100.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z100.object({id:z100.uuid(),kind:SupportReportEventKindSchema,body:z100.string().nullable(),metadata:z100.record(z100.string(),z100.unknown()),actor:SupportReportActorDTOSchema,createdAt:z100.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z100.object({id:z100.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z100.array(z100.string()),source:SupportReportSourceSchema,message:z100.string(),reporter:z100.object({id:z100.string().nullable(),name:z100.string().nullable(),email:z100.string().nullable()}),organization:z100.object({id:z100.string().nullable(),name:z100.string()}),project:z100.object({id:z100.uuid().nullable(),name:z100.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z100.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z100.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z100.string().nullable(),deliveredAt:z100.coerce.date().nullable()}).nullable(),duplicateOfReportId:z100.uuid().nullable(),resolvedAt:z100.coerce.date().nullable(),createdAt:z100.coerce.date(),updatedAt:z100.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z100.string().nullable(),clientVersion:z100.string().nullable(),links:z100.array(SupportReportLinkDTOSchema),events:z100.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z100.object({reports:z100.array(SupportReportSummaryDTOSchema),total:z100.number().int().nonnegative(),statusCounts:z100.object({new:z100.number().int().nonnegative(),in_progress:z100.number().int().nonnegative(),waiting:z100.number().int().nonnegative(),resolved:z100.number().int().nonnegative(),duplicate:z100.number().int().nonnegative(),irrelevant:z100.number().int().nonnegative(),ignored:z100.number().int().nonnegative()}),limit:z100.number().int().positive(),offset:z100.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z100.object({id:z100.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z100.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z101}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=z101.iso.datetime({offset:!0}).pipe(z101.coerce.date()),OpsRecentChatInputSchema=z101.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z101.string().trim().min(1).max(255).optional(),limit:z101.coerce.number().int().min(1).max(200).default(100),cursor:z101.string().trim().min(1).max(2e3).optional(),slim:z101.boolean().default(!0),reason:z101.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=z101.object({id:z101.string(),threadId:z101.string(),providerMessageId:z101.string().nullable(),invocationId:z101.string().nullable(),env:z101.string().nullable(),role:z101.string(),parts:z101.array(z101.record(z101.string(),z101.unknown())),metadata:z101.object({status:z101.string().optional(),traceUrl:z101.string().optional(),externalFileChanges:z101.array(z101.unknown()).optional()}),stats:z101.object({toolCount:z101.number().int().nonnegative(),failedToolCount:z101.number().int().nonnegative()}),createdAt:z101.iso.datetime({offset:!0}),project:z101.object({id:z101.string(),name:z101.string(),displayName:z101.string().nullable(),organizationId:z101.string().nullable()})}),OpsRecentChatResponseSchema=z101.object({target:z101.object({backendProfile:OpsBackendProfileSchema,projectEnv:z101.string().nullable()}),window:z101.object({from:z101.iso.datetime({offset:!0}),to:z101.iso.datetime({offset:!0})}),messages:z101.object({items:z101.array(OpsRecentChatMessageSchema),nextCursor:z101.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z102}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=z102.object({backendProfile:OpsBackendProfileSchema,provider:z102.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z102.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z102.object({backendProfile:OpsBackendProfileSchema,provider:z102.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z102.literal(!1),reason:z102.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z103}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=z103.object({packageManager:z103.string().trim().min(1).max(200).nullable(),trackedLockfiles:z103.array(z103.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z103.string().trim().min(1)}),OpsProjectPackageManagerSchema=z103.object({target:z103.object({backendProfile:OpsBackendProfileSchema,projectId:z103.uuid(),projectEnv:z103.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z104}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchRecoveredOwnerSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z104.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchRecoveredOwnerSchema=z104.object({branch:BranchSchema,sessionId:z104.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z104.object({branches:OpsAgentBranchAllowlistSchema,reason:z104.string().trim().min(1).max(1e3),recoveredOwners:z104.array(OpsAgentBranchRecoveredOwnerSchema).max(OPS_AGENT_BRANCH_DISCARD_LIMIT).optional()}).refine(input=>(input.recoveredOwners??[]).every(owner=>input.branches.includes(owner.branch)),{error:"every recovered owner must name a Branch from the allowlist",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.branch)).size===owners.length},{error:"recovered owners must not repeat a Branch",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.sessionId)).size===owners.length},{error:"recovered owners must not repeat a session",path:["recoveredOwners"]}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.safeExtend({planHash:z104.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants","recovery_direct_owner_present","recovery_session_not_found","recovery_session_not_project_agent_run","recovery_session_not_terminal","recovery_session_already_bound"],OpsAgentBranchDiscardBlockerSchema=z104.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z105}from"zod";function createAgentRunWebhookEventDataSchema(status){return z105.object({run:z105.object({id:z105.string(),agentName:z105.string(),trigger:z105.string(),status:z105.literal(status),startedAt:z105.string().nullable(),finishedAt:z105.string().nullable(),reason:z105.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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_common2();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","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z105.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z105.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z105.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z105.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z105.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z105.object({reason:WebhookEntryChangeReasonSchema,operationId:z105.string().optional(),batch:z105.object({index:z105.number().int().positive(),total:z105.number().int().positive()}).optional(),changes:z105.array(z105.object({action:WebhookEntryChangeActionSchema,contentType:z105.string(),id:z105.string(),documentId:z105.string(),locale:z105.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z105.object({form:z105.object({id:z105.string(),label:z105.string()}),submission:z105.object({id:z105.string(),data:z105.record(z105.string(),z105.unknown()),submittedAt:z105.string()})}),PublishStartedWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("publishing"),startedAt:z105.string()})}),PublishSucceededWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("published"),url:z105.string(),publishedAt:z105.string(),firstPublish:z105.boolean()})}),PublishFailedWebhookEventDataSchema=z105.object({publication:z105.object({status:z105.literal("failed"),reason:z105.string()})}),PublishUnpublishedWebhookEventDataSchema=z105.object({publication:z105.object({previousUrl:z105.string(),unpublishedAt:z105.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z105.object({review:z105.object({id:z105.string(),runId:z105.string(),agentName:z105.string(),classification:z105.string(),summary:z105.string(),reasons:z105.array(z105.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z105.object({review:z105.object({id:z105.string(),runId:z105.string(),agentName:z105.string(),resolution:z105.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z105.object({report:z105.object({weekStart:z105.string(),weekEnd:z105.string(),pageviews:z105.number(),visitors:z105.number(),previousPageviews:z105.number(),previousVisitors:z105.number()})}),MediaAssetWebhookEventDataSchema=z105.object({id:z105.string().nullable(),name:z105.string().nullable(),type:z105.string(),mimeType:z105.string().nullable(),fileSize:z105.number().nullable()}),MediaUploadedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("updated")}),MediaDeletedWebhookEventDataSchema=z105.object({asset:MediaAssetWebhookEventDataSchema,operation:z105.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z105.object({domain:z105.object({id:z105.string(),hostname:z105.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z105.object({domain:z105.object({id:z105.string(),hostname:z105.string()})}),LabelChangedWebhookEventDataSchema=z105.object({changes:z105.array(z105.object({action:z105.enum(["created","updated","deleted"]),key:z105.string(),locale:z105.string(),value:z105.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),isDefault:z105.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),previousCode:z105.string()})}),LocaleDeletedWebhookEventDataSchema=z105.object({locale:z105.object({code:z105.string(),entriesDeleted:z105.number().int().nonnegative(),labelsDeleted:z105.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z105.object({environment:z105.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z105.object({environment:z105.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z105.object({merge:z105.object({id:z105.string(),from:BranchSchema,to:BranchSchema,applied:z105.array(z105.object({surface:SurfaceNameSchema,count:z105.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z105.object({branch:z105.object({name:BranchSchema}),version:z105.object({versionId:z105.uuid(),name:z105.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,"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,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z105.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z105.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z105.discriminatedUnion("source",[z105.object({source:z105.literal("literal"),value:z105.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z105.object({source:z105.literal("secret"),key:z105.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z105.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z105.object({name:z105.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z105.object({name:z105.string(),source:z105.enum(["literal","secret"]),secretKey:z105.string().nullable(),secretPrefix:z105.string().nullable(),configured:z105.literal(!0)}),WebhookFilterSchema=z105.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z105.string().min(1).max(255).optional(),agentName:z105.string().min(1).max(120).optional(),mediaType:z105.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z105.string().min(1).max(255).optional(),locale:z105.string().min(1).max(120).optional()}),JsonValueSchema=z105.lazy(()=>z105.union([z105.string(),z105.number(),z105.boolean(),z105.null(),z105.array(JsonValueSchema),z105.record(z105.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z105.object({name:z105.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z105.url(),enabled:z105.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z105.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z105.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z105.object({name:z105.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z105.url().optional(),enabled:z105.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z105.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z105.boolean().optional()}),TestProjectWebhookRequestSchema=z105.object({eventType:WebhookEventTypeSchema.optional(),data:z105.record(z105.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z105.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z105.uuid(),name:z105.string(),eventType:WebhookEventTypeSchema,enabled:z105.boolean(),destination:z105.object({host:z105.string(),maskedUrl:z105.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z105.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z105.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z105.coerce.date().nullable(),deliveryStats24h:z105.object({succeeded:z105.number().int().nonnegative(),failed:z105.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z105.uuid(),projectId:z105.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z105.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z105.number().int().positive(),test:z105.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z105.number().int().nonnegative(),responseStatus:z105.number().int().nullable(),lastErrorCode:z105.string().nullable(),lastErrorMessage:z105.string().nullable(),payloadAvailable:z105.boolean(),destination:z105.object({host:z105.string(),maskedUrl:z105.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z105.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z105.string().nullable(),qstashMessageId:z105.string().nullable(),deliveredAt:z105.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z105.object({items:z105.array(WebhookDeliveryDTOSchema),pagination:z105.object({page:z105.number().int().positive(),limit:z105.number().int().positive(),total:z105.number().int().nonnegative(),totalPages:z105.number().int().positive(),hasMore:z105.boolean()}),stats:z105.object({total:z105.number().int().nonnegative(),succeeded:z105.number().int().nonnegative(),failed:z105.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z105.object({id:z105.uuid(),deliveryId:z105.uuid(),attempt:z105.number().int().positive(),status:z105.enum(["delivering","succeeded","failed"]),responseStatus:z105.number().int().nullable(),durationMs:z105.number().int().nonnegative(),responseExcerpt:z105.string().nullable(),errorCode:z105.string().nullable(),errorMessage:z105.string().nullable(),createdAt:z105.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z105.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z105.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z106}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=z106.object({key:z106.literal("fimo-2"),enabled:z106.boolean(),dismissed:z106.boolean().default(!1),interacted:z106.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z107}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_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z107.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z107.object({total:z107.number(),base:z107.number(),purchases:z107.number(),awards:z107.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z107.object({id:z107.string(),name:z107.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z107.object({type:z107.string(),brand:z107.string().nullable(),last4:z107.string().nullable(),expirationDate:z107.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z107.object({currency:z107.string(),nextPaymentAmount:z107.number().nullable(),nextPaymentAt:z107.string().nullable(),billingInterval:z107.string().nullable(),totalAmount:z107.number().nullable(),discountAmount:z107.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z107.object({id:z107.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z107.string().nullable(),currentPeriodEndsAt:z107.string().nullable(),renewsAt:z107.string().nullable(),cancelAt:z107.string().nullable(),renewAutomatically:z107.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z107.object({type:z107.enum(["low_balance","critical_balance","approaching_limit"]),message:z107.string(),estimatedPromptsRemaining:z107.number().nullable(),avgCostPerPrompt:z107.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z107.object({monthlyCredits:z107.number().nullable(),usedThisPeriod:z107.number(),remainingThisPeriod:z107.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z107.object({organizationId:z107.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z107.string().nullable(),tenureDays:z107.number().int().nonnegative(),capturedAt:z107.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z107.object({hasSubscription:z107.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z107.number().nullable(),alerts:z107.array(CreditAlertDTOSchema),portalUrl:z107.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z107.object({creditCount:z107.number().int().positive(),expiresAt:z107.string().datetime().nullable().optional(),message:z107.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z107.literal("free"),amountCents:z107.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z107.literal("purchase"),amountCents:z107.number().int().positive()}),CreditTopupRequestDTOSchema=z107.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z107.object({success:z107.boolean(),transactionId:z107.string().nullable(),newBalance:z107.number(),creditCount:z107.number(),type:z107.enum(["free","purchase"]),invoiceId:z107.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z108}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=z108.object({totalCredits:z108.number(),totalCostUsd:z108.number(),totalMessages:z108.number(),avgCostPerMessage:z108.number(),periodStart:z108.string().nullable(),periodEnd:z108.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z108.object({projectId:z108.string(),projectName:z108.string(),projectDisplayName:z108.string().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z108.object({userId:z108.string(),userName:z108.string().nullable(),userEmail:z108.string().email().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z108.object({date:z108.string(),credits:z108.number(),costUsd:z108.number(),messages:z108.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z108.object({userId:z108.string(),userName:z108.string().nullable(),userEmail:z108.string().email().nullable(),credits:z108.number(),costUsd:z108.number(),messages:z108.number(),percentage:z108.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z108.object({projectId:z108.string(),projectName:z108.string(),projectDisplayName:z108.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z108.array(UsageByUserForProjectDTOSchema),timeline:z108.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z108.object({summary:UsageSummaryDTOSchema,byProject:z108.array(UsageByProjectDTOSchema),byUser:z108.array(UsageByUserDTOSchema),timeline:z108.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z109}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=z109.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z109.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z109.object({startDate:z109.string().optional(),endDate:z109.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z109.coerce.number().int().positive().default(1),limit:z109.coerce.number().int().positive().max(100).default(20),sortBy:z109.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z109.string().optional(),activeOnly:z109.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),avgCreditsPerMessage:z109.number(),periodStart:z109.string(),periodEnd:z109.string(),creditsChange:z109.number().nullable(),costChange:z109.number().nullable(),messagesChange:z109.number().nullable(),unattributedCredits:z109.number(),unattributedCostUsd:z109.number(),unattributedMessages:z109.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z109.object({organizationId:z109.string(),organizationName:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),userCount:z109.number(),projectCount:z109.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().nullable(),userImage:z109.string().nullable(),organizationId:z109.string().nullable(),organizationName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),projectCount:z109.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),organizationId:z109.string(),organizationName:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number(),userCount:z109.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z109.object({id:z109.string(),name:z109.string(),value:z109.number(),percentage:z109.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z109.object({day:z109.number(),hour:z109.number(),value:z109.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z109.object({summary:UsageOverviewSummaryDTOSchema,timeline:z109.array(UsageTimelinePointDTOSchema),topOrganizations:z109.array(OrganizationUsageRowDTOSchema),topUsers:z109.array(UserUsageRowDTOSchema),topProjects:z109.array(ProjectUsageRowDTOSchema),creditDistribution:z109.array(UsageDistributionItemDTOSchema),userDistribution:z109.array(UsageDistributionItemDTOSchema),heatmap:z109.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z109.object({page:z109.number(),limit:z109.number(),totalItems:z109.number(),totalPages:z109.number(),hasMore:z109.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z109.object({organizations:z109.array(OrganizationUsageRowDTOSchema),top:z109.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z109.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z109.object({users:z109.array(ExtendedUserUsageRowDTOSchema),top:z109.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z109.string(),ownerName:z109.string().nullable(),ownerEmail:z109.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z109.object({projects:z109.array(ExtendedProjectUsageRowDTOSchema),top:z109.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z109.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z109.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z109.object({credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z109.object({id:z109.string(),name:z109.string(),createdAt:z109.string(),memberCount:z109.number(),projectCount:z109.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z109.object({id:z109.string(),name:z109.string().nullable(),email:z109.string(),image:z109.string().nullable(),createdAt:z109.string(),organizationCount:z109.number(),projectCount:z109.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z109.object({id:z109.string(),name:z109.string(),displayName:z109.string().nullable(),createdAt:z109.string(),organizationId:z109.string(),organizationName:z109.string(),ownerId:z109.string(),ownerName:z109.string().nullable(),ownerEmail:z109.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z109.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z110}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=z110.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z110.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z110.object({command:z110.string().min(1).max(1e4),cwd:z110.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z110.record(z110.string(),z110.string()).optional(),name:z110.string().optional(),waitForCompletion:z110.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=z110.object({identifier:z110.string(),status:SandboxProcessStatusSchema,command:z110.string().optional(),startedAt:z110.string().optional(),exitCode:z110.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z110.object({processes:z110.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z110.object({processId:z110.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z110.object({success:z110.boolean(),message:z110.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z111}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();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_files();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_control_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_notification_preference_catalog_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch:null}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment();if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
209
209
  `)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only Branch '${ctx.branch}'. Switch off the release/* tag or pass --branch <writable-branch>.`);return{ctx,fimo:createCliFimoClient(cfg,ctx.branch)}}var NotInProjectError,InvalidBranchOverrideError,BranchNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_config();init_sdk_transport();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidBranchOverrideError=class extends Error{static{__name(this,"InvalidBranchOverrideError")}value;constructor(value){super(`--branch value '${value}' is invalid. Branch names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidBranchOverrideError",this.value=value}},BranchNotFoundError=class extends Error{static{__name(this,"BranchNotFoundError")}branch;knownBranches;constructor(branch,knownBranches){super(`Branch '${branch}' not found on the server. Known Branches: ${knownBranches.length>0?knownBranches.join(", "):"(none yet)"}.`),this.name="BranchNotFoundError",this.branch=branch,this.knownBranches=knownBranches}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("Fimo could not detect a current Git Branch. Check out a Branch or pass --branch <name>."),this.name="GitBranchUndetectedError"}};__name(resolveBranchFromGit,"resolveBranchFromGit");__name(resolveBranchFromEnvironment,"resolveBranchFromEnvironment");__name(getProjectContext,"getProjectContext");__name(branchSourceBanner,"branchSourceBanner");__name(branchOverrideFromCommand,"branchOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var isAmbiguous,isFullWidth,isWide,init_utils=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/utils.js"(){isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide")}});var ANSI_RE,CONTROL_RE,TAB_RE,EMOJI_RE,LATIN_RE,MODIFIER_RE,NO_TRUNCATION,getStringTruncatedWidth,dist_default,init_dist3=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/index.js"(){init_utils();ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index2=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index2>=length&&index2>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index2);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index2>=length)break;if(LATIN_RE.lastIndex=index2,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index2,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index2,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index2,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index2,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index2,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index2,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index2,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=EMOJI_RE.lastIndex;continue}index2+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth}});var NO_TRUNCATION2,fastStringWidth,dist_default2,init_dist4=__esm({"../../node_modules/.pnpm/fast-string-width@1.1.0/node_modules/fast-string-width/dist/index.js"(){init_dist3();NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth}});function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
210
210
  `)}var ESC,CSI,END_CODE,ANSI_ESCAPE_BELL,ANSI_CSI,ANSI_OSC,ANSI_SGR_TERMINATOR,ANSI_ESCAPE_LINK,GROUP_REGEX,getClosingCode,wrapAnsiCode,wrapAnsiHyperlink,wrapWord,stringVisibleTrimSpacesRight,exec,CRLF_OR_LF,init_main=__esm({"../../node_modules/.pnpm/fast-wrap-ansi@0.1.6/node_modules/fast-wrap-ansi/lib/main.js"(){init_dist4();ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last2=words.length;for(;last2&&!dist_default2(words[last2-1]);)last2--;return last2===words.length?string:words.slice(0,last2).join(" ")+words.slice(last2).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index2=0;index2<words.length;index2++){let word=words[index2];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index2!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
211
211
  `),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
@@ -1187,11 +1187,11 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1187
1187
  ${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
1188
1188
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path53=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path53,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch),git=createGitService(loadConfig(),ctx.branch),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(git,ctx.projectId,ctx.branch,cwd),serverPromise=withSoftTimeout(fimo.execute("branches.status",{projectId:ctx.projectId,branch:ctx.branch,against:options.vs,surfaces:surfaces?.map(surface=>surface==="translations"?"labels":surface)}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let portableServer=serverResult.value,server={branch:portableServer.branch,env:portableServer.branch,vs:portableServer.against,syncState:portableServer.syncState??(portableServer.state==="clean"?"in-sync":"diverged"),generatedAt:portableServer.generatedAt,surfaces:portableServer.surfaces.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),crossSurface:portableServer.crossSurface?.map(finding=>({...finding,source:{...finding.source,surface:finding.source.surface==="labels"?"translations":finding.source.surface},target:{...finding.target,surface:finding.target.surface==="labels"?"translations":finding.target.surface}}))},serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
1189
1189
 
1190
- ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs50 from"node:fs";import path52 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash}from"node:crypto";import{promises}from"node:fs";import path from"node:path";import{z}from"zod";var CapabilityTokenSchema=z.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z.array(CapabilityTokenSchema);import{z as z2}from"zod";var CronTriggerSchema=z2.object({type:z2.literal("schedule"),cron:z2.string().min(1,"cron expression required"),tz:z2.string().optional()}),ManualTriggerSchema=z2.object({type:z2.literal("manual")}),WebhookTriggerSchema=z2.object({type:z2.literal("webhook"),path:z2.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z2.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z2.object({name:z2.string().min(1),capability_grant:z2.enum(["inherit","explicit"]).optional(),explicit_grants:z2.array(z2.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z2.object({"sub-agents":z2.array(SubAgentRefSchema)}),RuntimeConfigSchema=z2.object({cloud:z2.boolean().optional(),dev:z2.boolean().optional(),long_running:z2.boolean().optional(),max_credits:z2.number().int().min(1).optional(),max_steps:z2.number().int().min(1).optional()}),DataSourceSchema=z2.enum(["main","prod"]),ConfigValueKeySchema=z2.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z2.preprocess(value=>typeof value=="string"?{key:value}:value,z2.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z2.boolean().default(!0),delivery:z2.literal("process_env").default("process_env")})),IntegrationKeySchema=z2.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z2.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z2.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z2.object({enabled:z2.boolean().default(!0),tools:z2.record(IntegrationToolKeySchema,z2.boolean()).optional()})),IntegrationPolicySchema=z2.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z2.object({version:z2.literal(1),description:z2.string().min(1).max(280).optional(),model:z2.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z2.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z2.array(DataSourceSchema).optional(),secrets:z2.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path.relative(dir,path.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path.basename(bundlePath),goalPath=path.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path.join(bundlePath,"SOUL.md")),capsPath=path.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path.join(bundlePath,"scripts")),listDir(path.join(bundlePath,"references")),listDir(path.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path.join(agentsDir,entry.name);if(await fileExists(path.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var AGENT_MODEL_IDS=["google/gemini-2.5-flash-lite","google/gemini-3.5-flash-lite","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-2.5-flash","google/gemini-3-flash","anthropic/claude-haiku-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5","anthropic/claude-opus-5","anthropic/claude-fable-5","google/gemini-3.1-flash-image-preview","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3","zai/glm-5.2","zai/glm-5.3-flash","relace-search"],DEFAULT_AGENT_MODEL_ID="openai/gpt-5.6-luna";function isSupportedAgentModel(model){return AGENT_MODEL_IDS.includes(model)}__name(isSupportedAgentModel,"isSupportedAgentModel");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let model=bundle.config.model;model!==void 0&&!isSupportedAgentModel(model)&&issues.push({pointer:"config.yaml:model",message:`unsupported model '${model}'; omit the field to use ${DEFAULT_AGENT_MODEL_ID}, or pick one of: ${AGENT_MODEL_IDS.join(", ")}`,severity:"error"});let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z3}from"zod";var SurfaceGuardPolicySchema=z3.enum(["block","warn","allow"]),ClassificationSchema=z3.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z3.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z3.object({enabled:z3.boolean(),allowed_skills:z3.array(z3.string().min(1)).default([]),allowed_classifications:z3.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z3.enum(["off","daily","weekly"]),NotificationFormatSchema=z3.object({markdown:z3.boolean().default(!0),html:z3.boolean().default(!1)}),NotificationsPolicySchema=z3.object({email_recipients:z3.array(z3.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z3.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z3.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z4}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z4.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z4.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
1190
+ ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs50 from"node:fs";import path52 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash}from"node:crypto";import{promises}from"node:fs";import path from"node:path";import{z}from"zod";var CapabilityTokenSchema=z.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z.array(CapabilityTokenSchema);import{z as z2}from"zod";var CronTriggerSchema=z2.object({type:z2.literal("schedule"),cron:z2.string().min(1,"cron expression required"),tz:z2.string().optional()}),ManualTriggerSchema=z2.object({type:z2.literal("manual")}),WebhookTriggerSchema=z2.object({type:z2.literal("webhook"),path:z2.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z2.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z2.object({name:z2.string().min(1),capability_grant:z2.enum(["inherit","explicit"]).optional(),explicit_grants:z2.array(z2.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z2.object({"sub-agents":z2.array(SubAgentRefSchema)}),RuntimeConfigSchema=z2.object({cloud:z2.boolean().optional(),dev:z2.boolean().optional(),long_running:z2.boolean().optional(),max_credits:z2.number().int().min(1).optional(),max_steps:z2.number().int().min(1).optional()}),DataSourceSchema=z2.enum(["main","prod"]),ConfigValueKeySchema=z2.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z2.preprocess(value=>typeof value=="string"?{key:value}:value,z2.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z2.boolean().default(!0),delivery:z2.literal("process_env").default("process_env")})),IntegrationKeySchema=z2.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z2.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z2.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z2.object({enabled:z2.boolean().default(!0),tools:z2.record(IntegrationToolKeySchema,z2.boolean()).optional()})),IntegrationPolicySchema=z2.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z2.object({version:z2.literal(1),description:z2.string().min(1).max(280).optional(),model:z2.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z2.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z2.array(DataSourceSchema).optional(),secrets:z2.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path.relative(dir,path.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path.basename(bundlePath),goalPath=path.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path.join(bundlePath,"SOUL.md")),capsPath=path.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path.join(bundlePath,"scripts")),listDir(path.join(bundlePath,"references")),listDir(path.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path.join(agentsDir,entry.name);if(await fileExists(path.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var AGENT_MODEL_IDS=["google/gemini-2.5-flash-lite","google/gemini-3.5-flash-lite","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-2.5-flash","google/gemini-3-flash","google/gemini-3.1-pro-preview","anthropic/claude-haiku-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.7","anthropic/claude-sonnet-5","anthropic/claude-opus-5","anthropic/claude-fable-5","google/gemini-3.1-flash-image-preview","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3","zai/glm-5.2","zai/glm-5.3-flash","relace-search"],DEFAULT_AGENT_MODEL_ID="openai/gpt-5.6-luna";function isSupportedAgentModel(model){return AGENT_MODEL_IDS.includes(model)}__name(isSupportedAgentModel,"isSupportedAgentModel");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let model=bundle.config.model;model!==void 0&&!isSupportedAgentModel(model)&&issues.push({pointer:"config.yaml:model",message:`unsupported model '${model}'; omit the field to use ${DEFAULT_AGENT_MODEL_ID}, or pick one of: ${AGENT_MODEL_IDS.join(", ")}`,severity:"error"});let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z3}from"zod";var SurfaceGuardPolicySchema=z3.enum(["block","warn","allow"]),ClassificationSchema=z3.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z3.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z3.object({enabled:z3.boolean(),allowed_skills:z3.array(z3.string().min(1)).default([]),allowed_classifications:z3.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z3.enum(["off","daily","weekly"]),NotificationFormatSchema=z3.object({markdown:z3.boolean().default(!0),html:z3.boolean().default(!1)}),NotificationsPolicySchema=z3.object({email_recipients:z3.array(z3.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z3.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z3.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z4}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z4.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z4.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
1191
1191
  ${line}`):next2=(content2.endsWith(`
1192
1192
  `)?content2:content2+`
1193
1193
  `)+line+`
1194
- `,fs9.writeFileSync(configPath,next2)}__name(writeDescriptionToConfig,"writeDescriptionToConfig");async function createAgentCommand(name,options){try{let result=await createAgent({name,template:options.template,cwd:options.cwd,description:options.description,requireFimoProject:options.cwd===void 0});if(!result.ok){ui.error({command:"agents create",code:"AGENT_CREATE_FAILED",message:result.error??"Failed to scaffold agent."});return}let rel=path9.relative(process.cwd(),result.agentDir);ui.ok({command:"agents create",headline:`Created agent at ${rel}`,details:{agent:name,agent_dir:result.agentDir,relative_dir:rel},hint:"Next: `fimo agents validate "+name+"` then push to main to wire its triggers."})}catch(err){err instanceof InvalidAgentNameError?ui.error({command:"agents create",code:"INVALID_AGENT_NAME",message:err.message}):printBundleError("agents create",err)}}__name(createAgentCommand,"createAgentCommand");import path10 from"node:path";init_dist();init_config();init_config();init_sdk_transport();function createIntegrationService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg),projectPath3=__name((projectId,integrationKey)=>`/api/management/projects/${projectId}/integrations${integrationKey?`/${encodeURIComponent(integrationKey)}`:""}`,"projectPath");return{async list(projectId){return(await transport.request(projectPath3(projectId))).data},async addMcp(input){return(await transport.request(projectPath3(input.projectId),{method:"POST",body:JSON.stringify(input.request)})).data},async getInfo(projectId,integrationKey){return(await transport.request(`${projectPath3(projectId,integrationKey)}/info`)).data},async getStatus(projectId,integrationKey){return(await transport.request(`${projectPath3(projectId,integrationKey)}/status`)).data},async connect(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).data},async enable(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await transport.request(projectPath3(input.projectId,input.integrationKey),{method:"PUT",body:JSON.stringify(payload)})).data},async connectOrganizationWithToken(input){return(await transport.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 startOrganizationConnect(input){return(await transport.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data},async switchAuth(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data},async disable(projectId,integrationKey){await transport.request(projectPath3(projectId,integrationKey),{method:"DELETE"})},async setCredential(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data},async clearCredential(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data},async runTool(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data},async bindChannel(projectId,request){return(await transport.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}}}__name(createIntegrationService,"createIntegrationService");function createModelCatalogService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async list(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let tag of query.tag??[])params.append("tag",tag);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let search=params.toString();return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models${search?`?${search}`:""}`)).data},async get(projectId,key){try{return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(error){if(error instanceof ApiRequestError&&error.status===404)return null;throw error}}}}__name(createModelCatalogService,"createModelCatalogService");async function agentIntegrationsCommand(name,opts){try{let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),bundle=await parseBundle(path10.join(resolveAgentBundlesDir(projectRoot),name)),policy=agentIntegrationPolicy(bundle.config),projectStatus=await loadProjectIntegrationStatus(opts,projectRoot),statusByKey=new Map(projectStatus.map(status=>[status.integrationKey,status])),keys=new Set([...Object.keys(policy),...projectStatus.map(status=>status.integrationKey)]);if(keys.size===0){ui.info({command:"agents integrations",message:`Agent '${name}' has no explicit integration policy and no project integrations were found.`});return}ui.table({command:"agents integrations",columns:[{key:"integration",label:"INTEGRATION"},{key:"project",label:"PROJECT"},{key:"agent",label:"AGENT"},{key:"tools",label:"TOOLS"}],rows:[...keys].sort().map(integrationKey=>{let entry=policy[integrationKey],status=statusByKey.get(integrationKey);return{integration:integrationKey,project:renderProjectStatus(status),agent:renderAgentPolicy(entry),tools:renderTools(entry)}})})}catch(err){printBundleError("agents integrations",err)}}__name(agentIntegrationsCommand,"agentIntegrationsCommand");async function loadProjectIntegrationStatus(opts,projectRoot){let projectId=opts.project??resolveFimoProject(projectRoot)?.settings.projectId;if(!projectId)return[];try{return await createIntegrationService(loadConfig()).list(projectId)}catch{return[]}}__name(loadProjectIntegrationStatus,"loadProjectIntegrationStatus");function renderProjectStatus(status){return status?status.enabled?`enabled (${status.authModeLabel??status.authMode??"auth unknown"})`:status.installed?"disabled":"available":"unknown"}__name(renderProjectStatus,"renderProjectStatus");function renderAgentPolicy(entry){return entry&&entry.enabled?"enabled":"disabled"}__name(renderAgentPolicy,"renderAgentPolicy");function renderTools(entry){if(!entry?.enabled)return"no tools";if(entry.tools===void 0)return"all available tools";if(enabledAgentIntegrationTools(entry).length===0)return"no tools";let tools=entry?.tools??{};return Object.entries(tools).sort(([a],[b])=>a.localeCompare(b)).map(([tool,enabled])=>`${tool}:${enabled?"on":"off"}`).join(", ")}__name(renderTools,"renderTools");init_dist();async function listAgents(opts={}){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd());return(await listBundles(resolveAgentBundlesDir(projectRoot))).map(b=>({name:b.name,declared:!0,triggers:(b.config.triggers??[]).map(t2=>t2.type),capabilities:[...b.capabilities]}))}__name(listAgents,"listAgents");async function listAgentsCommand(opts={}){let agents;try{agents=await listAgents(opts)}catch(err){ui.error({command:"agents list",code:"AGENT_BUNDLE_LIST_FAILED",message:err.message});return}if(agents.length===0){ui.info({command:"agents list",message:"(no agents)",hint:"Run `fimo agents create <name>` to scaffold one."});return}ui.table({command:"agents list",columns:[{key:"name",label:"NAME"},{key:"triggers",label:"TRIGGERS"},{key:"capabilities",label:"CAPS"}],rows:agents.map(a=>({name:a.name,triggers:a.triggers.length===0?"\u2014":a.triggers.join(", "),capabilities:a.capabilities.length===0?"(read-only)":`${a.capabilities.length} caps`}))})}__name(listAgentsCommand,"listAgentsCommand");init_esm();init_dist();init_config();init_sdk_transport();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),fimo=createCliFimoClient(cfg),branch=options.branch,session;try{if(options.session){let response=await fimo.execute("agents.status",{projectId,sessionId:options.session});session={...response.data.session,env:response.data.session.branch}}else{let latest=(await fimo.execute("agents.runs",{projectId,agentName:name,branch,limit:1})).data[0];if(session=latest?{...latest,env:latest.branch}:void 0,!session){ui.info({command:"agents report",message:`(no runs for '${name}'${branch?` on Branch '${branch}'`:""})`});return}}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let shortId2=session.id.slice(0,8),document=normalizeReportDocument(session.reportDocument);if(!document){ui.result({command:"agents report",data:{agent:name,session_id:session.id,short_id:shortId2,status:session.status,terminal_reason:session.terminalReason??null,report_document:null},render:__name(()=>{let lines=[];return lines.push(`! No report for '${name}' \xB7 session ${shortId2} (${session.status}).`),session.terminalReason?lines.push(` reason: ${session.terminalReason}`):session.status!=="finished"&&lines.push(" The run has not finished yet \u2014 a report is written when it completes."),lines.join(`
1194
+ `,fs9.writeFileSync(configPath,next2)}__name(writeDescriptionToConfig,"writeDescriptionToConfig");async function createAgentCommand(name,options){try{let result=await createAgent({name,template:options.template,cwd:options.cwd,description:options.description,requireFimoProject:options.cwd===void 0});if(!result.ok){ui.error({command:"agents create",code:"AGENT_CREATE_FAILED",message:result.error??"Failed to scaffold agent."});return}let rel=path9.relative(process.cwd(),result.agentDir);ui.ok({command:"agents create",headline:`Created agent at ${rel}`,details:{agent:name,agent_dir:result.agentDir,relative_dir:rel},hint:"Next: `fimo agents validate "+name+"` then push to main to wire its triggers."})}catch(err){err instanceof InvalidAgentNameError?ui.error({command:"agents create",code:"INVALID_AGENT_NAME",message:err.message}):printBundleError("agents create",err)}}__name(createAgentCommand,"createAgentCommand");import path10 from"node:path";init_dist();init_config();init_config();init_sdk_transport();function createIntegrationService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg),projectPath3=__name((projectId,integrationKey)=>`/api/management/projects/${projectId}/integrations${integrationKey?`/${encodeURIComponent(integrationKey)}`:""}`,"projectPath");return{async list(projectId){return(await transport.request(projectPath3(projectId))).data},async addMcp(input){return(await transport.request(projectPath3(input.projectId),{method:"POST",body:JSON.stringify(input.request)})).data},async getInfo(projectId,integrationKey){return(await transport.request(`${projectPath3(projectId,integrationKey)}/info`)).data},async getStatus(projectId,integrationKey){return(await transport.request(`${projectPath3(projectId,integrationKey)}/status`)).data},async connect(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).data},async enable(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await transport.request(projectPath3(input.projectId,input.integrationKey),{method:"PUT",body:JSON.stringify(payload)})).data},async connectOrganizationWithToken(input){return(await transport.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 switchAuth(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data},async disable(projectId,integrationKey){await transport.request(projectPath3(projectId,integrationKey),{method:"DELETE"})},async setCredential(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data},async clearCredential(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data},async runTool(input){return(await transport.request(`${projectPath3(input.projectId,input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data},async bindChannel(projectId,request){return(await transport.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}}}__name(createIntegrationService,"createIntegrationService");function createModelCatalogService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async list(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let tag of query.tag??[])params.append("tag",tag);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let search=params.toString();return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models${search?`?${search}`:""}`)).data},async get(projectId,key){try{return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(error){if(error instanceof ApiRequestError&&error.status===404)return null;throw error}}}}__name(createModelCatalogService,"createModelCatalogService");async function agentIntegrationsCommand(name,opts){try{let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),bundle=await parseBundle(path10.join(resolveAgentBundlesDir(projectRoot),name)),policy=agentIntegrationPolicy(bundle.config),projectStatus=await loadProjectIntegrationStatus(opts,projectRoot),statusByKey=new Map(projectStatus.map(status=>[status.integrationKey,status])),keys=new Set([...Object.keys(policy),...projectStatus.map(status=>status.integrationKey)]);if(keys.size===0){ui.info({command:"agents integrations",message:`Agent '${name}' has no explicit integration policy and no project integrations were found.`});return}ui.table({command:"agents integrations",columns:[{key:"integration",label:"INTEGRATION"},{key:"project",label:"PROJECT"},{key:"agent",label:"AGENT"},{key:"tools",label:"TOOLS"}],rows:[...keys].sort().map(integrationKey=>{let entry=policy[integrationKey],status=statusByKey.get(integrationKey);return{integration:integrationKey,project:renderProjectStatus(status),agent:renderAgentPolicy(entry),tools:renderTools(entry)}})})}catch(err){printBundleError("agents integrations",err)}}__name(agentIntegrationsCommand,"agentIntegrationsCommand");async function loadProjectIntegrationStatus(opts,projectRoot){let projectId=opts.project??resolveFimoProject(projectRoot)?.settings.projectId;if(!projectId)return[];try{return await createIntegrationService(loadConfig()).list(projectId)}catch{return[]}}__name(loadProjectIntegrationStatus,"loadProjectIntegrationStatus");function renderProjectStatus(status){return status?status.enabled?`enabled (${status.authModeLabel??status.authMode??"auth unknown"})`:status.installed?"disabled":"available":"unknown"}__name(renderProjectStatus,"renderProjectStatus");function renderAgentPolicy(entry){return entry&&entry.enabled?"enabled":"disabled"}__name(renderAgentPolicy,"renderAgentPolicy");function renderTools(entry){if(!entry?.enabled)return"no tools";if(entry.tools===void 0)return"all available tools";if(enabledAgentIntegrationTools(entry).length===0)return"no tools";let tools=entry?.tools??{};return Object.entries(tools).sort(([a],[b])=>a.localeCompare(b)).map(([tool,enabled])=>`${tool}:${enabled?"on":"off"}`).join(", ")}__name(renderTools,"renderTools");init_dist();async function listAgents(opts={}){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd());return(await listBundles(resolveAgentBundlesDir(projectRoot))).map(b=>({name:b.name,declared:!0,triggers:(b.config.triggers??[]).map(t2=>t2.type),capabilities:[...b.capabilities]}))}__name(listAgents,"listAgents");async function listAgentsCommand(opts={}){let agents;try{agents=await listAgents(opts)}catch(err){ui.error({command:"agents list",code:"AGENT_BUNDLE_LIST_FAILED",message:err.message});return}if(agents.length===0){ui.info({command:"agents list",message:"(no agents)",hint:"Run `fimo agents create <name>` to scaffold one."});return}ui.table({command:"agents list",columns:[{key:"name",label:"NAME"},{key:"triggers",label:"TRIGGERS"},{key:"capabilities",label:"CAPS"}],rows:agents.map(a=>({name:a.name,triggers:a.triggers.length===0?"\u2014":a.triggers.join(", "),capabilities:a.capabilities.length===0?"(read-only)":`${a.capabilities.length} caps`}))})}__name(listAgentsCommand,"listAgentsCommand");init_esm();init_dist();init_config();init_sdk_transport();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),fimo=createCliFimoClient(cfg),branch=options.branch,session;try{if(options.session){let response=await fimo.execute("agents.status",{projectId,sessionId:options.session});session={...response.data.session,env:response.data.session.branch}}else{let latest=(await fimo.execute("agents.runs",{projectId,agentName:name,branch,limit:1})).data[0];if(session=latest?{...latest,env:latest.branch}:void 0,!session){ui.info({command:"agents report",message:`(no runs for '${name}'${branch?` on Branch '${branch}'`:""})`});return}}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let shortId2=session.id.slice(0,8),document=normalizeReportDocument(session.reportDocument);if(!document){ui.result({command:"agents report",data:{agent:name,session_id:session.id,short_id:shortId2,status:session.status,terminal_reason:session.terminalReason??null,report_document:null},render:__name(()=>{let lines=[];return lines.push(`! No report for '${name}' \xB7 session ${shortId2} (${session.status}).`),session.terminalReason?lines.push(` reason: ${session.terminalReason}`):session.status!=="finished"&&lines.push(" The run has not finished yet \u2014 a report is written when it completes."),lines.join(`
1195
1195
  `)},"render")});return}ui.result({command:"agents report",data:{agent:name,session_id:session.id,status:session.status,report_document:document},render:__name(()=>`${`Report \xB7 ${name} \xB7 session ${session.id} \xB7 ${session.status}`}
1196
1196
 
1197
1197
  ${renderDocument(document,{details:options.details===!0,agentName:name,sessionId:session.id})}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(agentReportCommand,"agentReportCommand");function renderDocument(document,target){if(target.details)return flattenReportDocument(document);let brief=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)].join(`
@@ -1209,7 +1209,6 @@ ${issues.join(`
1209
1209
  `)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index2=nextIndex;nextIndex+=1,results[index2]=await run(items[index2])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),params.limit=String(pagination.limit);let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let offset=parseCursorNumber(cursor,{defaultValue:0,minimum:0}),response=await content2.listAssets(ctx.projectId,{...params,offset:String(offset)});return toOffsetPaginationPage(response)},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}));ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item));return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}}),failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.read",{projectId:ctx.projectId,branch:ctx.branch,id,cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.createFolder",{projectId:ctx.projectId,branch:ctx.branch,name,parentId:options.parentId});ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.move",{projectId:ctx.projectId,branch:ctx.branch,id,parentId:options.parentId});ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.",scopeCount=__name(scope=>scope.referenceCount??scope.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope=>[scope.scope,scopeCount(scope)])),referenceCount=scopes.reduce((total,scope)=>total+scopeCount(scope),0),codeReferenceCount=scopes.reduce((total,scope)=>total+(scope.codeReferenceCount??0),0);return{status:scopes.some(scope=>scope.coverage!=="complete"||scope.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope=>[scope.scope,scope.coverage])),counts,referenceCount,codeReferenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(content2,projectId,id){let events=await content2.getAssetReferenceImpact(projectId,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(content2,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("assets.replaceReferences",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.with}),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await ot2({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the project? This cannot be undone.`:`Permanently destroy asset ${id} across the project? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement=await fimo.execute("assets.replaceAndDestroy",{projectId:ctx.projectId,branch:ctx.branch,id,replacementAssetId:options.replaceWith}),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await fimo.execute("assets.destroy",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let outcome=await fimo.execute("assets.replaceAndRemove",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.replaceWith}),receipt2={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!1,removal:{operationId:outcome.id,expiresAt:outcome.expiresAt,undoable:outcome.undoable},replacement:{assetId:options.replaceWith,code:outcome.codeReplacement}};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError;if(!options.withoutChecking)try{usage=await loadAssetImpact(content2,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await fimo.execute("assets.delete",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}__name(isValidBranch2,"isValidBranch");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2);if(!branch)return null;let tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:"branch",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["symbolic-ref","--short","-q","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&isValidBranch2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_config();init_sdk_transport();init_sdk_transport();init_git();init_project_context();init_esm();function buildPreviewUrl(webUrl,projectId,branch){return new URL(`/preview/${encodeURIComponent(projectId)}/${encodeBranchPathSegment2(branch)}`,webUrl).toString()}__name(buildPreviewUrl,"buildPreviewUrl");function buildProjectPreviewUrl(webUrl,projectId,branch){return new URL(`/app/projects/${encodeURIComponent(projectId)}/branch/${encodeURIComponent(branch)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function branchOverride(program2){return branchOverrideFromCommand(program2)}__name(branchOverride,"branchOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{data:branches}=await fimo.execute("branches.list",{projectId:ctx.projectId,includeDeleted:opts.verbose,includeAgentBranches:opts.all});if(branches.length===0){ui.info({command:"branch",message:"(no Branches yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"branch",label:"BRANCH"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:branches.map(row2=>({branch:row2.branch,status:row2.status,parent:row2.parentBranch??"\u2014"})),isActive:__name(row2=>row2.branch===ctx.branch,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),parentBranch=opts.from??ctx.branch;if(isProductionBranch(name)||isProductionBranch(parentBranch)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let{data:project}=await fimo.execute("projects.get",{projectId:ctx.projectId}),{data:created}=await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),createdBranch=branchNameOf(created),previewUrl=project.previewEnabled===!1?null:buildPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),headline=`Created Branch '${createdBranch}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{branch:createdBranch,parent_branch:parentBranch,env:createdBranch,parent_env:parentBranch,status:created.status,preview_url:previewUrl,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentBranch,previewUrl,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentBranch}`];return result.previewUrl&&lines.push(` Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
1210
1210
  `)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch);if(name===DEFAULT_BRANCH){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default Branch '${DEFAULT_BRANCH}'.`});return}if(isProductionBranch(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be deleted.`});return}await fimo.execute("branches.delete",{projectId:ctx.projectId,branch:name}),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{branch:name,env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),cwd=resolveProjectCwd();if(isProductionBranch(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentBranch=opts.from??ctx.branch,parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),created=!0}else await fimo.execute("branches.get",{projectId:ctx.projectId,branch:name});let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{branch:name,created,git_switched:gitSwitched,parent_branch:opts.from??null,env:name,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever runtime env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{branch,conflicts}=await fimo.execute("branches.sync",{projectId:ctx.projectId,branch:ctx.branch,from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0,synced=branchNameOf(branch);ui.ok({command:"pull",headline:`Branch '${synced}' synced`,details:{branch:synced,env:synced,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentBranch(fimo,projectId,parentBranch,ctx,fromFlag){try{return await fimo.execute("branches.get",{projectId,branch:parentBranch}),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active Branch (\`${ctx.branch}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.branch}\`)`:ctx.source==="tag"?`the release tag \`${ctx.branch}\``:`the project default (\`${ctx.branch}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing Branch via \`--from <branch>\` (try \`--from ${DEFAULT_BRANCH}\`)`):ctx.source==="branch"?(fixes.push(`switch Branches first: \`fimo checkout ${DEFAULT_BRANCH}\``),fixes.push(`or pass \`--from ${DEFAULT_BRANCH}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--branch <existing>\` (try \`--branch ${DEFAULT_BRANCH}\`)`):fixes.push(`pass \`--from ${DEFAULT_BRANCH}\` to fork from main`),{ok:!1,message:`Cannot create Branch: parent Branch '${parentBranch}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentBranch,"validateParentBranch");init_dist();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
1211
1211
  Examples:
1212
- fimo integrations connect slack
1213
1212
  fimo channels bind slack:#launch
1214
1213
  fimo channels bind slack:#support --connection strapi-hq --agent support-agent
1215
1214
 
@@ -1336,7 +1335,7 @@ Examples:
1336
1335
  `)}return question.state==="open"&&lines.push("","Answer with:",` fimo inbox answer ${notificationId} --body '${exampleAnswer(question.form)}'`),lines.join(`
1337
1336
  `)}__name(renderInboxItem,"renderInboxItem");function renderStepBody(step){let body=step.body;switch(body.type){case"text":return[`Write an answer${body.placeholder?` (${body.placeholder})`:""}.`];case"choices":return[pickLine(step),...body.actions.map(action=>option(action.label,action.description,step.recommended))];case"cards":return[pickLine(step),...body.items.map(item=>option(item.title,[item.subtitle,item.imageUrl].filter(Boolean).join(" \xB7 ")||void 0,step.recommended))];case"assets":return[pickLine(step),...body.items.map(item=>option(item.label??item.alt,`${item.alt} \xB7 ${item.url}`,step.recommended))];case"table":return[pickLine(step),` ${body.columns.map(column=>column.label).join(" \xB7 ")}`,...body.rows.map(row2=>option(row2.cells[0]??"",row2.cells.slice(1).join(" \xB7 ")||void 0,step.recommended))];case"capabilities":return["Approve any (an empty selection approves none):",...body.items.map(item=>option(item.label,item.reason,step.recommended))]}}__name(renderStepBody,"renderStepBody");function pickLine(step){return step.multiSelect?"Pick any:":"Pick one:"}__name(pickLine,"pickLine");function option(label,detail,recommended){return` - ${label}${label===recommended?" (recommended)":""}${detail?` \u2014 ${detail}`:""}`}__name(option,"option");function exampleAnswer(form){return JSON.stringify({answers:form.steps.map(step=>({stepId:step.id,selected:[],note:""}))})}__name(exampleAnswer,"exampleAnswer");function renderInboxAnswer(result){let lines=[result.replay?`Already answered: ${result.notification.title}. The run it continued is the same one.`:`Answered: ${result.notification.title}. The run continues with your answer.`,""];for(let item of result.answer)lines.push(`${item.header}: ${item.answer.replaceAll(`
1338
1337
  `," ")}`);return result.capabilities&&lines.push(`Capabilities approved: ${result.capabilities.approved.join(", ")||"none"}`,`Capabilities denied: ${result.capabilities.denied.join(", ")||"none"}`),lines.join(`
1339
- `)}__name(renderInboxAnswer,"renderInboxAnswer");init_init();init_dist6();import fs36 from"node:fs";import path37 from"node:path";init_dist();init_open();init_auth();init_config();init_interactive();init_project();function relativeAgentConfigPath(projectRoot,agentName){return path37.relative(projectRoot,path37.join(resolveProjectAgentsDir(projectRoot),agentName,"config.yaml")).replaceAll("\\","/")}__name(relativeAgentConfigPath,"relativeAgentConfigPath");function registerIntegrationsCommands(program2){let integrations=program2.command("integrations").description("Manage project integrations").addHelpText("after",`
1338
+ `)}__name(renderInboxAnswer,"renderInboxAnswer");init_init();init_dist6();import fs36 from"node:fs";import path37 from"node:path";init_dist();init_auth();init_config();init_interactive();init_project();function relativeAgentConfigPath(projectRoot,agentName){return path37.relative(projectRoot,path37.join(resolveProjectAgentsDir(projectRoot),agentName,"config.yaml")).replaceAll("\\","/")}__name(relativeAgentConfigPath,"relativeAgentConfigPath");function registerIntegrationsCommands(program2){let integrations=program2.command("integrations").description("Manage project integrations").addHelpText("after",`
1340
1339
  Examples:
1341
1340
  fimo integrations list
1342
1341
  fimo integrations info firecrawl
@@ -1344,7 +1343,6 @@ Examples:
1344
1343
  fimo integrations enable firecrawl --auth fimo
1345
1344
  fimo integrations connect firecrawl --name client-a --token-stdin
1346
1345
  fimo integrations enable firecrawl --connection client-a
1347
- fimo integrations connect slack
1348
1346
  fimo integrations run firecrawl search --query "Example Domain" --max-results 3 --include-domains example.com
1349
1347
  fimo integrations run firecrawl scrape --url https://example.com --formats markdown,summary,links
1350
1348
  fimo integrations run firecrawl scrape --url https://example.com --connection client-b
@@ -1355,7 +1353,7 @@ Examples:
1355
1353
  fimo integrations run <provider> <tool> --input @request.json
1356
1354
 
1357
1355
  Run \`fimo integrations <command> --help\` for command-specific help.
1358
- `);integrations.command("list").description("List supported integrations and project setup status").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand2(opts)),integrations.command("info <integration>").description("Show integration tools, auth modes, and recipes").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>infoCommand(integration,opts)),integrations.command("status <integration>").description("Show project setup status for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>statusCommand(integration,opts)),integrations.command("connect <integration>").description("Connect an integration account, workspace, or API key to the active organization").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--org <organizationId>","Organization id (defaults to current project org or active organization)").option("--name <alias>","Connection name/alias").option("--token <value>","API token value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read an API token from stdin").option("--no-open","Print the connect URL without opening a browser").action((integration,opts)=>connectCommand(integration,opts)),integrations.command("enable <integration>").description("Enable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--auth <mode>","Override auth mode: fimo, api-key, or oauth").option("--connection <alias>","Enable with a named organization connection").action((integration,opts)=>enableCommand(integration,opts)),integrations.command("disable <integration>").description("Disable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>disableCommand(integration,opts)),integrations.command("run <integration> <tool>").description("Run an enabled integration tool").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--connection <alias>","Use a named integration connection for this run only").option("--input <json|@file|->","Provider input as inline JSON, @file, or - for stdin").option("--url <url>","URL for Firecrawl scrape, map, or crawl").option("--query <query>","Query for Firecrawl search").option("--formats <formats>","Comma-separated output formats: markdown, summary, links, images, html, raw-html").option("--all-content","Allow Firecrawl to include non-main page content").option("--limit <count>","Maximum URLs/pages for Firecrawl map or crawl").option("--max-results <count>","Maximum search results for Firecrawl search").option("--sources <sources>","Comma-separated Firecrawl search sources: web, news, images").option("--categories <categories>","Comma-separated Firecrawl search categories: github, research, pdf").option("--include-domains <domains>","Only return Firecrawl search results from these comma-separated domains").option("--exclude-domains <domains>","Exclude these comma-separated domains from Firecrawl search results").option("--freshness <range>","Firecrawl search freshness: hour, day, week, month, or year").option("--location <location>","Firecrawl search location, such as Barcelona,Spain").option("--country <code>","Two-letter Firecrawl search country code").option("--no-highlights","Disable query-relevant Firecrawl search excerpts").option("--search <term>","Filter Firecrawl map results").option("--include-subdomains","Include subdomains in Firecrawl map results").option("--timeout-ms <ms>","Provider timeout in milliseconds").option("--wait-for-ms <ms>","Wait before scraping, in milliseconds").option("--name <name>","Name for Firecrawl monitor.create").option("--schedule <schedule>","Plain-language schedule for Firecrawl monitor.create, such as hourly").option("--timezone <timezone>","Timezone for Firecrawl monitor.create schedule").option("--goal <goal>","Plain-language goal for Firecrawl monitor.create").option("--emails <emails>","Comma-separated notification emails for Firecrawl monitor.create").option("--target <type>","Firecrawl monitor target type: scrape or crawl","scrape").option("--monitor-id <id>","Firecrawl monitor id for monitor lifecycle commands").option("--check-id <id>","Firecrawl monitor check id for monitor.check").option("--retention-days <days>","Retention days for Firecrawl monitor.create").option("--judge","Enable Firecrawl goal judging for monitor.create").action((integration,tool,opts)=>runCommand(integration,tool,opts)),integrations.command("auth").description("Choose the active auth mode for an enabled integration").command("use <integration> <mode>").description("Switch auth mode: fimo, api-key, or oauth").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,mode2,opts)=>authUseCommand(integration,mode2,opts));let credentials=integrations.command("credentials").description("Manage hidden integration credentials");credentials.command("set <integration> [credential] [value]").description("Set a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the credential value from stdin").option("--value <value>","Credential value (prefer --stdin in shells that record history)").action((integration,credential,value,opts)=>credentialsSetCommand(integration,credential,opts.value??value,opts)),credentials.command("clear <integration> [credential]").alias("unset").description("Clear a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,credential,opts)=>credentialsClearCommand(integration,credential,opts))}__name(registerIntegrationsCommands,"registerIntegrationsCommands");async function listCommand2(opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts);if(currentAgentSession()){await listAgentRuntimeCommand(integrations,projectId,opts);return}let rows=await integrations.list(projectId);ui.table({command:"integrations list",columns:[{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"},{key:"credentials",label:"CREDENTIALS"}],rows:rows.map(row2=>({integration:row2.integrationKey,status:row2.enabled?"enabled":row2.installed?"disabled":"available",auth:row2.authModeLabel??"",connection:row2.connectionAlias??"",credentials:credentialStatusLabel(row2.credentialStatus)}))})}__name(listCommand2,"listCommand");async function listAgentRuntimeCommand(integrations,projectId,opts){let sessionIntegrations=sessionIntegrationKeys();if(sessionIntegrations){await listSessionIntegrationSnapshot(integrations,projectId,sessionIntegrations);return}let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration access cannot be listed because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path37.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),statuses=await integrations.list(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let[integrationKey,entry]of Object.entries(policy).sort(([a],[b])=>a.localeCompare(b))){let status=statusByKey.get(integrationKey);if(!entry.enabled||!status?.enabled)continue;let info=await integrations.getInfo(projectId,integrationKey),knownTools=new Set(info.tools.map(tool=>tool.key)),availableTools=enabledAgentIntegrationTools(entry,[...knownTools]).filter(tool=>knownTools.has(tool));availableTools.length!==0&&rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:availableTools.join(", ")})}let data2={agentName,configuredBy:relativeAgentConfigPath(projectRoot,agentName),rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listAgentRuntimeCommand,"listAgentRuntimeCommand");async function listSessionIntegrationSnapshot(integrations,projectId,integrationKeys){let statuses=await integrations.list(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let integrationKey of[...integrationKeys].sort()){let status=statusByKey.get(integrationKey);if(!status?.enabled)continue;let info=await integrations.getInfo(projectId,integrationKey);rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:info.tools.map(tool=>tool.key).sort().join(", ")})}let data2={agentName:process.env.FIMO_AGENT_NAME?.trim()||"chat",configuredBy:"session snapshot",rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listSessionIntegrationSnapshot,"listSessionIntegrationSnapshot");async function infoCommand(integration,opts,command="integrations info"){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),info=await integrations.getInfo(projectId,integration);ui.result({command,data:info,render:__name(()=>renderInfo(info),"render")})}__name(infoCommand,"infoCommand");async function statusCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),status=await integrations.getStatus(projectId,integration);ui.result({command:"integrations status",data:status,render:__name(()=>renderStatus(status),"render")})}__name(statusCommand,"statusCommand");async function enableCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),authMode=opts.auth?parseAuthMode(opts.auth):void 0,installation=await integrations.enable({projectId,integrationKey:integration,authMode,connectionAlias:opts.connection});emitInstallationOk("integrations enable",`Enabled ${installation.integrationKey}`,installation)}__name(enableCommand,"enableCommand");async function connectCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),organizationId=resolveOrganizationId(opts);if(integration.toLowerCase()==="slack"){let connect=await integrations.startOrganizationConnect({organizationId,integrationKey:integration});opts.open!==!1&&await open_default(connect.connectUrl),ui.ok({command:"integrations connect",headline:opts.open===!1?`Connect ${connect.integrationKey}`:`Opening ${connect.integrationKey} connect`,details:{organization_id:organizationId,integration:connect.integrationKey,connect_url:connect.connectUrl,expires_at:connect.expiresAt}});return}let token=await resolveConnectionToken(opts),connection=await integrations.connectOrganizationWithToken({organizationId,integrationKey:integration,alias:opts.name,token});ui.ok({command:"integrations connect",headline:`Connected ${connection.integrationKey}`,details:{organization_id:organizationId,integration:connection.integrationKey,connection:connection.alias,auth:authKindCliLabel(connection.authKind),status:connection.status}})}__name(connectCommand,"connectCommand");async function disableCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts);await integrations.disable(projectId,integration),ui.ok({command:"integrations disable",headline:`Disabled ${integration}`,details:{project_id:projectId,integration}})}__name(disableCommand,"disableCommand");async function runCommand(integration,tool,opts,command="integrations run"){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),request=await buildRunRequest(integration,tool,opts);await requireAgentIntegrationTool(integration,request.tool,opts);let run=await integrations.runTool({projectId,integrationKey:integration,request});ui.result({command,data:run,render:__name(()=>renderToolRun(run),"render")})}__name(runCommand,"runCommand");async function requireAgentIntegrationTool(integration,tool,opts){if(!currentAgentSession())return;let sessionIntegrations=sessionIntegrationKeys();if(sessionIntegrations){if(sessionIntegrations.has(integration.toLowerCase()))return;throw new Error(`This agent session is not allowed to run integration '${integration.toLowerCase()}'.`)}let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration policy cannot be checked because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path37.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),integrationKey=integration.toLowerCase(),toolKey=tool.toLowerCase();if(!agentAllowsIntegrationTool(policy,integrationKey,toolKey))throw new Error(`Agent '${agentName}' is not allowed to run ${integrationKey}.${toolKey}. Set integrations.${integrationKey}.enabled: true in ${relativeAgentConfigPath(projectRoot,agentName)}, or add ${toolKey}: true under its tools map to use a narrower allowlist.`)}__name(requireAgentIntegrationTool,"requireAgentIntegrationTool");function sessionIntegrationKeys(){let value=process.env.FIMO_AGENT_INTEGRATIONS;return value===void 0?null:new Set(value.split(",").map(integrationKey=>integrationKey.trim().toLowerCase()).filter(Boolean))}__name(sessionIntegrationKeys,"sessionIntegrationKeys");async function authUseCommand(integration,mode2,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),authMode=parseAuthMode(mode2),installation=await integrations.switchAuth({projectId,integrationKey:integration,authMode});emitInstallationOk("integrations auth use",`Using ${installation.authModeLabel} for ${installation.integrationKey}`,installation)}__name(authUseCommand,"authUseCommand");async function credentialsSetCommand(integration,credential,valueArg,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",value=opts.stdin||valueArg===void 0?await readStdinValue():valueArg,installation=await integrations.setCredential({projectId,integrationKey:integration,credentialId,value});emitInstallationOk("integrations credentials set",`Stored credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsSetCommand,"credentialsSetCommand");async function credentialsClearCommand(integration,credential,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",installation=await integrations.clearCredential({projectId,integrationKey:integration,credentialId});emitInstallationOk("integrations credentials clear",`Cleared credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsClearCommand,"credentialsClearCommand");function emitInstallationOk(command,headline,installation){ui.ok({command,headline,details:{project_id:installation.projectId,integration:installation.integrationKey,enabled:installation.enabled,auth_mode:installation.authMode,auth:installation.authModeLabel,connection:installation.connectionAlias,credential_status:installation.credentialStatus,configured_credentials:installation.configuredCredentials}})}__name(emitInstallationOk,"emitInstallationOk");function renderInfo(info){let lines=[];lines.push(`${info.name}`),lines.push(info.summary),lines.push(""),lines.push("Auth");for(let mode2 of info.authModes)lines.push(` ${mode2.mode.padEnd(8)} ${mode2.label} - ${mode2.description}`);if(info.credentials.length>0){lines.push(""),lines.push("Credentials");for(let credential of info.credentials)lines.push(` ${credential.id.padEnd(12)} ${credential.label}`)}if(info.tools.length>0){lines.push(""),lines.push("Tools");for(let tool of info.tools)lines.push(` ${tool.key.padEnd(18)} ${tool.effect.padEnd(9)} ${tool.description}`)}if(info.recipes.length>0){lines.push(""),lines.push("Recipes");for(let recipe of info.recipes)lines.push(` ${recipe.title}`),lines.push(` ${recipe.description}`),recipe.command&&lines.push(` ${recipe.command}`)}return lines.join(`
1356
+ `);integrations.command("list").description("List supported integrations and project setup status").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand2(opts)),integrations.command("info <integration>").description("Show integration tools, auth modes, and recipes").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>infoCommand(integration,opts)),integrations.command("status <integration>").description("Show project setup status for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>statusCommand(integration,opts)),integrations.command("connect <integration>").description("Connect an integration account, workspace, or API key to the active organization").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--org <organizationId>","Organization id (defaults to current project org or active organization)").option("--name <alias>","Connection name/alias").option("--token <value>","API token value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read an API token from stdin").option("--no-open","Print the connect URL without opening a browser").action((integration,opts)=>connectCommand(integration,opts)),integrations.command("enable <integration>").description("Enable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--auth <mode>","Override auth mode: fimo, api-key, or oauth").option("--connection <alias>","Enable with a named organization connection").action((integration,opts)=>enableCommand(integration,opts)),integrations.command("disable <integration>").description("Disable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>disableCommand(integration,opts)),integrations.command("run <integration> <tool>").description("Run an enabled integration tool").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--connection <alias>","Use a named integration connection for this run only").option("--input <json|@file|->","Provider input as inline JSON, @file, or - for stdin").option("--url <url>","URL for Firecrawl scrape, map, or crawl").option("--query <query>","Query for Firecrawl search").option("--formats <formats>","Comma-separated output formats: markdown, summary, links, images, html, raw-html").option("--all-content","Allow Firecrawl to include non-main page content").option("--limit <count>","Maximum URLs/pages for Firecrawl map or crawl").option("--max-results <count>","Maximum search results for Firecrawl search").option("--sources <sources>","Comma-separated Firecrawl search sources: web, news, images").option("--categories <categories>","Comma-separated Firecrawl search categories: github, research, pdf").option("--include-domains <domains>","Only return Firecrawl search results from these comma-separated domains").option("--exclude-domains <domains>","Exclude these comma-separated domains from Firecrawl search results").option("--freshness <range>","Firecrawl search freshness: hour, day, week, month, or year").option("--location <location>","Firecrawl search location, such as Barcelona,Spain").option("--country <code>","Two-letter Firecrawl search country code").option("--no-highlights","Disable query-relevant Firecrawl search excerpts").option("--search <term>","Filter Firecrawl map results").option("--include-subdomains","Include subdomains in Firecrawl map results").option("--timeout-ms <ms>","Provider timeout in milliseconds").option("--wait-for-ms <ms>","Wait before scraping, in milliseconds").option("--name <name>","Name for Firecrawl monitor.create").option("--schedule <schedule>","Plain-language schedule for Firecrawl monitor.create, such as hourly").option("--timezone <timezone>","Timezone for Firecrawl monitor.create schedule").option("--goal <goal>","Plain-language goal for Firecrawl monitor.create").option("--emails <emails>","Comma-separated notification emails for Firecrawl monitor.create").option("--target <type>","Firecrawl monitor target type: scrape or crawl","scrape").option("--monitor-id <id>","Firecrawl monitor id for monitor lifecycle commands").option("--check-id <id>","Firecrawl monitor check id for monitor.check").option("--retention-days <days>","Retention days for Firecrawl monitor.create").option("--judge","Enable Firecrawl goal judging for monitor.create").action((integration,tool,opts)=>runCommand(integration,tool,opts)),integrations.command("auth").description("Choose the active auth mode for an enabled integration").command("use <integration> <mode>").description("Switch auth mode: fimo, api-key, or oauth").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,mode2,opts)=>authUseCommand(integration,mode2,opts));let credentials=integrations.command("credentials").description("Manage hidden integration credentials");credentials.command("set <integration> [credential] [value]").description("Set a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the credential value from stdin").option("--value <value>","Credential value (prefer --stdin in shells that record history)").action((integration,credential,value,opts)=>credentialsSetCommand(integration,credential,opts.value??value,opts)),credentials.command("clear <integration> [credential]").alias("unset").description("Clear a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,credential,opts)=>credentialsClearCommand(integration,credential,opts))}__name(registerIntegrationsCommands,"registerIntegrationsCommands");async function listCommand2(opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts);if(currentAgentSession()){await listAgentRuntimeCommand(integrations,projectId,opts);return}let rows=await integrations.list(projectId);ui.table({command:"integrations list",columns:[{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"},{key:"credentials",label:"CREDENTIALS"}],rows:rows.map(row2=>({integration:row2.integrationKey,status:row2.enabled?"enabled":row2.installed?"disabled":"available",auth:row2.authModeLabel??"",connection:row2.connectionAlias??"",credentials:credentialStatusLabel(row2.credentialStatus)}))})}__name(listCommand2,"listCommand");async function listAgentRuntimeCommand(integrations,projectId,opts){let sessionIntegrations=sessionIntegrationKeys();if(sessionIntegrations){await listSessionIntegrationSnapshot(integrations,projectId,sessionIntegrations);return}let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration access cannot be listed because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path37.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),statuses=await integrations.list(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let[integrationKey,entry]of Object.entries(policy).sort(([a],[b])=>a.localeCompare(b))){let status=statusByKey.get(integrationKey);if(!entry.enabled||!status?.enabled)continue;let info=await integrations.getInfo(projectId,integrationKey),knownTools=new Set(info.tools.map(tool=>tool.key)),availableTools=enabledAgentIntegrationTools(entry,[...knownTools]).filter(tool=>knownTools.has(tool));availableTools.length!==0&&rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:availableTools.join(", ")})}let data2={agentName,configuredBy:relativeAgentConfigPath(projectRoot,agentName),rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listAgentRuntimeCommand,"listAgentRuntimeCommand");async function listSessionIntegrationSnapshot(integrations,projectId,integrationKeys){let statuses=await integrations.list(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let integrationKey of[...integrationKeys].sort()){let status=statusByKey.get(integrationKey);if(!status?.enabled)continue;let info=await integrations.getInfo(projectId,integrationKey);rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:info.tools.map(tool=>tool.key).sort().join(", ")})}let data2={agentName:process.env.FIMO_AGENT_NAME?.trim()||"chat",configuredBy:"session snapshot",rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listSessionIntegrationSnapshot,"listSessionIntegrationSnapshot");async function infoCommand(integration,opts,command="integrations info"){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),info=await integrations.getInfo(projectId,integration);ui.result({command,data:info,render:__name(()=>renderInfo(info),"render")})}__name(infoCommand,"infoCommand");async function statusCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),status=await integrations.getStatus(projectId,integration);ui.result({command:"integrations status",data:status,render:__name(()=>renderStatus(status),"render")})}__name(statusCommand,"statusCommand");async function enableCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),authMode=opts.auth?parseAuthMode(opts.auth):void 0,installation=await integrations.enable({projectId,integrationKey:integration,authMode,connectionAlias:opts.connection});emitInstallationOk("integrations enable",`Enabled ${installation.integrationKey}`,installation)}__name(enableCommand,"enableCommand");async function connectCommand(integration,opts){if(integration.toLowerCase()==="slack")throw new Error("Set up Slack from Project Settings > Connections in Fimo Studio.");let integrations=createIntegrationService(loadConfig()),organizationId=resolveOrganizationId(opts),token=await resolveConnectionToken(opts),connection=await integrations.connectOrganizationWithToken({organizationId,integrationKey:integration,alias:opts.name,token});ui.ok({command:"integrations connect",headline:`Connected ${connection.integrationKey}`,details:{organization_id:organizationId,integration:connection.integrationKey,connection:connection.alias,auth:authKindCliLabel(connection.authKind),status:connection.status}})}__name(connectCommand,"connectCommand");async function disableCommand(integration,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts);await integrations.disable(projectId,integration),ui.ok({command:"integrations disable",headline:`Disabled ${integration}`,details:{project_id:projectId,integration}})}__name(disableCommand,"disableCommand");async function runCommand(integration,tool,opts,command="integrations run"){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),request=await buildRunRequest(integration,tool,opts);await requireAgentIntegrationTool(integration,request.tool,opts);let run=await integrations.runTool({projectId,integrationKey:integration,request});ui.result({command,data:run,render:__name(()=>renderToolRun(run),"render")})}__name(runCommand,"runCommand");async function requireAgentIntegrationTool(integration,tool,opts){if(!currentAgentSession())return;let sessionIntegrations=sessionIntegrationKeys();if(sessionIntegrations){if(sessionIntegrations.has(integration.toLowerCase()))return;throw new Error(`This agent session is not allowed to run integration '${integration.toLowerCase()}'.`)}let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration policy cannot be checked because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path37.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),integrationKey=integration.toLowerCase(),toolKey=tool.toLowerCase();if(!agentAllowsIntegrationTool(policy,integrationKey,toolKey))throw new Error(`Agent '${agentName}' is not allowed to run ${integrationKey}.${toolKey}. Set integrations.${integrationKey}.enabled: true in ${relativeAgentConfigPath(projectRoot,agentName)}, or add ${toolKey}: true under its tools map to use a narrower allowlist.`)}__name(requireAgentIntegrationTool,"requireAgentIntegrationTool");function sessionIntegrationKeys(){let value=process.env.FIMO_AGENT_INTEGRATIONS;return value===void 0?null:new Set(value.split(",").map(integrationKey=>integrationKey.trim().toLowerCase()).filter(Boolean))}__name(sessionIntegrationKeys,"sessionIntegrationKeys");async function authUseCommand(integration,mode2,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),authMode=parseAuthMode(mode2),installation=await integrations.switchAuth({projectId,integrationKey:integration,authMode});emitInstallationOk("integrations auth use",`Using ${installation.authModeLabel} for ${installation.integrationKey}`,installation)}__name(authUseCommand,"authUseCommand");async function credentialsSetCommand(integration,credential,valueArg,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",value=opts.stdin||valueArg===void 0?await readStdinValue():valueArg,installation=await integrations.setCredential({projectId,integrationKey:integration,credentialId,value});emitInstallationOk("integrations credentials set",`Stored credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsSetCommand,"credentialsSetCommand");async function credentialsClearCommand(integration,credential,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",installation=await integrations.clearCredential({projectId,integrationKey:integration,credentialId});emitInstallationOk("integrations credentials clear",`Cleared credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsClearCommand,"credentialsClearCommand");function emitInstallationOk(command,headline,installation){ui.ok({command,headline,details:{project_id:installation.projectId,integration:installation.integrationKey,enabled:installation.enabled,auth_mode:installation.authMode,auth:installation.authModeLabel,connection:installation.connectionAlias,credential_status:installation.credentialStatus,configured_credentials:installation.configuredCredentials}})}__name(emitInstallationOk,"emitInstallationOk");function renderInfo(info){let lines=[];lines.push(`${info.name}`),lines.push(info.summary),lines.push(""),lines.push("Auth");for(let mode2 of info.authModes)lines.push(` ${mode2.mode.padEnd(8)} ${mode2.label} - ${mode2.description}`);if(info.credentials.length>0){lines.push(""),lines.push("Credentials");for(let credential of info.credentials)lines.push(` ${credential.id.padEnd(12)} ${credential.label}`)}if(info.tools.length>0){lines.push(""),lines.push("Tools");for(let tool of info.tools)lines.push(` ${tool.key.padEnd(18)} ${tool.effect.padEnd(9)} ${tool.description}`)}if(info.recipes.length>0){lines.push(""),lines.push("Recipes");for(let recipe of info.recipes)lines.push(` ${recipe.title}`),lines.push(` ${recipe.description}`),recipe.command&&lines.push(` ${recipe.command}`)}return lines.join(`
1359
1357
  `)}__name(renderInfo,"renderInfo");function renderStatus(status){return[status.integrationKey,`Status: ${status.enabled?"enabled":status.installed?"disabled":"not enabled"}`,`Auth: ${status.authModeLabel??"not selected"}`,`Connection: ${status.connectionAlias??"none"}`,`Credentials: ${credentialStatusLabel(status.credentialStatus)}`,status.configuredCredentials.length>0?`Configured credentials: ${status.configuredCredentials.join(", ")}`:"Configured credentials: none"].join(`
1360
1358
  `)}__name(renderStatus,"renderStatus");function renderAgentRuntimeIntegrationList(data2){let lines=["Integrations available to this agent runtime.",`Configured by: ${data2.configuredBy}`,"Use `fimo integrations info <integration>` for details and `fimo integrations run <integration> <tool> ...` to run a tool.",""];return data2.rows.length===0?(lines.push("No integrations are available to this agent runtime."),lines.join(`
1361
1359
  `)):(lines.push(formatPlainTable([["INTEGRATION","PROJECT","AUTH","AGENT","TOOLS"],...data2.rows.map(row2=>[row2.integration,row2.project,row2.auth,row2.agent,row2.tools])])),lines.join(`