fimo 0.15.0-staging.2 → 0.15.0-staging.4

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.
Files changed (67) hide show
  1. package/README.md +1 -0
  2. package/assets/content-templates/forms/framework.eta +90 -0
  3. package/assets/content-templates/forms/react.eta +42 -21
  4. package/assets/skills/fimo-cli/references/forms.md +2 -2
  5. package/assets/skills/fimo-cli/references/init.md +10 -8
  6. package/assets/skills/fimo-cli/references/projects.md +1 -1
  7. package/assets/skills/fimo-cli/references/schedules.md +5 -2
  8. package/assets/skills/fimo-code/references/forms.md +24 -10
  9. package/assets/skills/fimo-code/references/frameworks/astro.md +9 -0
  10. package/assets/skills/fimo-code/references/frameworks/next.md +25 -0
  11. package/assets/skills/fimo-code/references/frameworks/sveltekit.md +33 -5
  12. package/assets/skills/fimo-code/references/labels.md +1 -1
  13. package/dist/build/sveltekit/config.d.ts +2 -1
  14. package/dist/build/sveltekit/config.js +15 -5
  15. package/dist/build/sveltekit/files/edge.js +68 -0
  16. package/dist/build/sveltekit/files/serverless.js +42 -0
  17. package/dist/cli/bundle.json +1 -1
  18. package/dist/cli/index.js +31 -21
  19. package/dist/runtime/astro/server.d.ts +2 -0
  20. package/dist/runtime/astro/server.js +2 -0
  21. package/dist/runtime/forms/client.d.ts +13 -0
  22. package/dist/runtime/forms/client.js +83 -0
  23. package/dist/runtime/forms/index.d.ts +2 -0
  24. package/dist/runtime/forms/index.js +1 -0
  25. package/dist/runtime/index.d.ts +2 -0
  26. package/dist/runtime/index.js +4 -0
  27. package/dist/runtime/next/client.d.ts +2 -0
  28. package/dist/runtime/next/client.js +2 -0
  29. package/dist/runtime/next/server.d.ts +2 -0
  30. package/dist/runtime/next/server.js +2 -0
  31. package/dist/runtime/react-router/index.d.ts +1 -0
  32. package/dist/runtime/react-router/index.js +1 -0
  33. package/dist/runtime/sveltekit/forms.d.ts +15 -0
  34. package/dist/runtime/sveltekit/forms.js +15 -0
  35. package/dist/runtime/sveltekit/index.d.ts +2 -0
  36. package/dist/runtime/sveltekit/index.js +1 -0
  37. package/dist/runtime/sveltekit/labels.d.ts +7 -3
  38. package/dist/runtime/sveltekit/labels.js +1 -1
  39. package/dist/runtime/sveltekit/runtime.d.ts +2 -1
  40. package/dist/runtime/sveltekit/runtime.js +8 -2
  41. package/dist/runtime/templates.d.ts +1 -1
  42. package/dist/runtime/templates.js +1 -1
  43. package/dist/scripts/sync-forms.d.ts +1 -0
  44. package/dist/scripts/sync-forms.js +78 -26
  45. package/package.json +9 -4
  46. package/templates/astro/.fimo/config.json +21 -0
  47. package/templates/astro/AGENTS.md +37 -0
  48. package/templates/astro/CLAUDE.md +5 -0
  49. package/templates/astro/_gitignore +15 -0
  50. package/templates/astro/astro.config.mjs +7 -0
  51. package/templates/astro/package.json +22 -0
  52. package/templates/astro/pnpm-workspace.yaml +7 -0
  53. package/templates/astro/src/components/ProjectOverview.astro +42 -0
  54. package/templates/astro/src/env.d.ts +1 -0
  55. package/templates/astro/src/layouts/Base.astro +81 -0
  56. package/templates/astro/src/pages/index.astro +10 -0
  57. package/templates/astro/src/pages/projects/[slug].astro +26 -0
  58. package/templates/astro/src/pages/projects/index.astro +10 -0
  59. package/templates/astro/src/schemas/Project.json +9 -0
  60. package/templates/astro/src/schemas/Project.ts +29 -0
  61. package/templates/astro/src/schemas/Project.types.ts +70 -0
  62. package/templates/astro/src/schemas/SiteSettings.json +10 -0
  63. package/templates/astro/src/schemas/SiteSettings.ts +31 -0
  64. package/templates/astro/src/schemas/SiteSettings.types.ts +69 -0
  65. package/templates/astro/tsconfig.json +5 -0
  66. package/templates/react-router/package.json +1 -1
  67. package/templates/sveltekit/src/routes/+layout.server.ts +1 -2
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __fimoCreateRequire } from 'node:module';
3
3
  const require = __fimoCreateRequire(import.meta.url);
4
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string2=""+input,index2=string2.indexOf(close,open2.length);return~index2?open2+replaceClose(string2,close,replace,index2)+close:open2+string2+close},"formatter"),replaceClose=__name((string2,close,replace,index2)=>{let result="",cursor=0;do result+=string2.substring(cursor,index2)+replace,cursor=index2+close.length,index2=string2.indexOf(close,cursor);while(~index2);return result+string2.substring(cursor)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,stderr}=opts;function emit(stream,envelope){stream.write(`${JSON.stringify(envelope)}
4
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string2=""+input,index2=string2.indexOf(close,open2.length);return~index2?open2+replaceClose(string2,close,replace,index2)+close:open2+string2+close},"formatter"),replaceClose=__name((string2,close,replace,index2)=>{let result="",cursor=0;do result+=string2.substring(cursor,index2)+replace,cursor=index2+close.length,index2=string2.indexOf(close,cursor);while(~index2);return result+string2.substring(cursor)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,stderr}=opts;function emit(stream,envelope){stream.write(`${JSON.stringify(envelope)}
5
5
  `)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data2={headline:event.headline};return event.details&&(data2.details=event.details),base.data=data2,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}case"table":{let rows=event.rows.map(row2=>{let out={};for(let col of event.columns)out[col.key]=row2[col.key];return event.isActive?.(row2)===!0&&(out.__active=!0),out}),data2={columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"kv":{let data2={fields:event.fields};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.hint?{hint:event.hint}:{}}})},warn(event){emit(stdout,{status:"ok",command:event.command,schema_version:1,warnings:[event.message]})},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
6
6
  `)}__name(write,"write");function renderMessage(event){if(write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderMessage,"renderMessage");function renderAlignedFields(fields,indent){let keys=Object.keys(fields),longest=keys.reduce((m,k)=>Math.max(m,k.length),0);for(let k of keys){let value=fields[k];value!=null&&write(stdout,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r=>displayWidth(String(r[c2.key]??""))))),header=columns.map((c2,i)=>padToWidth(c2.label,widths[i])).join(" ");write(stdout,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout,`${marker} ${cells.join(" ")}`)}maybeHint(event.hint)}__name(renderTable2,"renderTable");function paintCell(cell,role){switch(role){case"success":return palette2.success(cell);case"warn":return palette2.warn(cell);case"error":return palette2.error(cell);case"dim":return palette2.dim(cell);case"accent":return palette2.accent(cell)}}__name(paintCell,"paintCell");function renderKv(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout.write(event.script.endsWith(`
7
7
  `)?event.script:`${event.script}
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
39
39
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process9.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process9.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path49.basename(filename,path49.extname(filename)),this}executableDir(path50){return path50===void 0?this._executableDir:(this._executableDir=path50,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process9.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
41
41
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
42
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z6}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z6.preprocess(referenceValuePreprocess,z6.object({documentId:z6.uuid()})),ReferenceInputValueSchema=z6.preprocess(referenceValuePreprocess,z6.union([z6.object({documentId:z6.uuid()}),z6.object({slug:z6.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.object({contentType:z6.string().min(1),documentId:z6.uuid()})),PolymorphicReferenceInputValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.union([z6.object({contentType:z6.string().min(1),documentId:z6.uuid()}),z6.object({contentType:z6.string().min(1),slug:z6.string().min(1)})]))}});import{z as z7}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path49){let conditionPath=[...path49,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path49)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z7.union([z7.object({field:z7.string().min(1),equals:z7.union([z7.string(),z7.number(),z7.boolean()])}).strict(),z7.object({field:z7.string().min(1),in:z7.array(z7.union([z7.string(),z7.number(),z7.boolean()])).min(1)}).strict()]),commonFieldShape={label:z7.string().min(1).optional(),description:z7.string().optional(),editable:z7.boolean().optional(),required:z7.boolean().optional(),default:z7.unknown().optional(),showIf:z7.union([showIfClauseSchema,z7.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z7.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z7.object({...commonFieldShape,type:z7.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z7.number().optional(),max:z7.number().optional(),minLength:z7.number().int().nonnegative().optional(),maxLength:z7.number().int().nonnegative().optional(),regex:z7.string().optional(),multiple:z7.boolean().optional(),allowedMimeTypes:z7.array(z7.string()).optional(),options:z7.array(z7.string().min(1)).min(1).optional(),unique:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z7.object({...commonFieldShape,type:z7.literal("reference"),target:z7.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z7.array(z7.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z7.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z7.record(z7.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z7.object({uid:z7.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z7.string().min(1),description:z7.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z7.object({fields:blockFieldsSchema}).strict(),blocksSchema=z7.object({oneOf:z7.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z7.object({...commonFieldShape,type:z7.literal("blocks"),min:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z7.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z7.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z8}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","admin_resource_read","merge_force"],AuditActionSchema=z8.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z8.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z8.enum(AUDIT_ACTOR_KINDS)}});import{z as z9}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z9.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z9.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z9.object({permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),enabled:z9.boolean().default(!0)}),OpsServiceTokenInputSchema=z9.object({name:z9.string().trim().min(1).max(120),permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),expiresAt:z9.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z9.object({importanceReason:z9.string().trim().min(1).max(1e3),ownerUserId:z9.string().trim().min(1).nullable().optional(),framework:z9.string().trim().max(120).nullable().optional(),packageManager:z9.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z9.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z9.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z9.object({projectId:z9.uuid(),title:z9.string().trim().min(1).max(240),userReport:z9.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z9.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z9.string().trim().max(1e4).nullable().optional(),outcome:z9.string().trim().max(1e4).nullable().optional(),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z9.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z9.object({fingerprint:z9.string().trim().min(1).max(240),title:z9.string().trim().min(1).max(240),description:z9.string().trim().min(1).max(1e4),affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z9.string().trim().min(1).max(64).nullable().optional(),workaround:z9.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z9.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z9.object({changeReference:z9.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z9.string().trim().min(1).max(1e4),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z9.object({recipientEmail:z9.email().optional(),subject:z9.string().trim().min(1).max(200).default("An update from Fimo"),message:z9.string().trim().min(1).max(5e3),locale:z9.string().trim().min(2).max(20),reason:z9.string().trim().min(1).max(1e3),acknowledgePolicy:z9.literal(!0)}),OpsSentryIssueIdSchema=z9.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z9.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z9.object({projectId:z9.uuid(),from:z9.coerce.date(),to:z9.coerce.date(),reason:z9.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart"],OpsProjectOperationKindSchema=z9.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z9.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z9.discriminatedUnion("kind",[z9.object({kind:z9.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z9.object({kind:z9.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z9.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z9.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z9.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z9.object({migrationId:OpsMigrationIdSchema,projectEnv:z9.string().trim().min(1).max(255).default("main"),reason:z9.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z9.intersection(OpsProjectOperationPlanInputSchema,z9.object({planHash:z9.string().trim().length(64),reason:z9.string().trim().min(1).max(1e3),consentReference:z9.string().trim().min(1).max(200).optional()}))}});import{z as z10}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z10.object({kind:z10.literal("say"),label:z10.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z10.string().min(1).max(240).optional(),message:z10.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z10.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z10.object({kind:z10.literal("app"),command:z10.literal("publish")}).strict(),BlockBaseSchema=z10.object({fallback:z10.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z10.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z10.literal("choices"),text:z10.string().max(500).optional(),actions:z10.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("entry"),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("asset"),assetId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("url"),url:z10.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z10.literal("table"),columns:z10.array(z10.object({label:z10.string().min(1).max(24)})).min(2).max(4),rows:z10.array(z10.object({cells:z10.array(z10.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z10.literal("cards"),layout:z10.enum(["rail","stack"]).optional(),items:z10.array(z10.object({title:z10.string().min(1).max(60),subtitle:z10.string().min(1).max(120).optional(),imageUrl:z10.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z10.literal("entry"),label:z10.string().min(1).max(80),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120),path:z10.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z10.literal("assets"),items:z10.array(z10.object({url:z10.url({protocol:/^https$/}).max(2e3),alt:z10.string().min(1).max(120),label:z10.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z10.literal("callout"),title:z10.string().min(1).max(80),text:z10.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z10.literal("stat"),items:z10.array(z10.object({label:z10.string().min(1).max(24),value:z10.string().min(1).max(16),delta:z10.string().min(1).max(12).optional(),tone:z10.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z10.literal("chart"),unit:z10.string().min(1).max(12).optional(),points:z10.array(z10.object({label:z10.string().min(1).max(12),value:z10.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z10.object({question:z10.string().min(1).max(500),header:z10.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z10.boolean(),recommended:z10.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z10.literal("form"),steps:z10.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z10.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z10.object({header:z10.string().min(1).max(25),question:z10.string().min(1).max(500),answer:z10.string().min(1).max(3e3),selectedLabels:z10.array(z10.string().min(1).max(120)).max(8),freeText:z10.string().max(2e3),skipped:z10.boolean()}),ChatFormAnswerMetadataSchema=z10.object({toolCallId:z10.string().max(255).optional(),shortTitle:z10.string().max(80).optional(),questions:z10.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z10.string().min(1).max(255)})}});import{z as z11}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,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=z11.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z11.object({dev:z11.string().trim().min(1).optional(),build:z11.string().trim().min(1).optional(),install:z11.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z11.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z11.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z11.object({source:z11.string().min(1),destination:z11.string().min(1)}),FimoHostingConfigSchema=z11.object({rewrites:z11.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z11.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."})})}});import{z as z12}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z12.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z12.string(),displayName:z12.string().nullable(),subdomain:z12.string().nullable().optional(),subdomainUpdatedAt:z12.date().nullable().optional(),organizationId:z12.string().nullable(),createdBy:z12.string().nullable(),previewEnabled:z12.boolean().default(!0),enabledChatModels:z12.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z12.string(),thumbnailUrl:z12.string().nullable(),publishedThumbnailUrl:z12.string().nullable(),category:z12.string().nullable(),appUrl:z12.string().nullable(),lastPublishedAt:z12.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z12.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z12.object({id:z12.uuid(),name:z12.string(),displayName:z12.string().nullable(),thumbnailUrl:z12.string().nullable(),category:z12.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z12.object({id:z12.string(),name:z12.string(),avatar:z12.string().nullable(),color:z12.object({bg:z12.string(),text:z12.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z12.object({path:z12.string(),content:z12.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z12.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z12.object({id:z12.string(),messageId:z12.string(),versionId:z12.string().nullable(),role:ProjectChatMessageRole,parts:z12.array(z12.any()),createdAt:z12.coerce.date()}),MessageUserMetadataSchema=z12.object({id:z12.string(),name:z12.string().nullable().optional(),image:z12.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z12.number(),metadata:z12.object({user:MessageUserMetadataSchema,changeManifest:z12.array(z12.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z12.object({versionId:z12.uuid(),commitHash:z12.string(),name:z12.string(),description:z12.string().nullable(),kind:z12.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z12.object({versionCount:z12.number().int().nonnegative(),snapshotBytes:z12.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z12.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z12.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z12.object({content:z12.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z12.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z12.object({success:z12.boolean(),message:z12.string().optional(),warning:z12.string().optional(),durationMs:z12.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z12.object({isPublished:z12.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z12.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z12.object({success:z12.boolean(),message:z12.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z12.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z13}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z13.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z13.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z13.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,previewUrl:z13.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z13.string().nullable(),deletedAt:z13.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z13.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z13.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z13.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z13.object({surface:z13.enum(["code","schemas","content","translations","assets","forms"]),status:z13.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z13.number().int().nonnegative(),conflictCount:z13.number().int().nonnegative()}),EnvDiffResultSchema=z13.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z13.coerce.date(),surfaces:z13.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z14}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=z14.object({success:z14.literal(!0),downloadUrl:z14.string(),expiresAt:z14.string(),fileSize:z14.number(),duration:z14.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z14.object({success:z14.literal(!0),projectId:z14.string(),projectName:z14.string(),displayName:z14.string(),projectUrl:z14.string(),duration:z14.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z14.object({contentTypes:z14.number(),entries:z14.number(),assets:z14.number(),translations:z14.number(),forms:z14.number(),codeFiles:z14.number(),assetFiles:z14.number()}),ImportPreviewSurfaceDTOSchema=z14.object({name:z14.string(),included:z14.boolean(),count:z14.number().optional(),note:z14.string().optional()}),ImportPreviewDTOSchema=z14.object({projectName:z14.string(),displayName:z14.string().nullable(),category:z14.string().nullable(),exportedAt:z14.string(),version:z14.string(),envScope:z14.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z14.array(ImportPreviewSurfaceDTOSchema),fileSize:z14.number(),fileName:z14.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z14.object({success:z14.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z15}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z15.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z15.object({type:z15.literal("manual")}),ScheduleTriggerSchema=z15.object({type:z15.literal("schedule"),cron:z15.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:z15.string().optional()}),WebhookTriggerSchema=z15.object({type:z15.literal("webhook"),path:z15.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z15.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z16}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=z16.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z16.object({token:z16.string().min(1),risk:CapabilityRiskTierSchema,description:z16.string()}),AgentSubAgentSummarySchema=z16.object({name:z16.string().min(1),grant:z16.enum(["inherit","explicit"]),effectiveCaps:z16.array(z16.string().min(1))}),AgentInstallSummaryDTOSchema=z16.object({agentName:z16.string().min(1),env:z16.string().min(1),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z16.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z16.array(CapabilitySummaryEntrySchema),criticalCapabilities:z16.array(CapabilitySummaryEntrySchema),subAgents:z16.array(AgentSubAgentSummarySchema),declaresDelegate:z16.boolean(),cycle:z16.array(z16.string()).nullable(),missingSubAgents:z16.array(z16.string()),warnings:z16.array(z16.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z17}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=z17.object({kind:TriggerKindSchema,summary:z17.string()}),AgentListItemTriggerStateSchema=z17.object({triggerIndex:z17.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z17.boolean(),wired:z17.boolean(),syncError:z17.string().nullable()}),AgentListItemDTOSchema=z17.object({name:z17.string().min(1),description:z17.string().nullable(),goalFirstLine:z17.string().nullable(),declaredCapabilities:z17.array(CapabilitySummaryEntrySchema),triggers:z17.array(AgentListItemTriggerSchema),triggerStates:z17.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z17.array(AgentListItemDTOSchema))}});import{z as z18}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=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}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=z19.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z19.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z19.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z19.object({verb:SurfaceDeltaVerbSchema,key:z19.string(),detail:z19.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z19.record(z19.string(),z19.unknown()).optional()}),PerSurfaceDeltaSchema=z19.object({surface:SurfaceNameSchema,status:z19.enum(["ok","timed_out","failed","unchanged"]),durationMs:z19.number().int().nonnegative().optional(),changedCount:z19.number().int().nonnegative(),conflictCount:z19.number().int().nonnegative(),items:z19.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z19.boolean().optional(),error:z19.string().optional()}),CrossSurfaceFindingSchema=z19.object({id:z19.string(),kind:z19.string(),description:z19.string(),severity:z19.enum(["warning","error"]),source:z19.object({surface:SurfaceNameSchema,key:z19.string()}),target:z19.object({surface:SurfaceNameSchema,key:z19.string()}),actions:z19.array(z19.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z19.object({env:EnvSchema,vs:EnvSchema,syncState:z19.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),agents:z19.array(z19.object({id:z19.string(),name:z19.string(),status:z19.enum(["active","paused","failed"]),lastRunAt:z19.coerce.date().nullable()})).optional(),crossSurface:z19.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z19.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),crossSurface:z19.array(CrossSurfaceFindingSchema).optional(),fingerprint:z19.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z19.object({path:z19.string(),state:z19.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z19.string(),additions:z19.number().int().nonnegative(),deletions:z19.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z19.object({oid:z19.string().optional(),content:z19.string().optional(),truncated:z19.boolean(),binary:z19.boolean()}),CodeConflictDetailSchema=z19.object({path:z19.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z19.string(),targetTipSha:z19.string(),mergeBaseSha:z19.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z19.object({id:z19.string(),slug:z19.string(),contentType:z19.string(),data:z19.record(z19.string(),z19.unknown()),updatedAt:z19.coerce.date()}),ContentRowDiffSchema=z19.object({collection:z19.string(),rowId:z19.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z19.object({name:z19.string(),label:z19.string(),isSingleton:z19.boolean(),fields:z19.record(z19.string(),z19.unknown())}),SchemaTypeDiffSchema=z19.object({typeName:z19.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z19.object({id:z19.string(),name:z19.string(),type:z19.enum(["file","folder"]),mimeType:z19.string().nullable(),storageKey:z19.string().nullable(),url:z19.string().nullable(),fileSize:z19.number().nullable(),width:z19.number().nullable(),height:z19.number().nullable(),altText:z19.string().nullable(),caption:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AssetDiffSchema=z19.object({assetId:z19.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z19.object({locale:z19.string(),key:z19.string(),parent:z19.string().nullable(),child:z19.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z19.object({formName:z19.string(),label:z19.string().nullable(),schemaFingerprint:z19.string(),fields:z19.record(z19.string(),z19.unknown()),settings:z19.record(z19.string(),z19.unknown()).optional()}),FormSchemaDiffSchema=z19.object({formName:z19.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z19.enum(CONFLICT_KINDS),ConflictSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),kind:ConflictKindSchema.optional(),description:z19.string(),parentValue:z19.unknown().optional(),childValue:z19.unknown().optional(),conflictingFields:z19.array(z19.string()).optional(),code:z19.object({path:z19.string(),unresolvable:z19.boolean().optional(),reason:z19.string().optional()}).optional()}),FieldPickSchema=z19.object({field:z19.string(),choice:z19.enum(["parent","child","pick","ai-pick"]),pickedValue:z19.unknown().optional(),aiSessionId:z19.string().optional()}),ConflictResolutionSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),choice:z19.enum(["parent","child","pick"]),pickedValue:z19.unknown().optional(),fieldPicks:z19.array(FieldPickSchema).optional()}),MergeResultSchema=z19.object({ok:z19.boolean(),mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z19.array(z19.object({surface:SurfaceNameSchema,count:z19.number().int().nonnegative()})),conflicts:z19.array(ConflictSchema).optional(),summary:z19.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z19.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z19.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z19.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z19.boolean().optional()}),ResolvedStrategySchema=z19.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z19.boolean()}),MergeRequestSchema=z19.object({from:EnvSchema,allowDirectMerge:z19.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z19.object({mergeId:z19.string().uuid(),streamUrl:z19.string(),strategy:ResolvedStrategySchema,acceptedAt:z19.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z19.object({mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z19.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z19.array(ConflictSchema),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedBy:z19.string().nullable(),lastEditedAt:z19.coerce.date().nullable(),initiator:z19.object({userId:z19.string().nullable(),role:z19.string().nullable(),agentName:z19.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z19.object({resolutions:z19.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z19.object({mergeId:z19.string().uuid(),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedAt:z19.coerce.date(),lastEditedBy:z19.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z19.object({mergeId:z19.string().uuid(),resolutions:z19.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z19.object({mergeId:z19.string().uuid()}),PublishReleaseRequestSchema=z19.object({version:z19.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z19.string().max(2e4).optional()}),PublishReleaseResultSchema=z19.object({releaseTag:z19.string(),sha:z19.string(),publishedAt:z19.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z20}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z20.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z20.object({cpuMs:z20.number().nonnegative().default(0),netBytes:z20.number().nonnegative().default(0),walltimeMs:z20.number().nonnegative().default(0),llmTokensIn:z20.number().nonnegative().optional(),llmTokensOut:z20.number().nonnegative().optional(),stepCount:z20.number().int().nonnegative().optional(),toolCallCounts:z20.record(z20.string().min(1).max(120),z20.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z20.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z20.object({capturedAt:z20.coerce.date(),fingerprint:z20.string().min(1).max(256),counts:z20.object({code:z20.number().int().nonnegative(),content:z20.number().int().nonnegative(),schemas:z20.number().int().nonnegative(),labels:z20.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z20.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z20.object({diff:DiffReportSchema,code:z20.array(CodeFileDiffSchema.extend({raw:z20.string().max(24576)})).max(200),schemas:z20.array(SchemaTypeDiffSchema).max(200),content:z20.array(z20.object({key:z20.string().min(1).max(512),collection:z20.string().min(1).max(256),slug:z20.string().max(512).optional(),verb:z20.enum(["added","modified","deleted"]),fields:z20.array(z20.object({name:z20.string().min(1).max(256),before:z20.unknown().optional(),after:z20.unknown().optional()})).max(20)})).max(200),labels:z20.array(z20.object({key:z20.string().min(1).max(512),locale:z20.string().min(1).max(64).optional(),before:z20.unknown().nullable(),after:z20.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),env:EnvSchema,agentName:z20.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z20.unknown().optional(),capabilities:z20.array(z20.string()).optional(),dataSources:z20.array(z20.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z20.string().nullable(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),cancelledAt:z20.coerce.date().nullable(),costUsd:z20.number().nonnegative(),costCeilingUsd:z20.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z20.boolean(),lastCheckpointId:z20.uuid().nullable(),branchEnvId:z20.uuid().nullable(),parentSessionId:z20.uuid().nullable(),terminalReason:z20.string().nullable(),errorMessage:z20.string().nullable(),report:z20.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z20.string().nullable(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z20.object({id:z20.uuid(),sessionId:z20.uuid(),checkpointIdx:z20.number().int().nonnegative(),payloadRef:z20.string(),payloadSizeBytes:z20.number().int().nonnegative(),checksum:z20.string().length(64),createdAt:z20.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z20.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z20.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z20.object({session:AgentSessionDTOSchema,checkpoints:z20.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z20.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z20.object({reason:z20.string().min(1).max(120).optional()})}});import{z as z21}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=z21.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z21.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z21.object({id:z21.uuid(),envId:z21.uuid(),sessionId:z21.uuid().nullable(),skillName:z21.string().min(1),classification:AgentBranchClassificationSchema,rationale:z21.string().nullable(),summary:z21.string().nullable(),surfaceDeltas:z21.record(z21.string(),z21.unknown()),createdAt:z21.coerce.date(),decidedAt:z21.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z21.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z21.object({path:z21.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z21.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z21.object({code:z21.literal("merge_conflict"),message:z21.string(),conflicts:z21.record(z21.string(),z21.number().int().nonnegative())})}});import{z as z22}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,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,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,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z22.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z22.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z22.enum(["secret_text"]),IntegrationCredentialUsageSchema=z22.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z22.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z22.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z22.object({mode:IntegrationAuthModeSchema,label:z22.string().min(1),description:z22.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z22.object({id:z22.string().min(1),label:z22.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z22.boolean()}),IntegrationToolDefinitionDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),description:z22.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z22.object({title:z22.string().min(1),description:z22.string().min(1),command:z22.string().min(1).optional()}),IntegrationInfoDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z22.array(IntegrationAuthModeDTOSchema),credentials:z22.array(IntegrationCredentialDefinitionDTOSchema),tools:z22.array(IntegrationToolDefinitionDTOSchema),recipes:z22.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),installed:z22.boolean(),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z22.string().nullable(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),connectionStatus:z22.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),installedAt:z22.coerce.date().nullable(),updatedAt:z22.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z22.string(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z22.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z22.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z22.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z22.object({value:z22.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z22.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z22.object({id:z22.uuid(),organizationId:z22.string().min(1),integrationKey:z22.string().min(1),alias:z22.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z22.string().min(1),externalAccountName:z22.string().nullable(),externalBotUserId:z22.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z22.array(z22.string()),connectedAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z22.object({alias:z22.string().min(1).max(120).optional(),token:z22.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z22.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),alias:z22.string().min(1).max(120),token:z22.string().min(1)}),z22.object({mode:z22.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z22.object({integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),integrationKey:z22.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z22.object({mode:z22.literal("oauth"),integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()})]),BindProjectChannelRequestSchema=z22.object({ref:z22.string().min(1),connectionAlias:z22.string().min(1).optional(),agentName:z22.string().min(1).max(160).nullable().optional(),force:z22.boolean().optional()}),ListProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1)}),SearchProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1),connectionAlias:z22.string().min(1),query:z22.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),connectionId:z22.uuid(),externalWorkspaceId:z22.string().min(1),externalChannelId:z22.string().min(1),externalChannelName:z22.string().nullable(),agentName:z22.string().nullable(),enabled:z22.boolean(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z22.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z22.object({id:z22.string().min(1),name:z22.string().min(1),visibility:z22.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z22.string().min(1).nullable(),canMove:z22.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z22.object({markdown:z22.boolean().optional(),summary:z22.boolean().optional(),links:z22.boolean().optional(),images:z22.boolean().optional(),html:z22.union([z22.literal("cleaned"),z22.literal("raw"),z22.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z22.object({url:z22.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z22.object({query:z22.string().min(1),maxResults:z22.number().int().positive().max(20).optional(),sources:z22.array(z22.enum(["web","news","images"])).min(1).max(3).optional(),categories:z22.array(z22.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z22.enum(["hour","day","week","month","year"]).optional(),location:z22.string().min(1).max(160).optional(),country:z22.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z22.object({url:z22.string().url(),search:z22.string().min(1).optional(),limit:z22.number().int().positive().max(200).optional(),includeSubdomains:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z22.object({url:z22.string().url(),limit:z22.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z22.object({text:z22.string().min(1).max(200).optional(),cron:z22.string().min(1).max(120).optional(),timezone:z22.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z22.object({type:z22.enum(["scrape","crawl"]).default("scrape"),urls:z22.array(z22.string().url()).min(1).max(50),scrapeOptions:z22.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z22.object({name:z22.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z22.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z22.string().min(1).max(2e3).optional(),judgeEnabled:z22.boolean().optional(),retentionDays:z22.number().int().min(1).max(365).optional(),notification:z22.object({email:z22.object({enabled:z22.boolean().default(!0),recipients:z22.array(z22.string().email()).min(1).max(20),includeDiffs:z22.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z22.object({monitorId:z22.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z22.string().uuid()}),RunProjectIntegrationToolRequestSchema=z22.object({tool:z22.string().min(1),input:z22.record(z22.string(),z22.unknown()),connectionAlias:z22.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z22.object({provider:z22.string().min(1),providerCredits:z22.number().nonnegative().optional(),providerCostUsd:z22.number().nonnegative().optional(),requests:z22.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z22.object({credits:z22.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()}),FirecrawlSearchToolOutputSchema=z22.object({query:z22.string(),provider:z22.literal("firecrawl"),warning:z22.string().optional(),results:z22.array(z22.object({title:z22.string(),url:z22.string(),snippet:z22.string().optional(),content:z22.string().optional(),score:z22.number().optional(),publishedAt:z22.string().optional()}))}),FirecrawlMapToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),count:z22.number(),links:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),description:z22.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),total:z22.number(),pages:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()})),warning:z22.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z22.object({cron:z22.string().optional(),text:z22.string().optional(),timezone:z22.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z22.object({id:z22.string().optional(),urls:z22.array(z22.string()).optional(),scrapeOptions:z22.record(z22.string(),z22.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z22.object({id:z22.string(),name:z22.string(),status:z22.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z22.string().nullable().optional(),lastRunAt:z22.string().nullable().optional(),currentCheckId:z22.string().nullable().optional(),targets:z22.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z22.string().nullable().optional(),judgeEnabled:z22.boolean().optional(),estimatedCreditsPerMonth:z22.number().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z22.object({id:z22.string(),monitorId:z22.string(),scheduledFor:z22.string().nullable().optional(),startedAt:z22.string().nullable().optional(),finishedAt:z22.string().nullable().optional(),estimatedCredits:z22.number().optional(),reservedCredits:z22.number().optional(),actualCredits:z22.number().optional(),billingStatus:z22.string().nullable().optional(),summary:z22.object({totalPages:z22.number().optional(),same:z22.number().optional(),changed:z22.number().optional(),new:z22.number().optional(),removed:z22.number().optional(),error:z22.number().optional()}).passthrough().optional(),error:z22.string().nullable().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitors:z22.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),deleted:z22.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),checks:z22.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),check:FirecrawlMonitorCheckOutputSchema,next:z22.string().optional()}),FirecrawlToolKeySchema=z22.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z22.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),tool:z22.string().min(1),connectionAlias:z22.string().min(1).nullable().optional(),output:z22.record(z22.string(),z22.unknown()),executedAt:z22.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z22.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z22.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z22.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z22.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z22.array(ProjectChannelCandidateDTOSchema))}});import{z as z23}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,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();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=z23.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=z23.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z23.uuid(),env:z23.string().min(1),name:z23.string().min(1),cron:z23.string().min(1),command:z23.string().min(1),secretKeys:z23.array(z23.string().min(1)),enabled:z23.boolean(),lastRunAt:z23.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z23.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z23.object({name:z23.string().min(1).max(120),cron:z23.string().min(1).max(120),command:z23.string().min(1).max(500),secretKeys:z23.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z23.object({name:z23.string().min(1).max(120).optional(),cron:z23.string().min(1).max(120).optional(),command:z23.string().min(1).max(500).optional(),secretKeys:z23.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z23.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z23.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z23.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z23.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z23.object({maxRuns:z23.number().int().positive(),retentionDays:z23.number().int().positive().nullable(),outputRetentionDays:z23.number().int().positive(),maxOutputBytes:z23.number().int().positive()}),ProjectScheduleUsageSchema=z23.object({runCount:z23.number().int().nonnegative(),runsWithOutput:z23.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z23.object({id:z23.uuid(),scheduleId:z23.uuid(),projectId:z23.uuid(),env:z23.string().min(1),scheduleName:z23.string().min(1),command:z23.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z23.object({id:z23.string().min(1),name:z23.string().min(1)}).nullable(),queuedAt:z23.coerce.date(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),exitCode:z23.number().int().nullable(),errorCode:z23.string().nullable(),error:z23.string().nullable(),outputBytes:z23.number().int().nonnegative(),outputTruncated:z23.boolean(),outputExpiresAt:z23.coerce.date().nullable(),metadataExpiresAt:z23.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z23.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z23.coerce.date().nullable(),items:z23.array(z23.object({key:z23.string().min(1),updatedAt:z23.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z23.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z23.object({trigger:z23.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z23.object({limit:z23.coerce.number().int().min(1).max(100).default(25),cursor:z23.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z23.object({items:z23.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z23.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z23.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z23.object({items:z23.array(ProjectScheduleRunDTOSchema),nextCursor:z23.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z24}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z24.object({id:z24.uuid(),occurredAt:z24.coerce.date(),projectId:z24.uuid().nullable(),env:z24.string().nullable(),actor:z24.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z24.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z24.unknown().optional(),ipAddress:z24.string().nullable().optional(),userAgent:z24.string().nullable().optional(),error:z24.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z24.object({rows:z24.array(AuditLogRowDTOSchema),nextCursor:z24.string().nullable()})),AuditLogQuerySchema=z24.object({env:z24.string().optional(),action:AuditActionSchema.optional(),actor:z24.string().optional(),from:z24.coerce.date().optional(),to:z24.coerce.date().optional(),limit:z24.coerce.number().int().min(1).max(200).optional(),cursor:z24.string().optional()})}});import{z as z25}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=z25.object({surface:SurfaceNameSchema,key:z25.string(),label:z25.string()}),InlineSchema=z25.object({text:z25.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z25.discriminatedUnion("type",[z25.object({type:z25.literal("paragraph"),content:z25.array(InlineSchema).max(24)}),z25.object({type:z25.literal("preview"),ref:DiffRefSchema,caption:z25.string().optional()}),z25.object({type:z25.literal("code"),code:z25.string(),lang:z25.string().optional(),caption:z25.string().optional()}),z25.object({type:z25.literal("risk"),level:z25.enum(["warning","error"]),content:z25.array(InlineSchema).max(24)}),z25.object({type:z25.literal("list"),items:z25.array(z25.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z25.object({headline:z25.string(),blocks:z25.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z25.object({summary:EnvDiffSummarySchema,fingerprint:z25.string(),generatedAt:z25.coerce.date(),cached:z25.boolean().optional(),credits:z25.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z26}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=z26.object({date:z26.string(),visitors:z26.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z26.object({key:z26.string(),visitors:z26.number().int().nonnegative(),pageviews:z26.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z26.object({path:z26.string(),pageName:z26.string().nullable().optional(),visitors:z26.number().int().nonnegative(),pageviews:z26.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z26.object({preset:z26.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z26.string(),requestedTo:z26.string(),effectiveFrom:z26.string(),effectiveTo:z26.string(),isRetentionLimited:z26.boolean(),groupBy:z26.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z26.object({date:z26.string(),content:z26.string(),updatedAt:z26.string(),updatedByUserId:z26.string()}),ProjectPageviewAnalyticsDTOSchema=z26.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z26.number().int().nonnegative(),pageviews:z26.number().int().nonnegative(),bounceRate:z26.number().min(0).max(100),viewsPerVisit:z26.number().nonnegative(),averageVisitDurationSeconds:z26.number().nonnegative(),visitorsSeries:z26.array(ProjectDailyVisitorsDTOSchema),topPages:z26.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z26.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z26.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z26.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z26.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z26.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z27}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z27.object({id:z27.string(),email:z27.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z27.coerce.date(),createdAt:z27.coerce.date(),inviterUserId:z27.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z27.object({id:z27.string(),token:z27.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z27.object({success:z27.boolean(),projectId:z27.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z28}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=z28.object({id:z28.string(),name:z28.string(),image:z28.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z28.object({count:z28.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z28.object({counts:z28.object({signed_up:z28.int(),activated:z28.int()}),credits:z28.object({total:z28.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z28.email(),emailVerified:z28.boolean(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z29}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z29.object({id:z29.string(),principalType:ProjectPrincipalTypeSchema,principalId:z29.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z29.coerce.date(),expiresAt:z29.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=z29.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z29.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z29.record(z29.string(),z29.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z29.object({access:z29.array(ProjectAccessItemDTOSchema),invites:z29.array(ProjectInviteDTOSchema),organization:z29.object({name:z29.string().nullable(),logo:z29.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z29.object({success:z29.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z29.object({success:z29.boolean(),projectId:z29.uuid()}))}});import{z as z30}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z30.object({publicationStatus:PublicationStatusSchema,appUrl:z30.string().nullable(),lastPublishedAt:z30.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z31}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z31.object({url:z31.url(),expiresAt:z31.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z32}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z32.string(),slug:z32.string().nullable(),logo:z32.string().nullable(),metadata:z32.record(z32.string(),z32.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),email:z32.email(),image:z32.string().nullable()}),OrganizationMemberDTOSchema=z32.object({id:z32.string(),userId:z32.string(),organizationId:z32.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z32.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z33}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z33.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z33.object({reason:CancellationReasonCodeSchema,details:z33.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z33.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z33.object({included:z33.number().optional(),unitPrice:z33.number().optional(),dailyCap:z33.number().nullable().optional()}),EntitlementsDTOSchema=z33.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z33.object({retentionDays:z33.number().int().positive(),canUseExtendedDateRanges:z33.boolean()}).optional(),history:z33.object({retentionDays:z33.number().int().positive()}).optional(),members:z33.object({canInvite:z33.boolean(),maxMembers:z33.number().int().positive().nullable()}).optional(),domains:z33.object({canUseCustomDomains:z33.boolean(),maxDomains:z33.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z33.object({id:z33.string(),external_id:z33.string(),customerId:z33.string(),planId:z33.string(),planCode:TemplateCodeSchema,currentPeriod:z33.object({start:z33.string(),end:z33.string().nullable()}),cancelAt:z33.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z33.string(),nextPaymentAt:z33.string().nullable(),baseAmount:z33.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z33.object({totalCap:z33.number(),dailyCap:z33.number(),usedTotal:z33.number()}),CreditBalanceDTOSchema=z33.object({total:z33.number(),base:z33.number(),dailyBase:z33.number(),purchases:z33.number(),awards:z33.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z33.object({total:z33.number(),nearLimit:z33.boolean(),canChat:z33.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z33.object({dailyFreeAvailable:z33.number(),monthlyAvailable:z33.number(),purchasedAvailable:z33.number(),awardedAvailable:z33.number()}),ProjectDailyCreditAllowanceDTOSchema=z33.object({periodCap:z33.number(),dailyGrant:z33.number(),usedThisPeriod:z33.number(),remainingThisPeriod:z33.number()}),ProjectCreditBalanceDTOSchema=z33.object({projectId:z33.uuid(),organizationId:z33.string(),balance:z33.object({totalAvailable:z33.number(),nearLimit:z33.boolean(),canUseAi:z33.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z33.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z33.discriminatedUnion("enabled",[z33.object({enabled:z33.literal(!0),thresholdUsd:z33.number().nonnegative(),refillAmountUsd:z33.number().nonnegative()}),z33.object({enabled:z33.literal(!1),thresholdUsd:z33.number().nonnegative().nullable(),refillAmountUsd:z33.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z33.discriminatedUnion("enabled",[z33.object({enabled:z33.literal(!0),thresholdUsd:z33.number().min(.01).multipleOf(.01),refillAmountUsd:z33.number().min(.01).multipleOf(.01)}).strict(),z33.object({enabled:z33.literal(!1),thresholdUsd:z33.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z33.object({invoiceId:z33.string(),newBalance:z33.int(),creditCount:z33.int(),amountUsd:z33.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z33.object({url:z33.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z34}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=z34.object({brand:z34.string(),last4:z34.string(),exp:z34.string(),isDefault:z34.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z35}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z35.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z35.object({type:z35.literal("renameField"),contentType:z35.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z35.object({enabled:z35.boolean()}).strict(),ContentTypeDTOSchema=z35.object({id:z35.string(),name:z35.string(),label:z35.string(),isSingleton:z35.boolean(),i18n:ContentTypeI18nSchema,fields:z35.record(z35.string(),FieldDefinitionSchema),createdAt:z35.string(),updatedAt:z35.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z35.object({contentTypes:z35.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z35.object({id:z35.string(),entryId:z35.string(),documentId:z35.string(),slug:z35.string(),locale:z35.string().optional(),createdAt:z35.string(),updatedAt:z35.string(),__fimo:z35.object({contentType:z35.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z35.object({data:z35.array(EntryDTOSchema),meta:z35.object({limit:z35.number(),offset:z35.number(),total:z35.number(),hasMore:z35.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z35.object({contentType:z35.string(),count:z35.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z35.object({counts:z35.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z35.object({count:z35.number().int().nonnegative(),sourceLocale:z35.string(),targetLocale:z35.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z35.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z35.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z35.union([z35.string(),z35.number(),z35.boolean(),z35.null()]),entryWhereOperatorSchema=z35.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z35.array(entryWhereScalarSchema).optional(),$nin:z35.array(entryWhereScalarSchema).optional(),$contains:z35.string().optional(),$startsWith:z35.string().optional(),$null:z35.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z35.record(z35.string(),z35.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z35.record(z35.string(),z35.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z35.object({data:z35.record(z35.string(),z35.unknown()),locale:z35.string().min(1).optional(),documentId:z35.uuid().optional()}),entryIdsSchema=z35.array(z35.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z35.object({sql:z35.string().min(1)}),BulkCreateEntriesRequestSchema=z35.object({entries:z35.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z35.union([z35.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z35.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z35.object({updates:z35.array(z35.object({id:z35.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z35.union([z35.object({ids:entryIdsSchema,locale:z35.string().min(1).optional()}),z35.object({where:EntryWhereSchema,locale:z35.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z35.object({data:z35.array(z35.record(z35.string(),z35.unknown())),meta:z35.object({rowCount:z35.number().int().nonnegative(),truncated:z35.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z35.object({data:z35.array(EntryDTOSchema),meta:z35.object({created:z35.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z35.object({data:z35.array(EntryDTOSchema),meta:z35.object({updated:z35.number().int().nonnegative(),missing:z35.array(z35.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z35.object({data:z35.array(EntryDTOSchema),meta:z35.object({deleted:z35.number().int().nonnegative(),missing:z35.array(z35.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z36}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z36.object({index:z36.number().int().nonnegative(),contentType:z36.string(),field:z36.string(),value:z36.string(),against:z36.enum(["stored","batch"]),ownerDocumentId:z36.uuid().optional(),ownerIndex:z36.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z36.object({code:z36.literal("unique_conflict"),message:z36.string(),conflicts:z36.array(UniqueConflictSchema),truncated:z36.boolean().optional()})}});import{z as z37}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=z37.object({kind:z37.literal("unique_conflict"),contentType:z37.string(),field:z37.string(),value:z37.string(),documentCount:z37.number().int().positive(),documentIds:z37.array(z37.uuid()),documentIdsTruncated:z37.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z37.object({code:z37.literal("schema_transition_rejected"),message:z37.string(),issues:z37.array(SchemaTransitionIssueSchema),truncated:z37.boolean().optional()})}});import{z as z38}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z38.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z38.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z38.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z38.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z38.object({field:CmsFieldNameSchema,direction:z38.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z38.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z38.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z38.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z38.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z38.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z39}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z39.object({id:z39.string(),name:z39.string()}),AssetDTOSchema=z39.object({id:z39.string(),name:z39.string(),type:AssetTypeSchema,originalFileName:z39.string().nullable(),parentId:z39.string().nullable(),mimeType:z39.string().nullable(),fileSize:z39.number().nullable(),url:z39.string().nullable(),storageKey:z39.string().nullable(),createdAt:z39.string(),updatedAt:z39.string(),altText:z39.string().nullable().optional(),caption:z39.string().nullable().optional(),aiCaption:z39.string().nullable().optional(),aiAltText:z39.string().nullable().optional(),aiTags:z39.array(z39.string()).nullable().optional(),aiPrimaryColor:z39.string().nullable().optional(),aiProcessingStatus:z39.string().nullable().optional(),width:z39.number().nullable().optional(),height:z39.number().nullable().optional(),path:z39.array(AssetPathItemSchema).optional(),hasChildren:z39.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z39.lazy(()=>z39.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z39.array(AssetDTOSchema))}});import{z as z40}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z40.object({key:z40.string(),value:z40.string().optional(),defaultValue:z40.string(),locale:z40.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string(),type:z41.enum(["file","folder"]),path:z41.string(),children:z41.lazy(()=>z41.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z41.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z41.object({path:z41.string(),exists:z41.boolean(),type:z41.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z42}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=z42.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z42.object({items:z42.array(ProjectMessagePublicDTOSchema),nextCursor:z42.string().nullable()}),ChatLiveTurnDTOSchema=z42.object({invocationId:z42.string(),step:z42.enum(["preparing","working","compacting","merging"]),startedAt:z42.string()}),ChatLiveTurnStateDTOSchema=z42.object({threadId:z42.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z42.object({id:z42.string(),role:z42.enum(["user","assistant"]),parts:z42.array(z42.unknown()),metadata:z42.record(z42.string(),z42.unknown()).nullable(),versionId:z42.string().nullable().optional(),createdAt:z42.date().transform(value=>value.toISOString()),providerMessageId:z42.string().nullable().optional(),invocationId:z42.string().nullable().optional(),invocationStatus:z42.string().nullable().optional(),invocationTerminalReason:z42.string().nullable().optional()}),ChatAttentionDTOSchema=z42.object({type:z42.literal("merge_conflict"),merge:z42.object({mergeId:z42.string().uuid(),projectId:z42.string(),fromEnv:z42.string(),toEnv:z42.string()}),publishAfterMerge:z42.boolean()}),ChatThreadMessagesPageDTOSchema=z42.object({threadId:z42.string().nullable(),title:z42.string().nullable(),messages:z42.array(ChatThreadMessageDTOSchema),nextCursor:z42.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z42.object({kind:z42.literal("replay"),threadId:z42.string(),userMessageId:z42.string()}),ChatQueuedOutcomeDTOSchema=z42.object({kind:z42.literal("queued"),threadId:z42.string(),userMessageId:z42.string(),blockingRootId:z42.string()}),ChatBusyOutcomeDTOSchema=z42.object({kind:z42.literal("busy"),threadId:z42.string(),userMessageId:z42.string(),blockingRootId:z42.string().optional()}),ChatRefusedOutcomeDTOSchema=z42.object({kind:z42.literal("refused"),threadId:z42.string(),userMessageId:z42.string(),refusedInvocationId:z42.string(),terminalReason:z42.string()}),ChatNonStreamingOutcomeDTOSchema=z42.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z42.object({success:z42.boolean(),deletedCount:z42.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z42.object({code:z42.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z42.string()})}});import{z as z43}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z43.object({url:z43.string().url(),key:z43.string(),size:z43.number(),contentType:z43.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z44}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=z44.object({canAccess:z44.boolean(),permissions:z44.record(z44.string(),z44.boolean()),role:z44.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z45}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:z45.string().trim().default(""),sort:z45.enum(["recent","name","relevance"]).default("recent"),category:z45.string().optional()})}});import{z as z46}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z46.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z46.enum(["fimo","external"]),PaymentStatusSchema=z46.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z46.object({id:z46.string().uuid(),domain:z46.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z46.boolean(),price:z46.number().int().nullable(),renewalPrice:z46.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z46.string().nullable(),failureReason:z46.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z46.object({domain:z46.string(),available:z46.boolean(),premium:z46.boolean(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),purchaseType:z46.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z46.object({domain:z46.string(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),premium:z46.boolean(),allowedYears:z46.array(z46.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z46.object({firstName:z46.string().max(100),lastName:z46.string().max(100),companyName:z46.string().max(100).optional(),address1:z46.string().max(255),address2:z46.string().max(255).optional(),city:z46.string().max(100),state:z46.string().max(100),zip:z46.string().max(20),country:z46.string().max(2),phone:z46.string().max(30),email:z46.union([z46.string().email().max(255),z46.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z46.object({firstName:z46.string().min(1).max(100),lastName:z46.string().min(1).max(100),companyName:z46.string().max(100).optional(),address1:z46.string().min(1).max(255),address2:z46.string().max(255).optional(),city:z46.string().min(1).max(100),state:z46.string().min(1).max(100),zip:z46.string().min(1).max(20),country:z46.string().min(1).max(2),phone:z46.string().min(1).max(30),email:z46.string().email().max(255)}),SearchDomainsRequestSchema=z46.object({keyword:z46.string().min(1).max(100),tldFilter:z46.array(z46.string()).optional()}),CheckAvailabilityRequestSchema=z46.object({domains:z46.array(z46.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=z46.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z46.object({domain:DomainNameSchema,years:z46.number().int().min(1).max(10).optional().default(3),autoRenew:z46.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z46.object({autoRenew:z46.boolean().optional()}),RenewDomainRequestSchema=z46.object({years:z46.number().int().min(1).max(10).optional().default(1),autoRenew:z46.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z46.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z46.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z46.object({verified:z46.boolean(),email:z46.string().nullable(),verifyBy:z46.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z47}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z47.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=z47.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=z47.object({txtName:z47.string().nullable().optional(),txtValue:z47.string().nullable().optional(),httpUrl:z47.string().nullable().optional(),httpBody:z47.string().nullable().optional(),cname:z47.string().nullable().optional(),cnameTarget:z47.string().nullable().optional()}),SSLValidationErrorSchema=z47.object({message:z47.string()}),OwnershipVerificationSchema=z47.object({type:z47.string(),name:z47.string(),value:z47.string()}),ProjectDomainSSLDTOSchema=z47.object({status:z47.string(),method:z47.string().nullable(),type:z47.string().nullable(),validationRecords:z47.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z47.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z47.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z47.enum(["subdomain","apex"]),RedirectConfigSchema=z47.object({type:z47.literal("apex_to_www"),linkedDomainId:z47.string()}).nullable().optional(),ProjectDomainDTOSchema=z47.object({id:z47.string(),hostname:z47.string(),status:z47.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z47.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z47.string(),scdCnameTarget:z47.string().optional(),apexTargets:z47.array(z47.string()),dnsAutoConfigured:z47.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z47.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z47.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z47.object({hostname:z47.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:z47.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z47.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z47.object({success:z47.boolean(),hostname:z47.string()}))}});import{z as z48}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=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z48.object({slug:z48.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z48.object({subdomain:z48.string(),subdomainUpdatedAt:z48.coerce.date()})),SubdomainSuggestionsQuerySchema=z48.object({base:z48.string().max(100).optional(),max:z48.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z48.object({suggestions:z48.array(z48.string())}))}});import{z as z49}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z49.object({translated:z49.number().int().nonnegative(),total:z49.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z49.object({locale:z49.string(),isDefault:z49.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z49.object({defaultLocale:z49.string(),routing:z49.object({strategy:z49.literal("path-prefix"),prefixDefaultLocale:z49.boolean()}),locales:z49.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z49.object({locale:z49.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z49.object({locale:z49.string().min(1).max(40)}),ProjectLocaleMutationSchema=z49.object({locale:z49.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z49.object({locale:z49.string(),entriesDeleted:z49.number().int().nonnegative(),labelsDeleted:z49.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z50}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=z50.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z50.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=z50.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z50.number(),credits:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z51}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z51.object({options:z51.record(z51.string(),z51.unknown()),name:z51.string().optional(),parentId:z51.string().nullable().optional(),altText:z51.string().optional(),caption:z51.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z51.string().min(1).optional(),model:z51.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=z51.object({jobId:z51.string(),status:z51.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z51.string().nullable().optional(),credits:z51.number().optional(),costUsd:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z51.object({error:z51.string(),code:z51.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:z51.array(GenerationTaskIdSchema).optional(),availableModels:z51.array(z51.string()).optional(),issues:z51.array(z51.unknown()).optional()})}});import{z as z52}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=z52.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z52.object({name:z52.string(),key:z52.string(),description:z52.string(),type:FlagTypeSchema,required:z52.boolean(),defaultValue:z52.unknown().optional(),enumValues:z52.array(z52.string()).optional(),isArray:z52.boolean()}),AssetModelPriceSchema=z52.object({unitPrice:z52.number(),unit:z52.string(),confidence:z52.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z52.object({id:z52.string(),shortName:z52.string(),provider:z52.string(),source:z52.string(),modality:z52.enum(["image","video","audio"]),tags:z52.array(z52.string()),displayName:z52.string(),description:z52.string(),flags:z52.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z52.object({model:z52.string(),costUsd:z52.number(),credits:z52.number(),billingMode:z52.enum(["fimo-credits","provider-account"]),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z53}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=z53.object({tourId:z53.string(),version:z53.string(),status:z53.string(),completedAt:z53.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z53.array(UserTourDTOSchema))}});import{z as z54}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=z54.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z54.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z54.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z54.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z54.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z54.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z54.enum(["user","agent","system"]),SupportReportTagSchema=z54.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z54.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z54.object({organization:z54.object({id:z54.string().trim().min(1).max(255),name:z54.string().trim().max(240).optional()}),project:z54.object({id:z54.uuid(),name:z54.string().trim().max(240).optional(),createdAt:z54.coerce.date().optional()}).optional(),environment:z54.string().trim().max(255).optional(),clientVersion:z54.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z54.object({message:z54.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z54.string().trim().max(200).optional(),limit:z54.coerce.number().int().min(1).max(100).default(50),offset:z54.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z54.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z54.uuid().nullable().optional(),note:z54.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=z54.object({message:z54.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z54.object({kind:SupportReportLinkKindSchema,label:z54.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z54.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z54.object({kind:SupportReportActorKindSchema,id:z54.string().nullable(),name:z54.string().nullable()}),SupportReportLinkDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportLinkKindSchema,label:z54.string(),url:SupportReportHttpUrlSchema,externalId:z54.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportEventKindSchema,body:z54.string().nullable(),metadata:z54.record(z54.string(),z54.unknown()),actor:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z54.object({id:z54.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z54.array(z54.string()),source:SupportReportSourceSchema,message:z54.string(),reporter:z54.object({id:z54.string().nullable(),name:z54.string().nullable(),email:z54.string().nullable()}),organization:z54.object({id:z54.string().nullable(),name:z54.string()}),project:z54.object({id:z54.uuid().nullable(),name:z54.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z54.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z54.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}).nullable(),duplicateOfReportId:z54.uuid().nullable(),resolvedAt:z54.coerce.date().nullable(),createdAt:z54.coerce.date(),updatedAt:z54.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z54.string().nullable(),clientVersion:z54.string().nullable(),links:z54.array(SupportReportLinkDTOSchema),events:z54.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z54.object({reports:z54.array(SupportReportSummaryDTOSchema),total:z54.number().int().nonnegative(),statusCounts:z54.object({new:z54.number().int().nonnegative(),in_progress:z54.number().int().nonnegative(),waiting:z54.number().int().nonnegative(),resolved:z54.number().int().nonnegative(),duplicate:z54.number().int().nonnegative(),irrelevant:z54.number().int().nonnegative(),ignored:z54.number().int().nonnegative()}),limit:z54.number().int().positive(),offset:z54.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z54.object({id:z54.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z54.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z55}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=z55.iso.datetime({offset:!0}).pipe(z55.coerce.date()),OpsRecentChatInputSchema=z55.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z55.string().trim().min(1).max(255).optional(),limit:z55.coerce.number().int().min(1).max(200).default(100),cursor:z55.string().trim().min(1).max(2e3).optional(),slim:z55.boolean().default(!0),reason:z55.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=z55.object({id:z55.string(),threadId:z55.string(),providerMessageId:z55.string().nullable(),invocationId:z55.string().nullable(),env:z55.string().nullable(),role:z55.string(),parts:z55.array(z55.record(z55.string(),z55.unknown())),metadata:z55.object({status:z55.string().optional(),traceUrl:z55.string().optional(),externalFileChanges:z55.array(z55.unknown()).optional()}),stats:z55.object({toolCount:z55.number().int().nonnegative(),failedToolCount:z55.number().int().nonnegative()}),createdAt:z55.iso.datetime({offset:!0}),project:z55.object({id:z55.string(),name:z55.string(),displayName:z55.string().nullable(),organizationId:z55.string().nullable()})}),OpsRecentChatResponseSchema=z55.object({target:z55.object({backendProfile:OpsBackendProfileSchema,projectEnv:z55.string().nullable()}),window:z55.object({from:z55.iso.datetime({offset:!0}),to:z55.iso.datetime({offset:!0})}),messages:z55.object({items:z55.array(OpsRecentChatMessageSchema),nextCursor:z55.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z56}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=z56.object({backendProfile:OpsBackendProfileSchema,provider:z56.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z56.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z56.object({backendProfile:OpsBackendProfileSchema,provider:z56.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z56.literal(!1),reason:z56.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z57}from"zod";function createAgentRunWebhookEventDataSchema(status){return z57.object({run:z57.object({id:z57.string(),agentName:z57.string(),trigger:z57.string(),status:z57.literal(status),startedAt:z57.string().nullable(),finishedAt:z57.string().nullable(),reason:z57.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z57.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z57.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z57.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z57.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z57.union([z57.literal(0),z57.literal(5),z57.literal(30),z57.literal(60)]),EntryChangedWebhookEventDataSchema=z57.object({reason:WebhookEntryChangeReasonSchema,operationId:z57.string().optional(),batch:z57.object({index:z57.number().int().positive(),total:z57.number().int().positive()}).optional(),changes:z57.array(z57.object({action:WebhookEntryChangeActionSchema,contentType:z57.string(),id:z57.string(),documentId:z57.string(),locale:z57.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z57.object({form:z57.object({id:z57.string(),label:z57.string()}),submission:z57.object({id:z57.string(),data:z57.record(z57.string(),z57.unknown()),submittedAt:z57.string()})}),PublishStartedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("publishing"),startedAt:z57.string()})}),PublishSucceededWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("published"),url:z57.string(),publishedAt:z57.string(),firstPublish:z57.boolean()})}),PublishFailedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("failed"),reason:z57.string()})}),PublishUnpublishedWebhookEventDataSchema=z57.object({publication:z57.object({previousUrl:z57.string(),unpublishedAt:z57.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),classification:z57.string(),summary:z57.string(),reasons:z57.array(z57.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),resolution:z57.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z57.object({report:z57.object({weekStart:z57.string(),weekEnd:z57.string(),pageviews:z57.number(),visitors:z57.number(),previousPageviews:z57.number(),previousVisitors:z57.number()})}),MediaAssetWebhookEventDataSchema=z57.object({id:z57.string().nullable(),name:z57.string().nullable(),type:z57.string(),mimeType:z57.string().nullable(),fileSize:z57.number().nullable()}),MediaUploadedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["updated","moved","analysis"]),analysis:z57.object({category:z57.string(),status:z57.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("generated"),generation:z57.object({model:z57.string(),mode:z57.string()})}),MediaProcessingFailedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["analysis","generation"]),failure:z57.object({code:z57.string()})}),DomainCreatedWebhookEventDataSchema=z57.object({domain:z57.object({id:z57.string(),hostname:z57.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z57.object({domain:z57.object({id:z57.string(),hostname:z57.string()})}),LabelChangedWebhookEventDataSchema=z57.object({changes:z57.array(z57.object({action:z57.enum(["created","updated","deleted"]),key:z57.string(),locale:z57.string(),value:z57.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z57.object({locale:z57.object({code:z57.string(),isDefault:z57.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z57.object({locale:z57.object({code:z57.string(),previousCode:z57.string()})}),LocaleDeletedWebhookEventDataSchema=z57.object({locale:z57.object({code:z57.string(),entriesDeleted:z57.number().int().nonnegative(),labelsDeleted:z57.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z57.object({environment:z57.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z57.object({environment:z57.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z57.object({merge:z57.object({id:z57.string(),from:EnvSchema,to:EnvSchema,applied:z57.array(z57.object({surface:SurfaceNameSchema,count:z57.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z57.object({environment:z57.object({name:EnvSchema}),version:z57.object({versionId:z57.uuid(),name:z57.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z57.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z57.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z57.discriminatedUnion("source",[z57.object({source:z57.literal("literal"),value:z57.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z57.object({source:z57.literal("secret"),key:z57.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z57.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z57.object({name:z57.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z57.object({name:z57.string(),source:z57.enum(["literal","secret"]),secretKey:z57.string().nullable(),secretPrefix:z57.string().nullable(),configured:z57.literal(!0)}),WebhookFilterSchema=z57.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z57.string().min(1).max(255).optional(),agentName:z57.string().min(1).max(120).optional(),mediaType:z57.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z57.string().min(1).max(255).optional(),locale:z57.string().min(1).max(120).optional()}),JsonValueSchema=z57.lazy(()=>z57.union([z57.string(),z57.number(),z57.boolean(),z57.null(),z57.array(JsonValueSchema),z57.record(z57.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z57.url(),enabled:z57.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z57.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z57.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z57.url().optional(),enabled:z57.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z57.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z57.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z57.object({eventType:WebhookEventTypeSchema.optional(),data:z57.record(z57.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z57.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z57.uuid(),name:z57.string(),eventType:WebhookEventTypeSchema,enabled:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z57.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z57.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z57.coerce.date().nullable(),deliveryStats24h:z57.object({succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z57.uuid(),projectId:z57.uuid(),env:EnvSchema,eventId:z57.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z57.number().int().positive(),test:z57.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z57.number().int().nonnegative(),responseStatus:z57.number().int().nullable(),lastErrorCode:z57.string().nullable(),lastErrorMessage:z57.string().nullable(),payloadAvailable:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z57.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z57.string().nullable(),qstashMessageId:z57.string().nullable(),deliveredAt:z57.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z57.object({items:z57.array(WebhookDeliveryDTOSchema),pagination:z57.object({page:z57.number().int().positive(),limit:z57.number().int().positive(),total:z57.number().int().nonnegative(),totalPages:z57.number().int().positive(),hasMore:z57.boolean()}),stats:z57.object({total:z57.number().int().nonnegative(),succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z57.object({id:z57.uuid(),deliveryId:z57.uuid(),attempt:z57.number().int().positive(),status:z57.enum(["delivering","succeeded","failed"]),responseStatus:z57.number().int().nullable(),durationMs:z57.number().int().nonnegative(),responseExcerpt:z57.string().nullable(),errorCode:z57.string().nullable(),errorMessage:z57.string().nullable(),createdAt:z57.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z57.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z57.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z58}from"zod";var PREVIEW_FEATURE_REGISTRY,previewFeatureKeys,PreviewFeatureDTOSchema,PreviewFeatureDTO,PreviewFeatureResponseSchema,PreviewFeatureListResponseSchema,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();init_response();PREVIEW_FEATURE_REGISTRY={"fimo-2":{key:"fimo-2",defaultEnabled:!1}},previewFeatureKeys=Object.keys(PREVIEW_FEATURE_REGISTRY),PreviewFeatureDTOSchema=z58.object({key:z58.enum(previewFeatureKeys),enabled:z58.boolean(),dismissed:z58.boolean().default(!1),interacted:z58.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z58.array(PreviewFeatureDTOSchema))}});import{z as z59}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}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=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}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=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional(),activeOnly:z61.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable(),unattributedCredits:z61.number(),unattributedCostUsd:z61.number(),unattributedMessages:z61.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),userDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),top:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),top:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),top:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}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=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path49,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path49} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
42
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z6}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z6.preprocess(referenceValuePreprocess,z6.object({documentId:z6.uuid()})),ReferenceInputValueSchema=z6.preprocess(referenceValuePreprocess,z6.union([z6.object({documentId:z6.uuid()}),z6.object({slug:z6.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.object({contentType:z6.string().min(1),documentId:z6.uuid()})),PolymorphicReferenceInputValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.union([z6.object({contentType:z6.string().min(1),documentId:z6.uuid()}),z6.object({contentType:z6.string().min(1),slug:z6.string().min(1)})]))}});import{z as z7}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path49){let conditionPath=[...path49,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path49)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z7.union([z7.object({field:z7.string().min(1),equals:z7.union([z7.string(),z7.number(),z7.boolean()])}).strict(),z7.object({field:z7.string().min(1),in:z7.array(z7.union([z7.string(),z7.number(),z7.boolean()])).min(1)}).strict()]),commonFieldShape={label:z7.string().min(1).optional(),description:z7.string().optional(),editable:z7.boolean().optional(),required:z7.boolean().optional(),default:z7.unknown().optional(),showIf:z7.union([showIfClauseSchema,z7.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z7.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z7.object({...commonFieldShape,type:z7.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z7.number().optional(),max:z7.number().optional(),minLength:z7.number().int().nonnegative().optional(),maxLength:z7.number().int().nonnegative().optional(),regex:z7.string().optional(),multiple:z7.boolean().optional(),allowedMimeTypes:z7.array(z7.string()).optional(),options:z7.array(z7.string().min(1)).min(1).optional(),unique:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z7.object({...commonFieldShape,type:z7.literal("reference"),target:z7.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z7.array(z7.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z7.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z7.record(z7.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z7.object({uid:z7.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z7.string().min(1),description:z7.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z7.object({fields:blockFieldsSchema}).strict(),blocksSchema=z7.object({oneOf:z7.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z7.object({...commonFieldShape,type:z7.literal("blocks"),min:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z7.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z7.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z8}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","admin_resource_read","merge_force"],AuditActionSchema=z8.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z8.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z8.enum(AUDIT_ACTOR_KINDS)}});import{z as z9}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z9.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z9.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z9.object({permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),enabled:z9.boolean().default(!0)}),OpsServiceTokenInputSchema=z9.object({name:z9.string().trim().min(1).max(120),permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),expiresAt:z9.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z9.object({importanceReason:z9.string().trim().min(1).max(1e3),ownerUserId:z9.string().trim().min(1).nullable().optional(),framework:z9.string().trim().max(120).nullable().optional(),packageManager:z9.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z9.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z9.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z9.object({projectId:z9.uuid(),title:z9.string().trim().min(1).max(240),userReport:z9.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z9.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z9.string().trim().max(1e4).nullable().optional(),outcome:z9.string().trim().max(1e4).nullable().optional(),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z9.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z9.object({fingerprint:z9.string().trim().min(1).max(240),title:z9.string().trim().min(1).max(240),description:z9.string().trim().min(1).max(1e4),affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z9.string().trim().min(1).max(64).nullable().optional(),workaround:z9.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z9.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z9.object({changeReference:z9.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z9.string().trim().min(1).max(1e4),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z9.object({recipientEmail:z9.email().optional(),subject:z9.string().trim().min(1).max(200).default("An update from Fimo"),message:z9.string().trim().min(1).max(5e3),locale:z9.string().trim().min(2).max(20),reason:z9.string().trim().min(1).max(1e3),acknowledgePolicy:z9.literal(!0)}),OpsSentryIssueIdSchema=z9.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z9.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z9.object({projectId:z9.uuid(),from:z9.coerce.date(),to:z9.coerce.date(),reason:z9.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart"],OpsProjectOperationKindSchema=z9.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z9.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z9.discriminatedUnion("kind",[z9.object({kind:z9.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z9.object({kind:z9.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z9.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z9.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z9.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z9.object({migrationId:OpsMigrationIdSchema,projectEnv:z9.string().trim().min(1).max(255).default("main"),reason:z9.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z9.intersection(OpsProjectOperationPlanInputSchema,z9.object({planHash:z9.string().trim().length(64),reason:z9.string().trim().min(1).max(1e3),consentReference:z9.string().trim().min(1).max(200).optional()}))}});import{z as z10}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z10.object({kind:z10.literal("say"),label:z10.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z10.string().min(1).max(240).optional(),message:z10.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z10.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z10.object({kind:z10.literal("app"),command:z10.literal("publish")}).strict(),BlockBaseSchema=z10.object({fallback:z10.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z10.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z10.literal("choices"),text:z10.string().max(500).optional(),actions:z10.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("entry"),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("asset"),assetId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("url"),url:z10.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z10.literal("table"),columns:z10.array(z10.object({label:z10.string().min(1).max(24)})).min(2).max(4),rows:z10.array(z10.object({cells:z10.array(z10.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z10.literal("cards"),layout:z10.enum(["rail","stack"]).optional(),items:z10.array(z10.object({title:z10.string().min(1).max(60),subtitle:z10.string().min(1).max(120).optional(),imageUrl:z10.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z10.literal("entry"),label:z10.string().min(1).max(80),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120),path:z10.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z10.literal("assets"),items:z10.array(z10.object({url:z10.url({protocol:/^https$/}).max(2e3),alt:z10.string().min(1).max(120),label:z10.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z10.literal("callout"),title:z10.string().min(1).max(80),text:z10.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z10.literal("stat"),items:z10.array(z10.object({label:z10.string().min(1).max(24),value:z10.string().min(1).max(16),delta:z10.string().min(1).max(12).optional(),tone:z10.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z10.literal("chart"),unit:z10.string().min(1).max(12).optional(),points:z10.array(z10.object({label:z10.string().min(1).max(12),value:z10.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z10.object({question:z10.string().min(1).max(500),header:z10.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z10.boolean(),recommended:z10.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z10.literal("form"),steps:z10.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z10.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z10.object({header:z10.string().min(1).max(25),question:z10.string().min(1).max(500),answer:z10.string().min(1).max(3e3),selectedLabels:z10.array(z10.string().min(1).max(120)).max(8),freeText:z10.string().max(2e3),skipped:z10.boolean()}),ChatFormAnswerMetadataSchema=z10.object({toolCallId:z10.string().max(255).optional(),shortTitle:z10.string().max(80).optional(),questions:z10.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z10.string().min(1).max(255)})}});import{z as z11}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,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=z11.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z11.object({dev:z11.string().trim().min(1).optional(),build:z11.string().trim().min(1).optional(),install:z11.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z11.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z11.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z11.object({source:z11.string().min(1),destination:z11.string().min(1)}),FimoHostingConfigSchema=z11.object({rewrites:z11.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z11.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."})})}});import{z as z12}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z12.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z12.string(),displayName:z12.string().nullable(),subdomain:z12.string().nullable().optional(),subdomainUpdatedAt:z12.date().nullable().optional(),organizationId:z12.string().nullable(),createdBy:z12.string().nullable(),previewEnabled:z12.boolean().default(!0),enabledChatModels:z12.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z12.string(),thumbnailUrl:z12.string().nullable(),publishedThumbnailUrl:z12.string().nullable(),category:z12.string().nullable(),appUrl:z12.string().nullable(),lastPublishedAt:z12.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z12.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z12.object({id:z12.uuid(),name:z12.string(),displayName:z12.string().nullable(),thumbnailUrl:z12.string().nullable(),category:z12.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z12.object({id:z12.string(),name:z12.string(),avatar:z12.string().nullable(),color:z12.object({bg:z12.string(),text:z12.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z12.object({path:z12.string(),content:z12.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z12.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z12.object({id:z12.string(),messageId:z12.string(),versionId:z12.string().nullable(),role:ProjectChatMessageRole,parts:z12.array(z12.any()),createdAt:z12.coerce.date()}),MessageUserMetadataSchema=z12.object({id:z12.string(),name:z12.string().nullable().optional(),image:z12.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z12.number(),metadata:z12.object({user:MessageUserMetadataSchema,changeManifest:z12.array(z12.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z12.object({versionId:z12.uuid(),commitHash:z12.string(),name:z12.string(),description:z12.string().nullable(),kind:z12.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z12.object({versionCount:z12.number().int().nonnegative(),snapshotBytes:z12.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z12.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z12.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z12.object({content:z12.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z12.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z12.object({success:z12.boolean(),message:z12.string().optional(),warning:z12.string().optional(),durationMs:z12.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z12.object({isPublished:z12.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z12.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z12.object({success:z12.boolean(),message:z12.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z12.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z13}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z13.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z13.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z13.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,previewUrl:z13.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z13.string().nullable(),deletedAt:z13.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z13.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z13.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z13.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z13.object({surface:z13.enum(["code","schemas","content","translations","assets","forms"]),status:z13.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z13.number().int().nonnegative(),conflictCount:z13.number().int().nonnegative()}),EnvDiffResultSchema=z13.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z13.coerce.date(),surfaces:z13.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z14}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=z14.object({success:z14.literal(!0),downloadUrl:z14.string(),expiresAt:z14.string(),fileSize:z14.number(),duration:z14.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z14.object({success:z14.literal(!0),projectId:z14.string(),projectName:z14.string(),displayName:z14.string(),projectUrl:z14.string(),duration:z14.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z14.object({contentTypes:z14.number(),entries:z14.number(),assets:z14.number(),translations:z14.number(),forms:z14.number(),codeFiles:z14.number(),assetFiles:z14.number()}),ImportPreviewSurfaceDTOSchema=z14.object({name:z14.string(),included:z14.boolean(),count:z14.number().optional(),note:z14.string().optional()}),ImportPreviewDTOSchema=z14.object({projectName:z14.string(),displayName:z14.string().nullable(),category:z14.string().nullable(),exportedAt:z14.string(),version:z14.string(),envScope:z14.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z14.array(ImportPreviewSurfaceDTOSchema),fileSize:z14.number(),fileName:z14.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z14.object({success:z14.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z15}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z15.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z15.object({type:z15.literal("manual")}),ScheduleTriggerSchema=z15.object({type:z15.literal("schedule"),cron:z15.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:z15.string().optional()}),WebhookTriggerSchema=z15.object({type:z15.literal("webhook"),path:z15.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z15.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z16}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=z16.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z16.object({token:z16.string().min(1),risk:CapabilityRiskTierSchema,description:z16.string()}),AgentSubAgentSummarySchema=z16.object({name:z16.string().min(1),grant:z16.enum(["inherit","explicit"]),effectiveCaps:z16.array(z16.string().min(1))}),AgentInstallSummaryDTOSchema=z16.object({agentName:z16.string().min(1),env:z16.string().min(1),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z16.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z16.array(CapabilitySummaryEntrySchema),criticalCapabilities:z16.array(CapabilitySummaryEntrySchema),subAgents:z16.array(AgentSubAgentSummarySchema),declaresDelegate:z16.boolean(),cycle:z16.array(z16.string()).nullable(),missingSubAgents:z16.array(z16.string()),warnings:z16.array(z16.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z17}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=z17.object({kind:TriggerKindSchema,summary:z17.string()}),AgentListItemTriggerStateSchema=z17.object({triggerIndex:z17.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z17.boolean(),wired:z17.boolean(),syncError:z17.string().nullable()}),AgentListItemDTOSchema=z17.object({name:z17.string().min(1),description:z17.string().nullable(),goalFirstLine:z17.string().nullable(),declaredCapabilities:z17.array(CapabilitySummaryEntrySchema),triggers:z17.array(AgentListItemTriggerSchema),triggerStates:z17.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z17.array(AgentListItemDTOSchema))}});import{z as z18}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=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}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=z19.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z19.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z19.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z19.object({verb:SurfaceDeltaVerbSchema,key:z19.string(),detail:z19.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z19.record(z19.string(),z19.unknown()).optional()}),PerSurfaceDeltaSchema=z19.object({surface:SurfaceNameSchema,status:z19.enum(["ok","timed_out","failed","unchanged"]),durationMs:z19.number().int().nonnegative().optional(),changedCount:z19.number().int().nonnegative(),conflictCount:z19.number().int().nonnegative(),items:z19.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z19.boolean().optional(),error:z19.string().optional()}),CrossSurfaceFindingSchema=z19.object({id:z19.string(),kind:z19.string(),description:z19.string(),severity:z19.enum(["warning","error"]),source:z19.object({surface:SurfaceNameSchema,key:z19.string()}),target:z19.object({surface:SurfaceNameSchema,key:z19.string()}),actions:z19.array(z19.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z19.object({env:EnvSchema,vs:EnvSchema,syncState:z19.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),agents:z19.array(z19.object({id:z19.string(),name:z19.string(),status:z19.enum(["active","paused","failed"]),lastRunAt:z19.coerce.date().nullable()})).optional(),crossSurface:z19.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z19.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),crossSurface:z19.array(CrossSurfaceFindingSchema).optional(),fingerprint:z19.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z19.object({path:z19.string(),state:z19.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z19.string(),additions:z19.number().int().nonnegative(),deletions:z19.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z19.object({oid:z19.string().optional(),content:z19.string().optional(),truncated:z19.boolean(),binary:z19.boolean()}),CodeConflictDetailSchema=z19.object({path:z19.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z19.string(),targetTipSha:z19.string(),mergeBaseSha:z19.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z19.object({id:z19.string(),slug:z19.string(),contentType:z19.string(),data:z19.record(z19.string(),z19.unknown()),updatedAt:z19.coerce.date()}),ContentRowDiffSchema=z19.object({collection:z19.string(),rowId:z19.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z19.object({name:z19.string(),label:z19.string(),isSingleton:z19.boolean(),fields:z19.record(z19.string(),z19.unknown())}),SchemaTypeDiffSchema=z19.object({typeName:z19.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z19.object({id:z19.string(),name:z19.string(),type:z19.enum(["file","folder"]),mimeType:z19.string().nullable(),storageKey:z19.string().nullable(),url:z19.string().nullable(),fileSize:z19.number().nullable(),width:z19.number().nullable(),height:z19.number().nullable(),altText:z19.string().nullable(),caption:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AssetDiffSchema=z19.object({assetId:z19.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z19.object({locale:z19.string(),key:z19.string(),parent:z19.string().nullable(),child:z19.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z19.object({formName:z19.string(),label:z19.string().nullable(),schemaFingerprint:z19.string(),fields:z19.record(z19.string(),z19.unknown()),settings:z19.record(z19.string(),z19.unknown()).optional()}),FormSchemaDiffSchema=z19.object({formName:z19.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z19.enum(CONFLICT_KINDS),ConflictSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),kind:ConflictKindSchema.optional(),description:z19.string(),parentValue:z19.unknown().optional(),childValue:z19.unknown().optional(),conflictingFields:z19.array(z19.string()).optional(),code:z19.object({path:z19.string(),unresolvable:z19.boolean().optional(),reason:z19.string().optional()}).optional()}),FieldPickSchema=z19.object({field:z19.string(),choice:z19.enum(["parent","child","pick","ai-pick"]),pickedValue:z19.unknown().optional(),aiSessionId:z19.string().optional()}),ConflictResolutionSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),choice:z19.enum(["parent","child","pick"]),pickedValue:z19.unknown().optional(),fieldPicks:z19.array(FieldPickSchema).optional()}),MergeResultSchema=z19.object({ok:z19.boolean(),mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z19.array(z19.object({surface:SurfaceNameSchema,count:z19.number().int().nonnegative()})),conflicts:z19.array(ConflictSchema).optional(),summary:z19.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z19.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z19.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z19.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z19.boolean().optional()}),ResolvedStrategySchema=z19.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z19.boolean()}),MergeRequestSchema=z19.object({from:EnvSchema,allowDirectMerge:z19.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z19.object({mergeId:z19.string().uuid(),streamUrl:z19.string(),strategy:ResolvedStrategySchema,acceptedAt:z19.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z19.object({mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z19.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z19.array(ConflictSchema),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedBy:z19.string().nullable(),lastEditedAt:z19.coerce.date().nullable(),initiator:z19.object({userId:z19.string().nullable(),role:z19.string().nullable(),agentName:z19.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z19.object({resolutions:z19.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z19.object({mergeId:z19.string().uuid(),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedAt:z19.coerce.date(),lastEditedBy:z19.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z19.object({mergeId:z19.string().uuid(),resolutions:z19.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z19.object({mergeId:z19.string().uuid()}),PublishReleaseRequestSchema=z19.object({version:z19.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z19.string().max(2e4).optional()}),PublishReleaseResultSchema=z19.object({releaseTag:z19.string(),sha:z19.string(),publishedAt:z19.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z20}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z20.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z20.object({cpuMs:z20.number().nonnegative().default(0),netBytes:z20.number().nonnegative().default(0),walltimeMs:z20.number().nonnegative().default(0),llmTokensIn:z20.number().nonnegative().optional(),llmTokensOut:z20.number().nonnegative().optional(),stepCount:z20.number().int().nonnegative().optional(),toolCallCounts:z20.record(z20.string().min(1).max(120),z20.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z20.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z20.object({capturedAt:z20.coerce.date(),fingerprint:z20.string().min(1).max(256),counts:z20.object({code:z20.number().int().nonnegative(),content:z20.number().int().nonnegative(),schemas:z20.number().int().nonnegative(),labels:z20.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z20.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z20.object({diff:DiffReportSchema,code:z20.array(CodeFileDiffSchema.extend({raw:z20.string().max(24576)})).max(200),schemas:z20.array(SchemaTypeDiffSchema).max(200),content:z20.array(z20.object({key:z20.string().min(1).max(512),collection:z20.string().min(1).max(256),slug:z20.string().max(512).optional(),verb:z20.enum(["added","modified","deleted"]),fields:z20.array(z20.object({name:z20.string().min(1).max(256),before:z20.unknown().optional(),after:z20.unknown().optional()})).max(20)})).max(200),labels:z20.array(z20.object({key:z20.string().min(1).max(512),locale:z20.string().min(1).max(64).optional(),before:z20.unknown().nullable(),after:z20.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),env:EnvSchema,agentName:z20.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z20.unknown().optional(),capabilities:z20.array(z20.string()).optional(),dataSources:z20.array(z20.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z20.string().nullable(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),cancelledAt:z20.coerce.date().nullable(),costUsd:z20.number().nonnegative(),costCeilingUsd:z20.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z20.boolean(),lastCheckpointId:z20.uuid().nullable(),branchEnvId:z20.uuid().nullable(),parentSessionId:z20.uuid().nullable(),terminalReason:z20.string().nullable(),errorMessage:z20.string().nullable(),report:z20.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z20.string().nullable(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z20.object({id:z20.uuid(),sessionId:z20.uuid(),checkpointIdx:z20.number().int().nonnegative(),payloadRef:z20.string(),payloadSizeBytes:z20.number().int().nonnegative(),checksum:z20.string().length(64),createdAt:z20.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z20.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z20.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z20.object({session:AgentSessionDTOSchema,checkpoints:z20.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z20.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z20.object({reason:z20.string().min(1).max(120).optional()})}});import{z as z21}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=z21.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z21.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z21.object({id:z21.uuid(),envId:z21.uuid(),sessionId:z21.uuid().nullable(),skillName:z21.string().min(1),classification:AgentBranchClassificationSchema,rationale:z21.string().nullable(),summary:z21.string().nullable(),surfaceDeltas:z21.record(z21.string(),z21.unknown()),createdAt:z21.coerce.date(),decidedAt:z21.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z21.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z21.object({path:z21.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z21.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z21.object({code:z21.literal("merge_conflict"),message:z21.string(),conflicts:z21.record(z21.string(),z21.number().int().nonnegative())})}});import{z as z22}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,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,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,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z22.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z22.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z22.enum(["secret_text"]),IntegrationCredentialUsageSchema=z22.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z22.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z22.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z22.object({mode:IntegrationAuthModeSchema,label:z22.string().min(1),description:z22.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z22.object({id:z22.string().min(1),label:z22.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z22.boolean()}),IntegrationToolDefinitionDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),description:z22.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z22.object({title:z22.string().min(1),description:z22.string().min(1),command:z22.string().min(1).optional()}),IntegrationInfoDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z22.array(IntegrationAuthModeDTOSchema),credentials:z22.array(IntegrationCredentialDefinitionDTOSchema),tools:z22.array(IntegrationToolDefinitionDTOSchema),recipes:z22.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),installed:z22.boolean(),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z22.string().nullable(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),connectionStatus:z22.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),installedAt:z22.coerce.date().nullable(),updatedAt:z22.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z22.string(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z22.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z22.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z22.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z22.object({value:z22.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z22.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z22.object({id:z22.uuid(),organizationId:z22.string().min(1),integrationKey:z22.string().min(1),alias:z22.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z22.string().min(1),externalAccountName:z22.string().nullable(),externalBotUserId:z22.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z22.array(z22.string()),connectedAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z22.object({alias:z22.string().min(1).max(120).optional(),token:z22.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z22.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),alias:z22.string().min(1).max(120),token:z22.string().min(1)}),z22.object({mode:z22.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z22.object({integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),integrationKey:z22.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z22.object({mode:z22.literal("oauth"),integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()})]),BindProjectChannelRequestSchema=z22.object({ref:z22.string().min(1),connectionAlias:z22.string().min(1).optional(),agentName:z22.string().min(1).max(160).nullable().optional(),force:z22.boolean().optional()}),ListProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1)}),SearchProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1),connectionAlias:z22.string().min(1),query:z22.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),connectionId:z22.uuid(),externalWorkspaceId:z22.string().min(1),externalChannelId:z22.string().min(1),externalChannelName:z22.string().nullable(),agentName:z22.string().nullable(),enabled:z22.boolean(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z22.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z22.object({id:z22.string().min(1),name:z22.string().min(1),visibility:z22.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z22.string().min(1).nullable(),canMove:z22.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z22.object({markdown:z22.boolean().optional(),summary:z22.boolean().optional(),links:z22.boolean().optional(),images:z22.boolean().optional(),html:z22.union([z22.literal("cleaned"),z22.literal("raw"),z22.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z22.object({url:z22.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z22.object({query:z22.string().min(1),maxResults:z22.number().int().positive().max(20).optional(),sources:z22.array(z22.enum(["web","news","images"])).min(1).max(3).optional(),categories:z22.array(z22.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z22.enum(["hour","day","week","month","year"]).optional(),location:z22.string().min(1).max(160).optional(),country:z22.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z22.object({url:z22.string().url(),search:z22.string().min(1).optional(),limit:z22.number().int().positive().max(200).optional(),includeSubdomains:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z22.object({url:z22.string().url(),limit:z22.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z22.object({text:z22.string().min(1).max(200).optional(),cron:z22.string().min(1).max(120).optional(),timezone:z22.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z22.object({type:z22.enum(["scrape","crawl"]).default("scrape"),urls:z22.array(z22.string().url()).min(1).max(50),scrapeOptions:z22.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z22.object({name:z22.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z22.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z22.string().min(1).max(2e3).optional(),judgeEnabled:z22.boolean().optional(),retentionDays:z22.number().int().min(1).max(365).optional(),notification:z22.object({email:z22.object({enabled:z22.boolean().default(!0),recipients:z22.array(z22.string().email()).min(1).max(20),includeDiffs:z22.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z22.object({monitorId:z22.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z22.string().uuid()}),RunProjectIntegrationToolRequestSchema=z22.object({tool:z22.string().min(1),input:z22.record(z22.string(),z22.unknown()),connectionAlias:z22.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z22.object({provider:z22.string().min(1),providerCredits:z22.number().nonnegative().optional(),providerCostUsd:z22.number().nonnegative().optional(),requests:z22.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z22.object({credits:z22.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()}),FirecrawlSearchToolOutputSchema=z22.object({query:z22.string(),provider:z22.literal("firecrawl"),warning:z22.string().optional(),results:z22.array(z22.object({title:z22.string(),url:z22.string(),snippet:z22.string().optional(),content:z22.string().optional(),score:z22.number().optional(),publishedAt:z22.string().optional()}))}),FirecrawlMapToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),count:z22.number(),links:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),description:z22.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),total:z22.number(),pages:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()})),warning:z22.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z22.object({cron:z22.string().optional(),text:z22.string().optional(),timezone:z22.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z22.object({id:z22.string().optional(),urls:z22.array(z22.string()).optional(),scrapeOptions:z22.record(z22.string(),z22.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z22.object({id:z22.string(),name:z22.string(),status:z22.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z22.string().nullable().optional(),lastRunAt:z22.string().nullable().optional(),currentCheckId:z22.string().nullable().optional(),targets:z22.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z22.string().nullable().optional(),judgeEnabled:z22.boolean().optional(),estimatedCreditsPerMonth:z22.number().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z22.object({id:z22.string(),monitorId:z22.string(),scheduledFor:z22.string().nullable().optional(),startedAt:z22.string().nullable().optional(),finishedAt:z22.string().nullable().optional(),estimatedCredits:z22.number().optional(),reservedCredits:z22.number().optional(),actualCredits:z22.number().optional(),billingStatus:z22.string().nullable().optional(),summary:z22.object({totalPages:z22.number().optional(),same:z22.number().optional(),changed:z22.number().optional(),new:z22.number().optional(),removed:z22.number().optional(),error:z22.number().optional()}).passthrough().optional(),error:z22.string().nullable().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitors:z22.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),deleted:z22.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),checks:z22.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),check:FirecrawlMonitorCheckOutputSchema,next:z22.string().optional()}),FirecrawlToolKeySchema=z22.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z22.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),tool:z22.string().min(1),connectionAlias:z22.string().min(1).nullable().optional(),output:z22.record(z22.string(),z22.unknown()),executedAt:z22.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z22.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z22.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z22.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z22.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z22.array(ProjectChannelCandidateDTOSchema))}});import{z as z23}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z23.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z23.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z23.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z23.object({userId:z23.string().min(1),name:z23.string(),email:z23.string().min(1),subscribed:z23.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z23.object({maxSubscribers:z23.number().int().positive(),subscriberCount:z23.number().int().nonnegative(),effectiveRecipientCount:z23.number().int().nonnegative(),currentUserSubscribed:z23.boolean(),candidates:z23.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z23.object({userIds:z23.array(z23.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z23.object({topic:UserManagedNotificationTopicSchema,enabled:z23.boolean(),source:z23.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z23.object({topics:z23.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z23.object({enabled:z23.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z23.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z23.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z23.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z23.string().nullable(),maskedEmail:z23.string().min(1),applied:z23.boolean(),expiresAt:z23.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z23.object({scheduleId:z23.string().min(1),scheduleName:z23.string(),projectId:z23.string().min(1),projectName:z23.string(),env:z23.string().min(1)}),FollowedSchedulesSchema=z23.object({schedules:z23.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z24}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z24.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=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),secretKeys:z24.array(z24.string().min(1)),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),overPolicyReasons:z24.array(z24.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500),secretKeys:z24.array(ProjectSecretKeySchema).default([]),enabled:z24.boolean().optional()}),UpdateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120).optional(),cron:z24.string().min(1).max(120).optional(),command:z24.string().min(1).max(500).optional(),secretKeys:z24.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z24.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z24.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z24.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z24.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z24.object({maxRuns:z24.number().int().positive(),retentionDays:z24.number().int().positive().nullable(),outputRetentionDays:z24.number().int().positive(),maxOutputBytes:z24.number().int().positive()}),SchedulePolicyStateSchema=z24.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z24.object({code:z24.enum(["Free","Premium"]),source:z24.enum(["cached_subscription","free_fallback"]),activeSchedules:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),concurrency:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),compute:z24.object({settledMs:z24.number().int().nonnegative(),reservedMs:z24.number().int().nonnegative(),includedMs:z24.number().int().positive(),remainingMs:z24.number().int().nonnegative(),resetsAt:z24.coerce.date()}),upgrade:z24.object({code:z24.literal("Premium"),activeSchedulesLimit:z24.number().int().positive(),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),maxConcurrentRuns:z24.number().int().positive(),computeIncludedMs:z24.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z24.array(z24.string())}),ProjectScheduleUsageSchema=z24.object({runCount:z24.number().int().nonnegative(),runsWithOutput:z24.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z24.object({id:z24.uuid(),scheduleId:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),scheduleName:z24.string().min(1),command:z24.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z24.object({id:z24.string().min(1),name:z24.string().min(1)}).nullable(),queuedAt:z24.coerce.date(),startedAt:z24.coerce.date().nullable(),finishedAt:z24.coerce.date().nullable(),exitCode:z24.number().int().nullable(),errorCode:z24.string().nullable(),error:z24.string().nullable(),outputBytes:z24.number().int().nonnegative(),outputTruncated:z24.boolean(),outputExpiresAt:z24.coerce.date().nullable(),metadataExpiresAt:z24.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z24.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z24.coerce.date().nullable(),items:z24.array(z24.object({key:z24.string().min(1),updatedAt:z24.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z24.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z24.object({trigger:z24.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z24.object({limit:z24.coerce.number().int().min(1).max(100).default(25),cursor:z24.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z24.object({items:z24.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z24.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z24.object({items:z24.array(ProjectScheduleRunDTOSchema),nextCursor:z24.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z25}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}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=z26.object({surface:SurfaceNameSchema,key:z26.string(),label:z26.string()}),InlineSchema=z26.object({text:z26.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z26.discriminatedUnion("type",[z26.object({type:z26.literal("paragraph"),content:z26.array(InlineSchema).max(24)}),z26.object({type:z26.literal("preview"),ref:DiffRefSchema,caption:z26.string().optional()}),z26.object({type:z26.literal("code"),code:z26.string(),lang:z26.string().optional(),caption:z26.string().optional()}),z26.object({type:z26.literal("risk"),level:z26.enum(["warning","error"]),content:z26.array(InlineSchema).max(24)}),z26.object({type:z26.literal("list"),items:z26.array(z26.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z26.object({headline:z26.string(),blocks:z26.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z26.object({summary:EnvDiffSummarySchema,fingerprint:z26.string(),generatedAt:z26.coerce.date(),cached:z26.boolean().optional(),credits:z26.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z27}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=z27.object({date:z27.string(),visitors:z27.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z27.object({key:z27.string(),visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z27.object({path:z27.string(),pageName:z27.string().nullable().optional(),visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z27.object({preset:z27.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z27.string(),requestedTo:z27.string(),effectiveFrom:z27.string(),effectiveTo:z27.string(),isRetentionLimited:z27.boolean(),groupBy:z27.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z27.object({date:z27.string(),content:z27.string(),updatedAt:z27.string(),updatedByUserId:z27.string()}),ProjectPageviewAnalyticsDTOSchema=z27.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative(),bounceRate:z27.number().min(0).max(100),viewsPerVisit:z27.number().nonnegative(),averageVisitDurationSeconds:z27.number().nonnegative(),visitorsSeries:z27.array(ProjectDailyVisitorsDTOSchema),topPages:z27.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z27.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z28}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z28.object({id:z28.string(),email:z28.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z28.coerce.date(),createdAt:z28.coerce.date(),inviterUserId:z28.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z28.object({id:z28.string(),token:z28.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z28.object({success:z28.boolean(),projectId:z28.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),name:z29.string(),image:z29.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z29.object({count:z29.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z29.object({counts:z29.object({signed_up:z29.int(),activated:z29.int()}),credits:z29.object({total:z29.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z29.email(),emailVerified:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z30}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z30.object({id:z30.string(),principalType:ProjectPrincipalTypeSchema,principalId:z30.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z30.coerce.date(),expiresAt:z30.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=z30.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z30.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z30.record(z30.string(),z30.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z30.object({access:z30.array(ProjectAccessItemDTOSchema),invites:z30.array(ProjectInviteDTOSchema),organization:z30.object({name:z30.string().nullable(),logo:z30.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z30.object({success:z30.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z30.object({success:z30.boolean(),projectId:z30.uuid()}))}});import{z as z31}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z31.object({publicationStatus:PublicationStatusSchema,appUrl:z31.string().nullable(),lastPublishedAt:z31.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z32}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z32.object({url:z32.url(),expiresAt:z32.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z33}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z33.string(),slug:z33.string().nullable(),logo:z33.string().nullable(),metadata:z33.record(z33.string(),z33.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z33.object({id:z33.string(),name:z33.string(),email:z33.email(),image:z33.string().nullable()}),OrganizationMemberDTOSchema=z33.object({id:z33.string(),userId:z33.string(),organizationId:z33.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z33.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z34}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z34.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z34.object({reason:CancellationReasonCodeSchema,details:z34.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z34.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z34.object({included:z34.number().optional(),unitPrice:z34.number().optional(),dailyCap:z34.number().nullable().optional()}),EntitlementsDTOSchema=z34.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z34.object({retentionDays:z34.number().int().positive(),canUseExtendedDateRanges:z34.boolean()}).optional(),history:z34.object({retentionDays:z34.number().int().positive()}).optional(),members:z34.object({canInvite:z34.boolean(),maxMembers:z34.number().int().positive().nullable()}).optional(),domains:z34.object({canUseCustomDomains:z34.boolean(),maxDomains:z34.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z34.object({id:z34.string(),external_id:z34.string(),customerId:z34.string(),planId:z34.string(),planCode:TemplateCodeSchema,currentPeriod:z34.object({start:z34.string(),end:z34.string().nullable()}),cancelAt:z34.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z34.string(),nextPaymentAt:z34.string().nullable(),baseAmount:z34.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z34.object({totalCap:z34.number(),dailyCap:z34.number(),usedTotal:z34.number()}),CreditBalanceDTOSchema=z34.object({total:z34.number(),base:z34.number(),dailyBase:z34.number(),purchases:z34.number(),awards:z34.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z34.object({total:z34.number(),nearLimit:z34.boolean(),canChat:z34.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z34.object({dailyFreeAvailable:z34.number(),monthlyAvailable:z34.number(),purchasedAvailable:z34.number(),awardedAvailable:z34.number()}),ProjectDailyCreditAllowanceDTOSchema=z34.object({periodCap:z34.number(),dailyGrant:z34.number(),usedThisPeriod:z34.number(),remainingThisPeriod:z34.number()}),ProjectCreditBalanceDTOSchema=z34.object({projectId:z34.uuid(),organizationId:z34.string(),balance:z34.object({totalAvailable:z34.number(),nearLimit:z34.boolean(),canUseAi:z34.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z34.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z34.discriminatedUnion("enabled",[z34.object({enabled:z34.literal(!0),thresholdUsd:z34.number().nonnegative(),refillAmountUsd:z34.number().nonnegative()}),z34.object({enabled:z34.literal(!1),thresholdUsd:z34.number().nonnegative().nullable(),refillAmountUsd:z34.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z34.discriminatedUnion("enabled",[z34.object({enabled:z34.literal(!0),thresholdUsd:z34.number().min(.01).multipleOf(.01),refillAmountUsd:z34.number().min(.01).multipleOf(.01)}).strict(),z34.object({enabled:z34.literal(!1),thresholdUsd:z34.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z34.object({invoiceId:z34.string(),newBalance:z34.int(),creditCount:z34.int(),amountUsd:z34.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z34.object({url:z34.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z35}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=z35.object({brand:z35.string(),last4:z35.string(),exp:z35.string(),isDefault:z35.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z36}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z36.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z36.object({type:z36.literal("renameField"),contentType:z36.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z36.object({enabled:z36.boolean()}).strict(),ContentTypeDTOSchema=z36.object({id:z36.string(),name:z36.string(),label:z36.string(),isSingleton:z36.boolean(),i18n:ContentTypeI18nSchema,fields:z36.record(z36.string(),FieldDefinitionSchema),createdAt:z36.string(),updatedAt:z36.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z36.object({contentTypes:z36.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z36.object({id:z36.string(),entryId:z36.string(),documentId:z36.string(),slug:z36.string(),locale:z36.string().optional(),createdAt:z36.string(),updatedAt:z36.string(),__fimo:z36.object({contentType:z36.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({limit:z36.number(),offset:z36.number(),total:z36.number(),hasMore:z36.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z36.object({contentType:z36.string(),count:z36.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z36.object({counts:z36.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z36.object({count:z36.number().int().nonnegative(),sourceLocale:z36.string(),targetLocale:z36.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z36.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z36.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z36.union([z36.string(),z36.number(),z36.boolean(),z36.null()]),entryWhereOperatorSchema=z36.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z36.array(entryWhereScalarSchema).optional(),$nin:z36.array(entryWhereScalarSchema).optional(),$contains:z36.string().optional(),$startsWith:z36.string().optional(),$null:z36.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z36.record(z36.string(),z36.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z36.record(z36.string(),z36.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z36.object({data:z36.record(z36.string(),z36.unknown()),locale:z36.string().min(1).optional(),documentId:z36.uuid().optional()}),entryIdsSchema=z36.array(z36.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z36.object({sql:z36.string().min(1)}),BulkCreateEntriesRequestSchema=z36.object({entries:z36.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z36.union([z36.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z36.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z36.object({updates:z36.array(z36.object({id:z36.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z36.union([z36.object({ids:entryIdsSchema,locale:z36.string().min(1).optional()}),z36.object({where:EntryWhereSchema,locale:z36.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z36.object({data:z36.array(z36.record(z36.string(),z36.unknown())),meta:z36.object({rowCount:z36.number().int().nonnegative(),truncated:z36.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({created:z36.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({updated:z36.number().int().nonnegative(),missing:z36.array(z36.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({deleted:z36.number().int().nonnegative(),missing:z36.array(z36.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z37}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z37.object({index:z37.number().int().nonnegative(),contentType:z37.string(),field:z37.string(),value:z37.string(),against:z37.enum(["stored","batch"]),ownerDocumentId:z37.uuid().optional(),ownerIndex:z37.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z37.object({code:z37.literal("unique_conflict"),message:z37.string(),conflicts:z37.array(UniqueConflictSchema),truncated:z37.boolean().optional()})}});import{z as z38}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=z38.object({kind:z38.literal("unique_conflict"),contentType:z38.string(),field:z38.string(),value:z38.string(),documentCount:z38.number().int().positive(),documentIds:z38.array(z38.uuid()),documentIdsTruncated:z38.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z38.object({code:z38.literal("schema_transition_rejected"),message:z38.string(),issues:z38.array(SchemaTransitionIssueSchema),truncated:z38.boolean().optional()})}});import{z as z39}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z39.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z39.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z39.object({field:CmsFieldNameSchema,direction:z39.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z39.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z39.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z39.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z39.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z39.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z40}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z40.object({id:z40.string(),name:z40.string()}),AssetDTOSchema=z40.object({id:z40.string(),name:z40.string(),type:AssetTypeSchema,originalFileName:z40.string().nullable(),parentId:z40.string().nullable(),mimeType:z40.string().nullable(),fileSize:z40.number().nullable(),url:z40.string().nullable(),storageKey:z40.string().nullable(),createdAt:z40.string(),updatedAt:z40.string(),altText:z40.string().nullable().optional(),caption:z40.string().nullable().optional(),aiCaption:z40.string().nullable().optional(),aiAltText:z40.string().nullable().optional(),aiTags:z40.array(z40.string()).nullable().optional(),aiPrimaryColor:z40.string().nullable().optional(),aiProcessingStatus:z40.string().nullable().optional(),width:z40.number().nullable().optional(),height:z40.number().nullable().optional(),path:z40.array(AssetPathItemSchema).optional(),hasChildren:z40.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z40.lazy(()=>z40.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z40.array(AssetDTOSchema))}});import{z as z41}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z41.object({key:z41.string(),value:z41.string().optional(),defaultValue:z41.string(),locale:z41.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z42}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=z42.object({id:z42.string(),name:z42.string(),type:z42.enum(["file","folder"]),path:z42.string(),children:z42.lazy(()=>z42.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z42.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z42.object({path:z42.string(),exists:z42.boolean(),type:z42.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z43}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=z43.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z43.object({items:z43.array(ProjectMessagePublicDTOSchema),nextCursor:z43.string().nullable()}),ChatLiveTurnDTOSchema=z43.object({invocationId:z43.string(),step:z43.enum(["preparing","working","compacting","merging"]),startedAt:z43.string()}),ChatLiveTurnStateDTOSchema=z43.object({threadId:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z43.object({id:z43.string(),role:z43.enum(["user","assistant"]),parts:z43.array(z43.unknown()),metadata:z43.record(z43.string(),z43.unknown()).nullable(),versionId:z43.string().nullable().optional(),createdAt:z43.date().transform(value=>value.toISOString()),providerMessageId:z43.string().nullable().optional(),invocationId:z43.string().nullable().optional(),invocationStatus:z43.string().nullable().optional(),invocationTerminalReason:z43.string().nullable().optional()}),ChatAttentionDTOSchema=z43.object({type:z43.literal("merge_conflict"),merge:z43.object({mergeId:z43.string().uuid(),projectId:z43.string(),fromEnv:z43.string(),toEnv:z43.string()}),publishAfterMerge:z43.boolean()}),ChatThreadMessagesPageDTOSchema=z43.object({threadId:z43.string().nullable(),title:z43.string().nullable(),messages:z43.array(ChatThreadMessageDTOSchema),nextCursor:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z43.object({kind:z43.literal("replay"),threadId:z43.string(),userMessageId:z43.string()}),ChatQueuedOutcomeDTOSchema=z43.object({kind:z43.literal("queued"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string()}),ChatBusyOutcomeDTOSchema=z43.object({kind:z43.literal("busy"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string().optional()}),ChatRefusedOutcomeDTOSchema=z43.object({kind:z43.literal("refused"),threadId:z43.string(),userMessageId:z43.string(),refusedInvocationId:z43.string(),terminalReason:z43.string()}),ChatNonStreamingOutcomeDTOSchema=z43.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z43.object({success:z43.boolean(),deletedCount:z43.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z43.object({code:z43.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z43.string()})}});import{z as z44}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z44.object({url:z44.string().url(),key:z44.string(),size:z44.number(),contentType:z44.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z45}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=z45.object({canAccess:z45.boolean(),permissions:z45.record(z45.string(),z45.boolean()),role:z45.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z46}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:z46.string().trim().default(""),sort:z46.enum(["recent","name","relevance"]).default("recent"),category:z46.string().optional()})}});import{z as z47}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z47.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z47.enum(["fimo","external"]),PaymentStatusSchema=z47.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z47.object({id:z47.string().uuid(),domain:z47.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z47.boolean(),price:z47.number().int().nullable(),renewalPrice:z47.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z47.string().nullable(),failureReason:z47.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z47.object({domain:z47.string(),available:z47.boolean(),premium:z47.boolean(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),purchaseType:z47.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z47.object({domain:z47.string(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),premium:z47.boolean(),allowedYears:z47.array(z47.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z47.object({firstName:z47.string().max(100),lastName:z47.string().max(100),companyName:z47.string().max(100).optional(),address1:z47.string().max(255),address2:z47.string().max(255).optional(),city:z47.string().max(100),state:z47.string().max(100),zip:z47.string().max(20),country:z47.string().max(2),phone:z47.string().max(30),email:z47.union([z47.string().email().max(255),z47.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z47.object({firstName:z47.string().min(1).max(100),lastName:z47.string().min(1).max(100),companyName:z47.string().max(100).optional(),address1:z47.string().min(1).max(255),address2:z47.string().max(255).optional(),city:z47.string().min(1).max(100),state:z47.string().min(1).max(100),zip:z47.string().min(1).max(20),country:z47.string().min(1).max(2),phone:z47.string().min(1).max(30),email:z47.string().email().max(255)}),SearchDomainsRequestSchema=z47.object({keyword:z47.string().min(1).max(100),tldFilter:z47.array(z47.string()).optional()}),CheckAvailabilityRequestSchema=z47.object({domains:z47.array(z47.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=z47.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z47.object({domain:DomainNameSchema,years:z47.number().int().min(1).max(10).optional().default(3),autoRenew:z47.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z47.object({autoRenew:z47.boolean().optional()}),RenewDomainRequestSchema=z47.object({years:z47.number().int().min(1).max(10).optional().default(1),autoRenew:z47.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z47.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z47.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z47.object({verified:z47.boolean(),email:z47.string().nullable(),verifyBy:z47.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z48}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z48.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=z48.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=z48.object({txtName:z48.string().nullable().optional(),txtValue:z48.string().nullable().optional(),httpUrl:z48.string().nullable().optional(),httpBody:z48.string().nullable().optional(),cname:z48.string().nullable().optional(),cnameTarget:z48.string().nullable().optional()}),SSLValidationErrorSchema=z48.object({message:z48.string()}),OwnershipVerificationSchema=z48.object({type:z48.string(),name:z48.string(),value:z48.string()}),ProjectDomainSSLDTOSchema=z48.object({status:z48.string(),method:z48.string().nullable(),type:z48.string().nullable(),validationRecords:z48.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z48.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z48.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z48.enum(["subdomain","apex"]),RedirectConfigSchema=z48.object({type:z48.literal("apex_to_www"),linkedDomainId:z48.string()}).nullable().optional(),ProjectDomainDTOSchema=z48.object({id:z48.string(),hostname:z48.string(),status:z48.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z48.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z48.string(),scdCnameTarget:z48.string().optional(),apexTargets:z48.array(z48.string()),dnsAutoConfigured:z48.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z48.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z48.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z48.object({hostname:z48.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:z48.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z48.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z48.object({success:z48.boolean(),hostname:z48.string()}))}});import{z as z49}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=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z49.object({slug:z49.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z49.object({subdomain:z49.string(),subdomainUpdatedAt:z49.coerce.date()})),SubdomainSuggestionsQuerySchema=z49.object({base:z49.string().max(100).optional(),max:z49.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z49.object({suggestions:z49.array(z49.string())}))}});import{z as z50}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z50.object({translated:z50.number().int().nonnegative(),total:z50.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z50.object({locale:z50.string(),isDefault:z50.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z50.object({defaultLocale:z50.string(),routing:z50.object({strategy:z50.literal("path-prefix"),prefixDefaultLocale:z50.boolean()}),locales:z50.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z50.object({locale:z50.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z50.object({locale:z50.string().min(1).max(40)}),ProjectLocaleMutationSchema=z50.object({locale:z50.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z50.object({locale:z50.string(),entriesDeleted:z50.number().int().nonnegative(),labelsDeleted:z50.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z51}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=z51.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z51.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=z51.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z51.number(),credits:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z52}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z52.object({options:z52.record(z52.string(),z52.unknown()),name:z52.string().optional(),parentId:z52.string().nullable().optional(),altText:z52.string().optional(),caption:z52.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z52.string().min(1).optional(),model:z52.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=z52.object({jobId:z52.string(),status:z52.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z52.string().nullable().optional(),credits:z52.number().optional(),costUsd:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z52.object({error:z52.string(),code:z52.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:z52.array(GenerationTaskIdSchema).optional(),availableModels:z52.array(z52.string()).optional(),issues:z52.array(z52.unknown()).optional()})}});import{z as z53}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=z53.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z53.object({name:z53.string(),key:z53.string(),description:z53.string(),type:FlagTypeSchema,required:z53.boolean(),defaultValue:z53.unknown().optional(),enumValues:z53.array(z53.string()).optional(),isArray:z53.boolean()}),AssetModelPriceSchema=z53.object({unitPrice:z53.number(),unit:z53.string(),confidence:z53.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z53.object({id:z53.string(),shortName:z53.string(),provider:z53.string(),source:z53.string(),modality:z53.enum(["image","video","audio"]),tags:z53.array(z53.string()),displayName:z53.string(),description:z53.string(),flags:z53.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z53.object({model:z53.string(),costUsd:z53.number(),credits:z53.number(),billingMode:z53.enum(["fimo-credits","provider-account"]),confidence:z53.enum(["exact","estimated","metered"]),basis:z53.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z54}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=z54.object({tourId:z54.string(),version:z54.string(),status:z54.string(),completedAt:z54.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z54.array(UserTourDTOSchema))}});import{z as z55}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=z55.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z55.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z55.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z55.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z55.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z55.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z55.enum(["user","agent","system"]),SupportReportTagSchema=z55.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z55.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z55.object({organization:z55.object({id:z55.string().trim().min(1).max(255),name:z55.string().trim().max(240).optional()}),project:z55.object({id:z55.uuid(),name:z55.string().trim().max(240).optional(),createdAt:z55.coerce.date().optional()}).optional(),environment:z55.string().trim().max(255).optional(),clientVersion:z55.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z55.object({message:z55.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z55.string().trim().max(200).optional(),limit:z55.coerce.number().int().min(1).max(100).default(50),offset:z55.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z55.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z55.uuid().nullable().optional(),note:z55.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=z55.object({message:z55.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z55.object({kind:SupportReportLinkKindSchema,label:z55.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z55.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z55.object({kind:SupportReportActorKindSchema,id:z55.string().nullable(),name:z55.string().nullable()}),SupportReportLinkDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportLinkKindSchema,label:z55.string(),url:SupportReportHttpUrlSchema,externalId:z55.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportEventKindSchema,body:z55.string().nullable(),metadata:z55.record(z55.string(),z55.unknown()),actor:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z55.object({id:z55.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z55.array(z55.string()),source:SupportReportSourceSchema,message:z55.string(),reporter:z55.object({id:z55.string().nullable(),name:z55.string().nullable(),email:z55.string().nullable()}),organization:z55.object({id:z55.string().nullable(),name:z55.string()}),project:z55.object({id:z55.uuid().nullable(),name:z55.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z55.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z55.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}).nullable(),duplicateOfReportId:z55.uuid().nullable(),resolvedAt:z55.coerce.date().nullable(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z55.string().nullable(),clientVersion:z55.string().nullable(),links:z55.array(SupportReportLinkDTOSchema),events:z55.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z55.object({reports:z55.array(SupportReportSummaryDTOSchema),total:z55.number().int().nonnegative(),statusCounts:z55.object({new:z55.number().int().nonnegative(),in_progress:z55.number().int().nonnegative(),waiting:z55.number().int().nonnegative(),resolved:z55.number().int().nonnegative(),duplicate:z55.number().int().nonnegative(),irrelevant:z55.number().int().nonnegative(),ignored:z55.number().int().nonnegative()}),limit:z55.number().int().positive(),offset:z55.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z55.object({id:z55.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z55.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z56}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=z56.iso.datetime({offset:!0}).pipe(z56.coerce.date()),OpsRecentChatInputSchema=z56.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z56.string().trim().min(1).max(255).optional(),limit:z56.coerce.number().int().min(1).max(200).default(100),cursor:z56.string().trim().min(1).max(2e3).optional(),slim:z56.boolean().default(!0),reason:z56.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=z56.object({id:z56.string(),threadId:z56.string(),providerMessageId:z56.string().nullable(),invocationId:z56.string().nullable(),env:z56.string().nullable(),role:z56.string(),parts:z56.array(z56.record(z56.string(),z56.unknown())),metadata:z56.object({status:z56.string().optional(),traceUrl:z56.string().optional(),externalFileChanges:z56.array(z56.unknown()).optional()}),stats:z56.object({toolCount:z56.number().int().nonnegative(),failedToolCount:z56.number().int().nonnegative()}),createdAt:z56.iso.datetime({offset:!0}),project:z56.object({id:z56.string(),name:z56.string(),displayName:z56.string().nullable(),organizationId:z56.string().nullable()})}),OpsRecentChatResponseSchema=z56.object({target:z56.object({backendProfile:OpsBackendProfileSchema,projectEnv:z56.string().nullable()}),window:z56.object({from:z56.iso.datetime({offset:!0}),to:z56.iso.datetime({offset:!0})}),messages:z56.object({items:z56.array(OpsRecentChatMessageSchema),nextCursor:z56.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z57}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=z57.object({backendProfile:OpsBackendProfileSchema,provider:z57.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z57.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z57.object({backendProfile:OpsBackendProfileSchema,provider:z57.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z57.literal(!1),reason:z57.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({versionId:z58.uuid(),name:z58.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}from"zod";var PREVIEW_FEATURE_REGISTRY,previewFeatureKeys,PreviewFeatureDTOSchema,PreviewFeatureDTO,PreviewFeatureResponseSchema,PreviewFeatureListResponseSchema,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();init_response();PREVIEW_FEATURE_REGISTRY={"fimo-2":{key:"fimo-2",defaultEnabled:!1}},previewFeatureKeys=Object.keys(PREVIEW_FEATURE_REGISTRY),PreviewFeatureDTOSchema=z59.object({key:z59.enum(previewFeatureKeys),enabled:z59.boolean(),dismissed:z59.boolean().default(!1),interacted:z59.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z59.array(PreviewFeatureDTOSchema))}});import{z as z60}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z60.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z60.object({total:z60.number(),base:z60.number(),purchases:z60.number(),awards:z60.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z60.object({id:z60.string(),name:z60.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z60.object({type:z60.string(),brand:z60.string().nullable(),last4:z60.string().nullable(),expirationDate:z60.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z60.object({currency:z60.string(),nextPaymentAmount:z60.number().nullable(),nextPaymentAt:z60.string().nullable(),billingInterval:z60.string().nullable(),totalAmount:z60.number().nullable(),discountAmount:z60.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z60.object({id:z60.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z60.string().nullable(),currentPeriodEndsAt:z60.string().nullable(),renewsAt:z60.string().nullable(),cancelAt:z60.string().nullable(),renewAutomatically:z60.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z60.object({type:z60.enum(["low_balance","critical_balance","approaching_limit"]),message:z60.string(),estimatedPromptsRemaining:z60.number().nullable(),avgCostPerPrompt:z60.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z60.object({monthlyCredits:z60.number().nullable(),usedThisPeriod:z60.number(),remainingThisPeriod:z60.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z60.object({organizationId:z60.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z60.string().nullable(),tenureDays:z60.number().int().nonnegative(),capturedAt:z60.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z60.object({hasSubscription:z60.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z60.number().nullable(),alerts:z60.array(CreditAlertDTOSchema),portalUrl:z60.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z60.object({creditCount:z60.number().int().positive(),expiresAt:z60.string().datetime().nullable().optional(),message:z60.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z60.literal("free"),amountCents:z60.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z60.literal("purchase"),amountCents:z60.number().int().positive()}),CreditTopupRequestDTOSchema=z60.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z60.object({success:z60.boolean(),transactionId:z60.string().nullable(),newBalance:z60.number(),creditCount:z60.number(),type:z60.enum(["free","purchase"]),invoiceId:z60.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z61}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=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),periodStart:z61.string().nullable(),periodEnd:z61.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().email().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().email().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z61.array(UsageByUserForProjectDTOSchema),timeline:z61.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z61.object({summary:UsageSummaryDTOSchema,byProject:z61.array(UsageByProjectDTOSchema),byUser:z61.array(UsageByUserDTOSchema),timeline:z61.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z62}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=z62.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z62.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z62.object({startDate:z62.string().optional(),endDate:z62.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z62.coerce.number().int().positive().default(1),limit:z62.coerce.number().int().positive().max(100).default(20),sortBy:z62.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z62.string().optional(),activeOnly:z62.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z62.object({totalCredits:z62.number(),totalCostUsd:z62.number(),totalMessages:z62.number(),avgCostPerMessage:z62.number(),avgCreditsPerMessage:z62.number(),periodStart:z62.string(),periodEnd:z62.string(),creditsChange:z62.number().nullable(),costChange:z62.number().nullable(),messagesChange:z62.number().nullable(),unattributedCredits:z62.number(),unattributedCostUsd:z62.number(),unattributedMessages:z62.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z62.object({date:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z62.object({organizationId:z62.string(),organizationName:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),userCount:z62.number(),projectCount:z62.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z62.object({userId:z62.string(),userName:z62.string().nullable(),userEmail:z62.string().nullable(),userImage:z62.string().nullable(),organizationId:z62.string().nullable(),organizationName:z62.string().nullable(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),projectCount:z62.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z62.object({projectId:z62.string(),projectName:z62.string(),projectDisplayName:z62.string().nullable(),organizationId:z62.string(),organizationName:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),userCount:z62.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z62.object({id:z62.string(),name:z62.string(),value:z62.number(),percentage:z62.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z62.object({day:z62.number(),hour:z62.number(),value:z62.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z62.object({summary:UsageOverviewSummaryDTOSchema,timeline:z62.array(UsageTimelinePointDTOSchema),topOrganizations:z62.array(OrganizationUsageRowDTOSchema),topUsers:z62.array(UserUsageRowDTOSchema),topProjects:z62.array(ProjectUsageRowDTOSchema),creditDistribution:z62.array(UsageDistributionItemDTOSchema),userDistribution:z62.array(UsageDistributionItemDTOSchema),heatmap:z62.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z62.object({page:z62.number(),limit:z62.number(),totalItems:z62.number(),totalPages:z62.number(),hasMore:z62.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z62.object({organizations:z62.array(OrganizationUsageRowDTOSchema),top:z62.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z62.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z62.object({users:z62.array(ExtendedUserUsageRowDTOSchema),top:z62.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z62.string(),ownerName:z62.string().nullable(),ownerEmail:z62.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z62.object({projects:z62.array(ExtendedProjectUsageRowDTOSchema),top:z62.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z62.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z62.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z62.object({credits:z62.number(),costUsd:z62.number(),messages:z62.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z62.object({id:z62.string(),name:z62.string(),createdAt:z62.string(),memberCount:z62.number(),projectCount:z62.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z62.object({id:z62.string(),name:z62.string().nullable(),email:z62.string(),image:z62.string().nullable(),createdAt:z62.string(),organizationCount:z62.number(),projectCount:z62.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z62.object({id:z62.string(),name:z62.string(),displayName:z62.string().nullable(),createdAt:z62.string(),organizationId:z62.string(),organizationName:z62.string(),ownerId:z62.string(),ownerName:z62.string().nullable(),ownerEmail:z62.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z63}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=z63.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z63.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z63.object({command:z63.string().min(1).max(1e4),cwd:z63.string().optional(),projectEnv:EnvSchema.optional(),env:z63.record(z63.string(),z63.string()).optional(),name:z63.string().optional(),waitForCompletion:z63.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z63.object({identifier:z63.string(),status:SandboxProcessStatusSchema,command:z63.string().optional(),startedAt:z63.string().optional(),exitCode:z63.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z63.object({processes:z63.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z63.object({processId:z63.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z63.object({success:z63.boolean(),message:z63.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z64}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path49,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path49} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
43
43
 
44
44
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
45
45
 
@@ -183,7 +183,7 @@ ${end2.comment}`:end2.comment}this.doc.range[2]=end2.offset;break}default:this.e
183
183
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
184
184
  `,nl)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(map2){let it2=map2.items[map2.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,it2.value){let end2="end"in it2.value?it2.value.end:void 0;(Array.isArray(end2)?end2[end2.length-1]:void 0)?.type==="comment"?end2?.push(this.sourceToken):map2.items.push({start:[this.sourceToken]})}else it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)map2.items.push({start:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else{if(this.atIndentedComment(it2.start,map2.indent)){let end2=map2.items[map2.items.length-2]?.value?.end;if(Array.isArray(end2)){Array.prototype.push.apply(end2,it2.start),end2.push(this.sourceToken),map2.items.pop();return}}it2.start.push(this.sourceToken)}return}if(this.indent>=map2.indent){let atMapIndent=!this.onKeyLine&&this.indent===map2.indent,atNextItem=atMapIndent&&(it2.sep||it2.explicitKey)&&this.type!=="seq-item-ind",start=[];if(atNextItem&&it2.sep&&!it2.value){let nl=[];for(let i=0;i<it2.sep.length;++i){let st2=it2.sep[i];switch(st2.type){case"newline":nl.push(i);break;case"space":break;case"comment":st2.indent>map2.indent&&(nl.length=0);break;default:nl.length=0}}nl.length>=2&&(start=it2.sep.splice(nl[1]))}switch(this.type){case"anchor":case"tag":atNextItem||it2.value?(start.push(this.sourceToken),map2.items.push({start}),this.onKeyLine=!0):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"explicit-key-ind":!it2.sep&&!it2.explicitKey?(it2.start.push(this.sourceToken),it2.explicitKey=!0):atNextItem||it2.value?(start.push(this.sourceToken),map2.items.push({start,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(it2.explicitKey)if(it2.sep)if(it2.value)map2.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(it2.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(it2.key)&&!includesToken(it2.sep,"newline")){let start2=getFirstKeyStartProps(it2.start),key=it2.key,sep2=it2.sep;sep2.push(this.sourceToken),delete it2.key,delete it2.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep:sep2}]})}else start.length>0?it2.sep=it2.sep.concat(start,this.sourceToken):it2.sep.push(this.sourceToken);else if(includesToken(it2.start,"newline"))Object.assign(it2,{key:null,sep:[this.sourceToken]});else{let start2=getFirstKeyStartProps(it2.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}else it2.sep?it2.value||atNextItem?map2.items.push({start,key:null,sep:[this.sourceToken]}):includesToken(it2.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs47=this.flowScalar(this.type);atNextItem||it2.value?(map2.items.push({start,key:fs47,sep:[]}),this.onKeyLine=!0):it2.sep?this.stack.push(fs47):(Object.assign(it2,{key:fs47,sep:[]}),this.onKeyLine=!0);return}default:{let bv=this.startBlockValue(map2);if(bv){if(bv.type==="block-seq"){if(!it2.explicitKey&&it2.sep&&!includesToken(it2.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else atMapIndent&&map2.items.push({start});this.stack.push(bv);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(seq){let it2=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it2.value){let end2="end"in it2.value?it2.value.end:void 0;(Array.isArray(end2)?end2[end2.length-1]:void 0)?.type==="comment"?end2?.push(this.sourceToken):seq.items.push({start:[this.sourceToken]})}else it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it2.start,seq.indent)){let end2=seq.items[seq.items.length-2]?.value?.end;if(Array.isArray(end2)){Array.prototype.push.apply(end2,it2.start),end2.push(this.sourceToken),seq.items.pop();return}}it2.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it2.value||this.indent<=seq.indent)break;it2.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;it2.value||includesToken(it2.start,"seq-item-ind")?seq.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return}if(this.indent>seq.indent){let bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop(),yield*this.step()}*flowCollection(fc){let it2=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do yield*this.pop(),top=this.peek(1);while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!it2||it2.sep?fc.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return;case"map-value-ind":!it2||it2.value?fc.items.push({start:[],key:null,sep:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!it2||it2.value?fc.items.push({start:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs47=this.flowScalar(this.type);!it2||it2.value?fc.items.push({start:[],key:fs47,sep:[]}):it2.sep?this.stack.push(fs47):Object.assign(it2,{key:fs47,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}let bv=this.startBlockValue(fc);bv?this.stack.push(bv):(yield*this.pop(),yield*this.step())}else{let parent2=this.peek(2);if(parent2.type==="block-map"&&(this.type==="map-value-ind"&&parent2.indent===fc.indent||this.type==="newline"&&!parent2.items[parent2.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&parent2.type!=="flow-collection"){let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);fixFlowSeqItems(fc);let sep2=fc.end.splice(1,fc.end.length);sep2.push(this.sourceToken);let map2={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep2}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map2}else yield*this.lineEnd(fc)}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
185
185
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
186
- `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser2}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer(),Document2=require_Document(),errors=require_errors(),log=require_log(),identity2=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse13(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse13,"parse");function stringify5(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify5,"stringify");exports2.parse=parse13;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify5}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer(),Document2=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit2=require_visit();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import fs5 from"node:fs";import path5 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function getTemplatePath(framework=DEFAULT_TEMPLATE){return path5.resolve(PACKAGE_ROOT,"templates",framework)}function readReleaseMeta(){try{let raw=fs5.readFileSync(RELEASE_FILE2,"utf8"),parsed=JSON.parse(raw);return{source:parsed.source==="npm"||parsed.source==="dev"?parsed.source:null}}catch{return{source:null}}}function readCliSemver(){try{let raw=fs5.readFileSync(PACKAGE_JSON_FILE,"utf8"),parsed=JSON.parse(raw);if(typeof parsed.version=="string"&&parsed.version.length>0)return parsed.version}catch{}return null}function computeFimoPin(meta,semver,options={}){return meta.source==="npm"&&semver?semver:(meta.source==="dev"||meta.source===null)&&options.devPackageRoot?`file:${options.devPackageRoot}`:null}function resolveFimoPin(options={}){return computeFimoPin(readReleaseMeta(),readCliSemver(),options)}function readDevReleaseVersion(startPath=PACKAGE_ROOT){let devJsonPath=findDevJson(startPath);if(!devJsonPath)return{devJsonPath:null,version:null};let parsed;try{parsed=JSON.parse(fs5.readFileSync(devJsonPath,"utf8"))}catch{throw new Error(`Invalid JSON in ${devJsonPath}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`)}if(typeof parsed.version!="string"||parsed.version.trim().length===0)throw new Error(`Missing "version" in ${devJsonPath}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`);return{devJsonPath,version:parsed.version.trim()}}function findDevJson(startPath){let current=startPath;for(;;){let candidate=path5.join(current,".fimo","dev.json");if(fs5.existsSync(candidate))return candidate;let parent2=path5.dirname(current);if(parent2===current)return null;current=parent2}}function rewriteFimoDep(pkg,pin=resolveFimoPin()){if(!pin)return!1;let changed=!1;for(let field of["dependencies","devDependencies"]){let deps=pkg[field];if(!deps)continue;let current=deps.fimo;if(typeof current!="string")continue;let looksLikeLegacyR2=current.includes("r2.dev/cli/fimo-"),looksLikeLocalFile=current.startsWith("file:"),looksLikeSemver=/^[\^~]?\d+\.\d+\.\d+/.test(current);(looksLikeLegacyR2||looksLikeLocalFile||looksLikeSemver||(current==="latest"||current==="staging"||current==="experimental"))&&current!==pin&&(deps.fimo=pin,changed=!0)}return changed}var MODULE_DIR,PACKAGE_ROOT,RELEASE_FILE2,PACKAGE_JSON_FILE,TEMPLATE_FRAMEWORKS,DEFAULT_TEMPLATE,init_templates=__esm({"src/runtime/templates.ts"(){MODULE_DIR=path5.dirname(fileURLToPath3(import.meta.url)),PACKAGE_ROOT=path5.resolve(MODULE_DIR,"..",".."),RELEASE_FILE2=path5.join(PACKAGE_ROOT,"release.json"),PACKAGE_JSON_FILE=path5.join(PACKAGE_ROOT,"package.json"),TEMPLATE_FRAMEWORKS=["react-router","nextjs","sveltekit"],DEFAULT_TEMPLATE="react-router";__name(getTemplatePath,"getTemplatePath");__name(readReleaseMeta,"readReleaseMeta");__name(readCliSemver,"readCliSemver");__name(computeFimoPin,"computeFimoPin");__name(resolveFimoPin,"resolveFimoPin");__name(readDevReleaseVersion,"readDevReleaseVersion");__name(findDevJson,"findDevJson");__name(rewriteFimoDep,"rewriteFimoDep")}});import fs6 from"node:fs";import path6 from"node:path";function resolveTemplateFramework(value){let framework=value===void 0?DEFAULT_TEMPLATE:value.trim().toLowerCase();if(!TEMPLATE_FRAMEWORKS.includes(framework))throw new TemplateFrameworkError(`Unknown project framework "${value}". Use one of: ${TEMPLATE_FRAMEWORKS.join(", ")}.`);return framework}function resolveTemplateRoot(framework=DEFAULT_TEMPLATE){let templateRoot=getTemplatePath(framework);if(fs6.existsSync(path6.join(templateRoot,"package.json")))return templateRoot;throw new Error(`Bundled ${framework} template not found at ${templateRoot}.`)}function resolveAgentTemplatesRoot(){if(fs6.existsSync(AGENT_TEMPLATES_ROOT))return AGENT_TEMPLATES_ROOT;throw new Error(`Bundled agent templates dir not found at ${AGENT_TEMPLATES_ROOT}.`)}function resolveAgentTemplate(name){let dir=path6.join(resolveAgentTemplatesRoot(),name);if(!fs6.existsSync(dir))throw new Error(`Agent template '${name}' not found.`);return dir}function listAgentTemplates(){let root2=(()=>{try{return resolveAgentTemplatesRoot()}catch{return null}})();if(!root2)return[];let entries2=fs6.readdirSync(root2,{withFileTypes:!0}),out=[];for(let entry of entries2){if(!entry.isDirectory())continue;let goalPath=path6.join(root2,entry.name,"GOAL.md"),goalFirstLine="";try{goalFirstLine=(fs6.readFileSync(goalPath,"utf8").split(`
186
+ `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser2}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer(),Document2=require_Document(),errors=require_errors(),log=require_log(),identity2=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse13(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse13,"parse");function stringify5(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify5,"stringify");exports2.parse=parse13;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify5}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer(),Document2=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit2=require_visit();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import fs5 from"node:fs";import path5 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function getTemplatePath(framework=DEFAULT_TEMPLATE){return path5.resolve(PACKAGE_ROOT,"templates",framework)}function readReleaseMeta(){try{let raw=fs5.readFileSync(RELEASE_FILE2,"utf8"),parsed=JSON.parse(raw);return{source:parsed.source==="npm"||parsed.source==="dev"?parsed.source:null}}catch{return{source:null}}}function readCliSemver(){try{let raw=fs5.readFileSync(PACKAGE_JSON_FILE,"utf8"),parsed=JSON.parse(raw);if(typeof parsed.version=="string"&&parsed.version.length>0)return parsed.version}catch{}return null}function computeFimoPin(meta,semver,options={}){return meta.source==="npm"&&semver?semver:(meta.source==="dev"||meta.source===null)&&options.devPackageRoot?`file:${options.devPackageRoot}`:null}function resolveFimoPin(options={}){return computeFimoPin(readReleaseMeta(),readCliSemver(),options)}function readDevReleaseVersion(startPath=PACKAGE_ROOT){let devJsonPath=findDevJson(startPath);if(!devJsonPath)return{devJsonPath:null,version:null};let parsed;try{parsed=JSON.parse(fs5.readFileSync(devJsonPath,"utf8"))}catch{throw new Error(`Invalid JSON in ${devJsonPath}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`)}if(typeof parsed.version!="string"||parsed.version.trim().length===0)throw new Error(`Missing "version" in ${devJsonPath}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`);return{devJsonPath,version:parsed.version.trim()}}function findDevJson(startPath){let current=startPath;for(;;){let candidate=path5.join(current,".fimo","dev.json");if(fs5.existsSync(candidate))return candidate;let parent2=path5.dirname(current);if(parent2===current)return null;current=parent2}}function rewriteFimoDep(pkg,pin=resolveFimoPin()){if(!pin)return!1;let changed=!1;for(let field of["dependencies","devDependencies"]){let deps=pkg[field];if(!deps)continue;let current=deps.fimo;if(typeof current!="string")continue;let looksLikeLegacyR2=current.includes("r2.dev/cli/fimo-"),looksLikeLocalFile=current.startsWith("file:"),looksLikeSemver=/^[\^~]?\d+\.\d+\.\d+/.test(current);(looksLikeLegacyR2||looksLikeLocalFile||looksLikeSemver||(current==="latest"||current==="staging"||current==="experimental"))&&current!==pin&&(deps.fimo=pin,changed=!0)}return changed}var MODULE_DIR,PACKAGE_ROOT,RELEASE_FILE2,PACKAGE_JSON_FILE,TEMPLATE_FRAMEWORKS,DEFAULT_TEMPLATE,init_templates=__esm({"src/runtime/templates.ts"(){MODULE_DIR=path5.dirname(fileURLToPath3(import.meta.url)),PACKAGE_ROOT=path5.resolve(MODULE_DIR,"..",".."),RELEASE_FILE2=path5.join(PACKAGE_ROOT,"release.json"),PACKAGE_JSON_FILE=path5.join(PACKAGE_ROOT,"package.json"),TEMPLATE_FRAMEWORKS=["react-router","astro","nextjs","sveltekit"],DEFAULT_TEMPLATE="react-router";__name(getTemplatePath,"getTemplatePath");__name(readReleaseMeta,"readReleaseMeta");__name(readCliSemver,"readCliSemver");__name(computeFimoPin,"computeFimoPin");__name(resolveFimoPin,"resolveFimoPin");__name(readDevReleaseVersion,"readDevReleaseVersion");__name(findDevJson,"findDevJson");__name(rewriteFimoDep,"rewriteFimoDep")}});import fs6 from"node:fs";import path6 from"node:path";function resolveTemplateFramework(value){let framework=value===void 0?DEFAULT_TEMPLATE:value.trim().toLowerCase();if(!TEMPLATE_FRAMEWORKS.includes(framework))throw new TemplateFrameworkError(`Unknown project framework "${value}". Use one of: ${TEMPLATE_FRAMEWORKS.join(", ")}.`);return framework}function resolveTemplateRoot(framework=DEFAULT_TEMPLATE){let templateRoot=getTemplatePath(framework);if(fs6.existsSync(path6.join(templateRoot,"package.json")))return templateRoot;throw new Error(`Bundled ${framework} template not found at ${templateRoot}.`)}function resolveAgentTemplatesRoot(){if(fs6.existsSync(AGENT_TEMPLATES_ROOT))return AGENT_TEMPLATES_ROOT;throw new Error(`Bundled agent templates dir not found at ${AGENT_TEMPLATES_ROOT}.`)}function resolveAgentTemplate(name){let dir=path6.join(resolveAgentTemplatesRoot(),name);if(!fs6.existsSync(dir))throw new Error(`Agent template '${name}' not found.`);return dir}function listAgentTemplates(){let root2=(()=>{try{return resolveAgentTemplatesRoot()}catch{return null}})();if(!root2)return[];let entries2=fs6.readdirSync(root2,{withFileTypes:!0}),out=[];for(let entry of entries2){if(!entry.isDirectory())continue;let goalPath=path6.join(root2,entry.name,"GOAL.md"),goalFirstLine="";try{goalFirstLine=(fs6.readFileSync(goalPath,"utf8").split(`
187
187
  `).find(l=>l.trim().length>0)??"").replace(/^#+\s*/,"").trim()}catch{}out.push({name:entry.name,goalFirstLine})}return out.sort((a,b)=>a.name.localeCompare(b.name))}async function copyAgentTemplate(templateRoot,targetDir){if(fs6.existsSync(targetDir))throw new Error(`Target directory '${targetDir}' already exists.`);fs6.mkdirSync(targetDir,{recursive:!0}),await copyTree(templateRoot,targetDir)}async function copyTemplate(templateRoot,targetDir){fs6.mkdirSync(targetDir,{recursive:!0}),await copyTree(templateRoot,targetDir),pinFimoDependency(targetDir)}function pinFimoDependency(targetDir){let pin=resolveFimoPin({devPackageRoot:CLI_ROOT});if(!pin)return;let pkgPath=path6.join(targetDir,"package.json");if(!fs6.existsSync(pkgPath))return;let pkg=JSON.parse(fs6.readFileSync(pkgPath,"utf8"));rewriteFimoDep(pkg,pin)&&(fs6.writeFileSync(pkgPath,JSON.stringify(pkg,null,2)+`
188
188
  `),fs6.rmSync(path6.join(targetDir,"pnpm-lock.yaml"),{force:!0}))}async function copyTree(srcDir,destDir){let entries2=fs6.readdirSync(srcDir,{withFileTypes:!0});for(let entry of entries2){if(EXCLUDED_DIRS.has(entry.name))continue;let srcPath=path6.join(srcDir,entry.name),destName=entry.name==="_gitignore"?".gitignore":entry.name,destPath=path6.join(destDir,destName);entry.isDirectory()?(fs6.mkdirSync(destPath,{recursive:!0}),await copyTree(srcPath,destPath)):entry.isFile()&&fs6.copyFileSync(srcPath,destPath)}}function writePerAgentVariants(targetDir,agents,agentsMdContent){let result={perAgentVariants:[],perAgentVariantsSkipped:[]},selected=new Set(agents);function writeIfMissing(relativePath,content2){let fullPath=path6.join(targetDir,relativePath);if(fs6.existsSync(fullPath)){result.perAgentVariantsSkipped.push(relativePath);return}fs6.mkdirSync(path6.dirname(fullPath),{recursive:!0}),fs6.writeFileSync(fullPath,content2),result.perAgentVariants.push(relativePath)}if(__name(writeIfMissing,"writeIfMissing"),selected.has("claude-code")&&writeIfMissing("CLAUDE.md",agentsMdContent),selected.has("cursor")){let cursorContent=`---
189
189
  description: Fimo project rules
@@ -206,13 +206,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
206
206
  `).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
207
207
  `);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
208
208
  `).slice(o);this.output.write(a.join(`
209
- `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z69,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z69=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
209
+ `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z70,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z70=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
210
210
  `);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y"),ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
211
211
  `:""}${o}
212
212
  `,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
213
- ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z69)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
213
+ ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z70)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
214
214
  ${t("cyan",d2)} `:`
215
- `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z69)} ${s}`}
215
+ `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z70)} ${s}`}
216
216
  ${$2}
217
217
  `}}}}).prompt()},"ot"),O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
218
218
  `);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
@@ -238,7 +238,7 @@ ${o}
238
238
  `}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
239
239
  `)?e.split(`
240
240
  `).map(s=>i(s)).join(`
241
- `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z69)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
241
+ `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z70)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
242
242
  `:""}${n}
243
243
  `;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
244
244
  ${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
@@ -255,7 +255,7 @@ ${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`
255
255
  ${c2}
256
256
  `}}}}).prompt(),"Ot")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});import fs14 from"node:fs";import path16 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiBaseUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl,...tenantApiBaseUrl?{tenantApiBaseUrl}:{}},layout=resolveProjectLayoutPaths(targetDir),projectPath=path16.join(targetDir,layout.project);fs14.mkdirSync(path16.dirname(projectPath),{recursive:!0}),writeIfChanged(projectPath,`${JSON.stringify(fimoJson,null,2)}
257
257
  `)}function seedSiteName(args){let{targetDir,project}=args,configPath=resolveProjectConfigPath(targetDir);if(fs14.existsSync(configPath))try{let original=fs14.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{},existingName=typeof seo.siteName=="string"?seo.siteName:"";if(!existingName.trim()||existingName===STARTER_SITE_NAME){let initialSiteName=project.displayName?.trim()||project.name;config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
258
- `)}}catch{}}function writeIfChanged(filePath,content2){fs14.existsSync(filePath)&&fs14.readFileSync(filePath,"utf-8")===content2||fs14.writeFileSync(filePath,content2)}var STARTER_SITE_NAME,init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){init_project();STARTER_SITE_NAME="Fimo Starter Site";__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(seedSiteName,"seedSiteName");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs15 from"node:fs";import path17 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or env not found.":error instanceof Error?error.message:String(error)}function chooseCloneEnv(envs,requestedEnv){return requestedEnv?envs.find(env=>env.env===requestedEnv)??null:envs.find(env=>env.env===DEFAULT_ENV)??envs[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){if(currentMode().format==="json")return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint:PICKER_HINT};if(!isInteractive())return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint:PICKER_HINT};if(!args.activeOrganizationId)return{status:"error",code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."};let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),{status:"error",code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}}if(projects2.length===0)return{status:"empty",message:"No projects in the active organization yet."};let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?{status:"cancelled"}:{status:"selected",projectId:selected}}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedEnv,apiUrl}=args,firstEnv=requestedEnv??DEFAULT_ENV;try{return{ok:!0,env:firstEnv,remote:await api.withEnv(firstEnv).getGitRemote(projectId,firstEnv)}}catch(firstError){if(requestedEnv||!isNotFound(firstError))throw firstError;let envs;try{envs=await api.listEnvs(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallbackEnv=chooseCloneEnv(envs,void 0);if(!fallbackEnv)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable envs.",hint:"Create an env before cloning this project."};if(fallbackEnv.env===firstEnv)throw firstError;return{ok:!0,env:fallbackEnv.env,remote:await api.withEnv(fallbackEnv.env).getGitRemote(projectId,fallbackEnv.env)}}}async function cloneProject(args){let{api,cfg,projectId,dir,env:requestedEnv}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,env;try{let resolved=await resolveRemote({api,projectId,requestedEnv,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,env}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path17.resolve(dir??defaultDirectoryName(project));if(fs15.existsSync(targetDir)&&fs15.readdirSync(targetDir).length>0){let name=path17.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path17.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,env,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,env,branch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg;if(!projectId){let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});switch(picked.status){case"selected":projectId=picked.projectId;break;case"cancelled":ui.info({command:"clone",message:"Cancelled."});return;case"empty":ui.info({command:"clone",message:picked.message});return;case"error":ui.error({command:"clone",code:picked.code,message:picked.message,...picked.hint?{hint:picked.hint}:{}});return}}currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,env,branch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env,branch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,PICKER_HINT,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneEnv,"chooseCloneEnv");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");PICKER_HINT="Pass a project ID explicitly, e.g. `fimo clone <projectId>`.";__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});import path19 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectEnvironmentCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path19.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new EnvironmentCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new EnvironmentCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new EnvironmentCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new EnvironmentCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectEnvironmentCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new EnvironmentCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectEnvironmentCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new EnvironmentCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new EnvironmentCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectEnvironmentCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch(args.cwd);if(localBranch!==args.remoteBranch)throw new EnvironmentCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectEnvironmentCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new EnvironmentCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}var EnvironmentCheckoutError,init_environment_checkout=__esm({"src/cli/utils/environment-checkout.ts"(){init_git();EnvironmentCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="EnvironmentCheckoutError"}static{__name(this,"EnvironmentCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectEnvironmentCheckout,"inspectEnvironmentCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(prepareDeployCheckout,"prepareDeployCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject(subject){return typeof subject=="object"&&subject!==null}__name(isObject,"isObject");function toArray2(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray2,"toArray");function extend(target,source){var index2,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index2=0,length=sourceKeys.length;index2<length;index2+=1)key=sourceKeys[index2],target[key]=source[key];return target}__name(extend,"extend");function repeat(string2,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string2;return result}__name(repeat,"repeat");function isNegativeZero(number2){return number2===0&&Number.NEGATIVE_INFINITY===1/number2}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject;module2.exports.toArray=toArray2;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end2,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
258
+ `)}}catch{}}function writeIfChanged(filePath,content2){fs14.existsSync(filePath)&&fs14.readFileSync(filePath,"utf-8")===content2||fs14.writeFileSync(filePath,content2)}var STARTER_SITE_NAME,init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){init_project();STARTER_SITE_NAME="Fimo Starter Site";__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(seedSiteName,"seedSiteName");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs15 from"node:fs";import path17 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or env not found.":error instanceof Error?error.message:String(error)}function chooseCloneEnv(envs,requestedEnv){return requestedEnv?envs.find(env=>env.env===requestedEnv)??null:envs.find(env=>env.env===DEFAULT_ENV)??envs[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){if(currentMode().format==="json")return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint:PICKER_HINT};if(!isInteractive())return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint:PICKER_HINT};if(!args.activeOrganizationId)return{status:"error",code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."};let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),{status:"error",code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}}if(projects2.length===0)return{status:"empty",message:"No projects in the active organization yet."};let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?{status:"cancelled"}:{status:"selected",projectId:selected}}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedEnv,apiUrl}=args,firstEnv=requestedEnv??DEFAULT_ENV;try{return{ok:!0,env:firstEnv,remote:await api.withEnv(firstEnv).getGitRemote(projectId,firstEnv)}}catch(firstError){if(requestedEnv||!isNotFound(firstError))throw firstError;let envs;try{envs=await api.listEnvs(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallbackEnv=chooseCloneEnv(envs,void 0);if(!fallbackEnv)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable envs.",hint:"Create an env before cloning this project."};if(fallbackEnv.env===firstEnv)throw firstError;return{ok:!0,env:fallbackEnv.env,remote:await api.withEnv(fallbackEnv.env).getGitRemote(projectId,fallbackEnv.env)}}}async function cloneProject(args){let{api,cfg,projectId,dir,env:requestedEnv}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,env;try{let resolved=await resolveRemote({api,projectId,requestedEnv,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,env}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path17.resolve(dir??defaultDirectoryName(project));if(fs15.existsSync(targetDir)&&fs15.readdirSync(targetDir).length>0){let name=path17.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path17.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,env,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,env,branch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg;if(!projectId){let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});switch(picked.status){case"selected":projectId=picked.projectId;break;case"cancelled":ui.info({command:"clone",message:"Cancelled."});return;case"empty":ui.info({command:"clone",message:picked.message});return;case"error":ui.error({command:"clone",code:picked.code,message:picked.message,...picked.hint?{hint:picked.hint}:{}});return}}currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,env,branch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env,branch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,PICKER_HINT,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneEnv,"chooseCloneEnv");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");PICKER_HINT="Pass a project ID explicitly, e.g. `fimo clone <projectId>`.";__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});import path19 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectEnvironmentCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path19.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new EnvironmentCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new EnvironmentCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new EnvironmentCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new EnvironmentCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectEnvironmentCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new EnvironmentCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectEnvironmentCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new EnvironmentCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new EnvironmentCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectEnvironmentCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch(args.cwd);if(localBranch!==args.remoteBranch)throw new EnvironmentCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectEnvironmentCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new EnvironmentCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new EnvironmentCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}var EnvironmentCheckoutError,init_environment_checkout=__esm({"src/cli/utils/environment-checkout.ts"(){init_git();EnvironmentCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="EnvironmentCheckoutError"}code;hint;static{__name(this,"EnvironmentCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectEnvironmentCheckout,"inspectEnvironmentCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(prepareDeployCheckout,"prepareDeployCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject(subject){return typeof subject=="object"&&subject!==null}__name(isObject,"isObject");function toArray2(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray2,"toArray");function extend(target,source){var index2,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index2=0,length=sourceKeys.length;index2<length;index2+=1)key=sourceKeys[index2],target[key]=source[key];return target}__name(extend,"extend");function repeat(string2,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string2;return result}__name(repeat,"repeat");function isNegativeZero(number2){return number2===0&&Number.NEGATIVE_INFINITY===1/number2}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject;module2.exports.toArray=toArray2;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end2,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
259
259
  \x85\u2028\u2029`.indexOf(this.buffer.charAt(start-1))===-1;)if(start-=1,this.position-start>maxLength/2-1){head=" ... ",start+=5;break}for(tail="",end2=this.position;end2<this.buffer.length&&`\0\r
260
260
  \x85\u2028\u2029`.indexOf(this.buffer.charAt(end2))===-1;)if(end2+=1,end2-this.position>maxLength/2-1){tail=" ... ",end2-=5;break}return snippet=this.buffer.slice(start,end2),common.repeat(" ",indent)+head+snippet+tail+`
261
261
  `+common.repeat(" ",indent+this.position-start+head.length)+"^"},"getSnippet");Mark.prototype.toString=__name(function(compact){var snippet,where="";return this.name&&(where+='in "'+this.name+'" '),where+="at line "+(this.line+1)+", column "+(this.column+1),compact||(snippet=this.getSnippet(),snippet&&(where+=`:
@@ -353,8 +353,8 @@ return __eta.res;
353
353
  `):type==="e"&&(returnStr+=content2+`
354
354
  `)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp(string2){return string2.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
355
355
  `).length}function parse5(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
356
- `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile2(path49){let res="";try{res=fs17.readFileSync(path49,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path49}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path20.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path20.join(views,formattedPath)}else resolvedFilePath=path20.join(path20.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path20.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path20.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path20.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse5,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse5,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path49){try{return JSON.parse(readFileSync4(path49,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
357
- `)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),templatePath2=assetPath("content-templates","forms","react.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist8();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z70}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
356
+ `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile2(path49){let res="";try{res=fs17.readFileSync(path49,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path49}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path20.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path20.join(views,formattedPath)}else resolvedFilePath=path20.join(path20.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path20.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path20.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path20.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse5,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse5,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path49){try{return JSON.parse(readFileSync4(path49,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
357
+ `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"||framework==="sveltekit-1"?"sveltekit":null}function hasPackageExport(cwd,subpath){let packagePath=join5(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function assertFrameworkRuntime(cwd,target){let missing=(target==="next"?["./forms","./next","./next/client"]:["./forms",`./${target}`]).filter(subpath=>!hasPackageExport(cwd,subpath));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project-local fimo package is missing ${missing.join(", ")}. Install the current fimo package, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo/next"},{suffix:".client.ts",runtimeImport:"fimo/next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo/sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist8();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z71}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
358
358
  - ${errors.join(`
359
359
  - `)}
360
360
  No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -367,7 +367,7 @@ ${imports}
367
367
  export const content = {
368
368
  ${entries2}
369
369
  } as const;
370
- `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist8();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z70.object({uid:z70.string().min(1),name:z70.string().min(1).optional(),isSingleton:z70.boolean().optional(),i18n:z70.object({enabled:z70.boolean().optional()}).optional(),fields:z70.record(z70.string(),z70.unknown()).optional()}),CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
370
+ `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist8();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z71.object({uid:z71.string().min(1),name:z71.string().min(1).optional(),isSingleton:z71.boolean().optional(),i18n:z71.object({enabled:z71.boolean().optional()}).optional(),fields:z71.record(z71.string(),z71.unknown()).optional()}),CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
371
371
  `)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
372
372
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
373
373
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -512,7 +512,7 @@ ${end2.comment}`:end2.comment}this.doc.range[2]=end2.offset;break}default:this.e
512
512
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
513
513
  `,nl)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(map2){let it2=map2.items[map2.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,it2.value){let end2="end"in it2.value?it2.value.end:void 0;(Array.isArray(end2)?end2[end2.length-1]:void 0)?.type==="comment"?end2?.push(this.sourceToken):map2.items.push({start:[this.sourceToken]})}else it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)map2.items.push({start:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else{if(this.atIndentedComment(it2.start,map2.indent)){let end2=map2.items[map2.items.length-2]?.value?.end;if(Array.isArray(end2)){arrayPushArray(end2,it2.start),end2.push(this.sourceToken),map2.items.pop();return}}it2.start.push(this.sourceToken)}return}if(this.indent>=map2.indent){let atMapIndent=!this.onKeyLine&&this.indent===map2.indent,atNextItem=atMapIndent&&(it2.sep||it2.explicitKey)&&this.type!=="seq-item-ind",start=[];if(atNextItem&&it2.sep&&!it2.value){let nl=[];for(let i=0;i<it2.sep.length;++i){let st2=it2.sep[i];switch(st2.type){case"newline":nl.push(i);break;case"space":break;case"comment":st2.indent>map2.indent&&(nl.length=0);break;default:nl.length=0}}nl.length>=2&&(start=it2.sep.splice(nl[1]))}switch(this.type){case"anchor":case"tag":atNextItem||it2.value?(start.push(this.sourceToken),map2.items.push({start}),this.onKeyLine=!0):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"explicit-key-ind":!it2.sep&&!it2.explicitKey?(it2.start.push(this.sourceToken),it2.explicitKey=!0):atNextItem||it2.value?(start.push(this.sourceToken),map2.items.push({start,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(it2.explicitKey)if(it2.sep)if(it2.value)map2.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(it2.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(it2.key)&&!includesToken(it2.sep,"newline")){let start2=getFirstKeyStartProps(it2.start),key=it2.key,sep2=it2.sep;sep2.push(this.sourceToken),delete it2.key,delete it2.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep:sep2}]})}else start.length>0?it2.sep=it2.sep.concat(start,this.sourceToken):it2.sep.push(this.sourceToken);else if(includesToken(it2.start,"newline"))Object.assign(it2,{key:null,sep:[this.sourceToken]});else{let start2=getFirstKeyStartProps(it2.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}else it2.sep?it2.value||atNextItem?map2.items.push({start,key:null,sep:[this.sourceToken]}):includesToken(it2.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs47=this.flowScalar(this.type);atNextItem||it2.value?(map2.items.push({start,key:fs47,sep:[]}),this.onKeyLine=!0):it2.sep?this.stack.push(fs47):(Object.assign(it2,{key:fs47,sep:[]}),this.onKeyLine=!0);return}default:{let bv=this.startBlockValue(map2);if(bv){if(bv.type==="block-seq"){if(!it2.explicitKey&&it2.sep&&!includesToken(it2.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else atMapIndent&&map2.items.push({start});this.stack.push(bv);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(seq){let it2=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it2.value){let end2="end"in it2.value?it2.value.end:void 0;(Array.isArray(end2)?end2[end2.length-1]:void 0)?.type==="comment"?end2?.push(this.sourceToken):seq.items.push({start:[this.sourceToken]})}else it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it2.start,seq.indent)){let end2=seq.items[seq.items.length-2]?.value?.end;if(Array.isArray(end2)){arrayPushArray(end2,it2.start),end2.push(this.sourceToken),seq.items.pop();return}}it2.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it2.value||this.indent<=seq.indent)break;it2.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;it2.value||includesToken(it2.start,"seq-item-ind")?seq.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return}if(this.indent>seq.indent){let bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop(),yield*this.step()}*flowCollection(fc){let it2=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do yield*this.pop(),top=this.peek(1);while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!it2||it2.sep?fc.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return;case"map-value-ind":!it2||it2.value?fc.items.push({start:[],key:null,sep:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!it2||it2.value?fc.items.push({start:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs47=this.flowScalar(this.type);!it2||it2.value?fc.items.push({start:[],key:fs47,sep:[]}):it2.sep?this.stack.push(fs47):Object.assign(it2,{key:fs47,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}let bv=this.startBlockValue(fc);bv?this.stack.push(bv):(yield*this.pop(),yield*this.step())}else{let parent2=this.peek(2);if(parent2.type==="block-map"&&(this.type==="map-value-ind"&&parent2.indent===fc.indent||this.type==="newline"&&!parent2.items[parent2.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&parent2.type!=="flow-collection"){let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);fixFlowSeqItems(fc);let sep2=fc.end.splice(1,fc.end.length);sep2.push(this.sourceToken);let map2={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep2}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map2}else yield*this.lineEnd(fc)}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
514
514
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
515
- `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser2}});var require_public_api2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),errors=require_errors2(),log=require_log2(),identity2=require_identity2(),lineCounter=require_line_counter2(),parser=require_parser2();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse13(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse13,"parse");function stringify5(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify5,"stringify");exports2.parse=parse13;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify5}});var require_dist3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),Schema=require_Schema2(),errors=require_errors2(),Alias=require_Alias2(),identity2=require_identity2(),Pair=require_Pair2(),Scalar=require_Scalar2(),YAMLMap=require_YAMLMap2(),YAMLSeq=require_YAMLSeq2(),cst=require_cst2(),lexer=require_lexer2(),lineCounter=require_line_counter2(),parser=require_parser2(),publicApi=require_public_api2(),visit2=require_visit2();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import{existsSync as existsSync9}from"node:fs";import{homedir as homedir2,platform as platform2,tmpdir as tmpdir2}from"node:os";import{basename as basename3,dirname as dirname6,isAbsolute as isAbsolute3,join as join10,normalize,relative as relative2,resolve as resolve8,sep}from"node:path";import{cp,lstat,mkdir,mkdtemp,readFile as readFile4,readdir,readlink,realpath,rm,stat,symlink,writeFile}from"node:fs/promises";import{spawn as spawn2}from"node:child_process";var import_yaml4,xdgConfigHome,CANONICAL_SKILLS_DIR,SKILL_MANIFEST_FILE,DEFAULT_CLONE_TIMEOUT_MS,DEFAULT_FETCH_TIMEOUT_MS,MS_PER_SECOND,SKIP_DISCOVERY_DIRS,COPY_EXCLUDE_FILES,COPY_EXCLUDE_DIRS,WELL_KNOWN_INDEX_FILE,WELL_KNOWN_PATHS,home,configHome,codexHome,claudeHome,vibeHome,resolveOpenClawGlobalSkillsDir,detectOpenClaw,skillAgents,getSkillAgentConfig,isUniversalSkillAgent,getSkillAgentDir,agentConfigEntries,getSkillAgentTypes,isSkillAgentType,getUniversalSkillAgents,detectInstalledSkillAgents,parseFrontmatter,sanitizeName,fetchSkillManifestFromUrl,isPathSafe,stripTrailingSlash,TEMP_PREFIX,SKILL_NAME_PATTERN,WellKnownTimeoutError,isValidWellKnownEntry,fetchOk,buildIndexCandidates,extractRequestedSkillName,validateIndexEntries,resolveIndex,writeSkillFiles,fetchWellKnownSkills,readJsonObjectIfExists,MARKETPLACE_RELATIVE_PATH,PLUGIN_RELATIVE_PATH,PLUGIN_SKILLS_SUBDIR,isClaudeRelativePath,stringValueOrEmpty,resolvePluginRoot,collectPluginSkillSearchDirs,collectPluginGroupings,getPluginSkillPaths,getPluginGroupings,CLONE_TIMEOUT_ENV_VAR,LEGACY_CLONE_TIMEOUT_ENV_VAR,TEMP_CLONE_PREFIX,GitCloneError,resolveCloneTimeoutMs,runGit2,AUTH_ERROR_MARKERS,isAuthErrorMessage,cloneRepo2,cleanupTempDir,getCanonicalSkillsDir,getSkillAgentBaseDir,cleanAndCreateDirectory,resolveSymlinkTarget,resolveParentSymlinks,isPathInsideBase,copyDirectory,isLoopError,createSymlink,installByCopy,installBySymlink,installSkillForAgent,OSC_RE,DCS_PM_APC_RE,CSI_RE,SIMPLE_ESC_RE,C1_RE,CONTROL_RE2,stripTerminalEscapes,sanitizeMetadata,PRIORITY_RELATIVE_PATHS,hasSkillManifest,parseSkillManifest,findSkillDirs,discoverSkills,getSkillDisplayName,filterSkillsByName,escapeRegex,sanitizeSubpath,HOST_CONFIGS,HOST_BY_NAME,HOST_BY_DOMAIN,SSH_URL_PATTERN,isLocalPath,isShorthandCandidate,buildHostedSource,buildHostUrlPatterns,HOST_URL_PATTERNS,decodeFragmentValue,looksLikeGitSource,parseFragmentRef,isDirectSkillMdUrl,EXCLUDED_WELL_KNOWN_HOSTS,isWellKnownCandidate,parseHostedShorthand,isHostnameAuthoritative,parseHostUrl,parseSshUrl,parseSkillSource,resolveSource,resolveTargetAgents,resolveSkillFilters,installSkillsFromSource,init_skill_DRd1jW7a=__esm({"../../node_modules/.pnpm/agent-install@0.0.5/node_modules/agent-install/dist/skill-DRd1jW7a.js"(){init_chunk_pbuEa_1d();init_to_error_message_Bg0SEUet();import_yaml4=__toESM(require_dist3(),1),xdgConfigHome=__name(()=>{let explicit=process.env.XDG_CONFIG_HOME?.trim();if(explicit)return explicit;if(platform2()==="win32"){let localAppData=process.env.LOCALAPPDATA?.trim();if(localAppData)return localAppData}return join10(homedir2(),".config")},"xdgConfigHome"),CANONICAL_SKILLS_DIR=".agents/skills",SKILL_MANIFEST_FILE="SKILL.md",DEFAULT_CLONE_TIMEOUT_MS=3e5,DEFAULT_FETCH_TIMEOUT_MS=3e4,MS_PER_SECOND=1e3,SKIP_DISCOVERY_DIRS=new Set(["node_modules",".git","dist","build","__pycache__","coverage",".next",".turbo"]),COPY_EXCLUDE_FILES=new Set(["metadata.json"]),COPY_EXCLUDE_DIRS=new Set([".git","__pycache__","__pypackages__"]),WELL_KNOWN_INDEX_FILE="index.json",WELL_KNOWN_PATHS=[".well-known/agent-skills",".well-known/skills"],home=homedir2(),configHome=xdgConfigHome(),codexHome=process.env.CODEX_HOME?.trim()||join10(home,".codex"),claudeHome=process.env.CLAUDE_CONFIG_DIR?.trim()||join10(home,".claude"),vibeHome=process.env.VIBE_HOME?.trim()||join10(home,".vibe"),resolveOpenClawGlobalSkillsDir=__name(()=>existsSync9(join10(home,".openclaw"))?join10(home,".openclaw/skills"):existsSync9(join10(home,".clawdbot"))?join10(home,".clawdbot/skills"):existsSync9(join10(home,".moltbot"))?join10(home,".moltbot/skills"):join10(home,".openclaw/skills"),"resolveOpenClawGlobalSkillsDir"),detectOpenClaw=__name(()=>existsSync9(join10(home,".openclaw"))||existsSync9(join10(home,".clawdbot"))||existsSync9(join10(home,".moltbot")),"detectOpenClaw"),skillAgents={adal:{name:"adal",displayName:"AdaL",skillsDir:".adal/skills",globalSkillsDir:join10(home,".adal/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".adal")),"detectInstalled")},"aider-desk":{name:"aider-desk",displayName:"AiderDesk",skillsDir:".aider-desk/skills",globalSkillsDir:join10(home,".aider-desk/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".aider-desk")),"detectInstalled")},amp:{name:"amp",displayName:"Amp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"amp")),"detectInstalled"),isUniversal:!0},antigravity:{name:"antigravity",displayName:"Antigravity",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/antigravity/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini/antigravity")),"detectInstalled"),isUniversal:!0},augment:{name:"augment",displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:join10(home,".augment/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".augment")),"detectInstalled")},bob:{name:"bob",displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:join10(home,".bob/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".bob")),"detectInstalled")},"claude-code":{name:"claude-code",displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:join10(claudeHome,"skills"),detectInstalled:__name(async()=>existsSync9(claudeHome),"detectInstalled")},cline:{name:"cline",displayName:"Cline",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cline")),"detectInstalled"),isUniversal:!0},"codearts-agent":{name:"codearts-agent",displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:join10(home,".codeartsdoer/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeartsdoer")),"detectInstalled")},codebuddy:{name:"codebuddy",displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:join10(home,".codebuddy/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".codebuddy"))||existsSync9(join10(home,".codebuddy")),"detectInstalled")},codemaker:{name:"codemaker",displayName:"Codemaker",skillsDir:".codemaker/skills",globalSkillsDir:join10(home,".codemaker/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codemaker")),"detectInstalled")},codestudio:{name:"codestudio",displayName:"Code Studio",skillsDir:".codestudio/skills",globalSkillsDir:join10(home,".codestudio/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codestudio")),"detectInstalled")},codex:{name:"codex",displayName:"Codex",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(codexHome,"skills"),detectInstalled:__name(async()=>existsSync9(codexHome)||existsSync9("/etc/codex"),"detectInstalled"),isUniversal:!0},"command-code":{name:"command-code",displayName:"Command Code",skillsDir:".commandcode/skills",globalSkillsDir:join10(home,".commandcode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".commandcode")),"detectInstalled")},continue:{name:"continue",displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:join10(home,".continue/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".continue"))||existsSync9(join10(home,".continue")),"detectInstalled")},cortex:{name:"cortex",displayName:"Cortex Code",skillsDir:".cortex/skills",globalSkillsDir:join10(home,".snowflake/cortex/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".snowflake/cortex")),"detectInstalled")},crush:{name:"crush",displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:join10(configHome,"crush/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"crush")),"detectInstalled")},cursor:{name:"cursor",displayName:"Cursor",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".cursor/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cursor")),"detectInstalled"),isUniversal:!0},deepagents:{name:"deepagents",displayName:"Deep Agents",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".deepagents/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".deepagents")),"detectInstalled"),isUniversal:!0},devin:{name:"devin",displayName:"Devin",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"devin/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"devin")),"detectInstalled"),isUniversal:!0},dexto:{name:"dexto",displayName:"Dexto",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".dexto")),"detectInstalled"),isUniversal:!0},droid:{name:"droid",displayName:"Factory Droid",skillsDir:".factory/skills",globalSkillsDir:join10(home,".factory/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".factory")),"detectInstalled")},firebender:{name:"firebender",displayName:"Firebender",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".firebender/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".firebender")),"detectInstalled"),isUniversal:!0},forgecode:{name:"forgecode",displayName:"ForgeCode",skillsDir:".forge/skills",globalSkillsDir:join10(home,".forge/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".forge")),"detectInstalled")},"gemini-cli":{name:"gemini-cli",displayName:"Gemini CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini")),"detectInstalled"),isUniversal:!0},"github-copilot":{name:"github-copilot",displayName:"GitHub Copilot",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".copilot/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".copilot")),"detectInstalled"),isUniversal:!0},goose:{name:"goose",displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:join10(configHome,"goose/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"goose")),"detectInstalled")},"iflow-cli":{name:"iflow-cli",displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:join10(home,".iflow/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".iflow")),"detectInstalled")},junie:{name:"junie",displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:join10(home,".junie/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".junie")),"detectInstalled")},kilo:{name:"kilo",displayName:"Kilo Code",skillsDir:".kilocode/skills",globalSkillsDir:join10(home,".kilocode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kilocode")),"detectInstalled")},"kimi-cli":{name:"kimi-cli",displayName:"Kimi Code CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kimi")),"detectInstalled"),isUniversal:!0},"kiro-cli":{name:"kiro-cli",displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:join10(home,".kiro/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kiro")),"detectInstalled")},kode:{name:"kode",displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:join10(home,".kode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kode")),"detectInstalled")},mcpjam:{name:"mcpjam",displayName:"MCPJam",skillsDir:".mcpjam/skills",globalSkillsDir:join10(home,".mcpjam/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mcpjam")),"detectInstalled")},"mistral-vibe":{name:"mistral-vibe",displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:join10(vibeHome,"skills"),detectInstalled:__name(async()=>existsSync9(vibeHome),"detectInstalled")},mux:{name:"mux",displayName:"Mux",skillsDir:".mux/skills",globalSkillsDir:join10(home,".mux/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mux")),"detectInstalled")},neovate:{name:"neovate",displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:join10(home,".neovate/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".neovate")),"detectInstalled")},openclaw:{name:"openclaw",displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:resolveOpenClawGlobalSkillsDir(),detectInstalled:__name(async()=>detectOpenClaw(),"detectInstalled")},opencode:{name:"opencode",displayName:"OpenCode",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"opencode/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"opencode")),"detectInstalled"),isUniversal:!0},openhands:{name:"openhands",displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:join10(home,".openhands/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".openhands")),"detectInstalled")},pi:{name:"pi",displayName:"Pi",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".pi/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pi")),"detectInstalled"),isUniversal:!0},pochi:{name:"pochi",displayName:"Pochi",skillsDir:".pochi/skills",globalSkillsDir:join10(home,".pochi/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pochi")),"detectInstalled")},qoder:{name:"qoder",displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:join10(home,".qoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qoder")),"detectInstalled")},"qwen-code":{name:"qwen-code",displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:join10(home,".qwen/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qwen")),"detectInstalled")},replit:{name:"replit",displayName:"Replit",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".replit")),"detectInstalled"),isUniversal:!0},roo:{name:"roo",displayName:"Roo Code",skillsDir:".roo/skills",globalSkillsDir:join10(home,".roo/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".roo")),"detectInstalled")},rovodev:{name:"rovodev",displayName:"Rovo Dev",skillsDir:".rovodev/skills",globalSkillsDir:join10(home,".rovodev/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".rovodev")),"detectInstalled")},"tabnine-cli":{name:"tabnine-cli",displayName:"Tabnine CLI",skillsDir:".tabnine/agent/skills",globalSkillsDir:join10(home,".tabnine/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".tabnine")),"detectInstalled")},trae:{name:"trae",displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae")),"detectInstalled")},"trae-cn":{name:"trae-cn",displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae-cn/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae-cn")),"detectInstalled")},universal:{name:"universal",displayName:"Universal",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>!1,"detectInstalled"),isUniversal:!0},warp:{name:"warp",displayName:"Warp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".warp")),"detectInstalled"),isUniversal:!0},windsurf:{name:"windsurf",displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:join10(home,".codeium/windsurf/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeium/windsurf")),"detectInstalled")},zencoder:{name:"zencoder",displayName:"Zencoder",skillsDir:".zencoder/skills",globalSkillsDir:join10(home,".zencoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".zencoder")),"detectInstalled")}},getSkillAgentConfig=__name(agentType=>skillAgents[agentType],"getSkillAgentConfig"),isUniversalSkillAgent=__name(agentType=>!!skillAgents[agentType].isUniversal,"isUniversalSkillAgent"),getSkillAgentDir=__name((agentType,options={})=>{let agent=skillAgents[agentType];return options.global??!1?agent.globalSkillsDir??join10(home,agent.skillsDir):join10(options.cwd??process.cwd(),agent.skillsDir)},"getSkillAgentDir"),agentConfigEntries=__name(()=>Object.values(skillAgents).map(config=>[config.name,config]),"agentConfigEntries"),getSkillAgentTypes=__name(()=>agentConfigEntries().map(([name])=>name),"getSkillAgentTypes"),isSkillAgentType=__name(value=>value in skillAgents,"isSkillAgentType"),getUniversalSkillAgents=__name(()=>agentConfigEntries().filter(([name,config])=>config.isUniversal&&name!=="universal").map(([name])=>name),"getUniversalSkillAgents"),detectInstalledSkillAgents=__name(async()=>(await Promise.all(Object.values(skillAgents).map(async config=>({name:config.name,installed:await config.detectInstalled()})))).filter(entry=>entry.installed).map(entry=>entry.name),"detectInstalledSkillAgents"),parseFrontmatter=__name(raw=>{let match=raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!match)return{data:{},content:raw};let parsed=(0,import_yaml4.parse)(match[1]??"");return{data:isPlainObject(parsed)?parsed:{},content:match[2]??""}},"parseFrontmatter"),sanitizeName=__name(name=>name.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill","sanitizeName"),fetchSkillManifestFromUrl=__name(async url=>{let controller=new AbortController,timer=setTimeout(()=>controller.abort(),DEFAULT_FETCH_TIMEOUT_MS);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch ${url}: HTTP ${response.status}`);let content2=await response.text(),{data:data2}=parseFrontmatter(content2);if(typeof data2.name!="string"||!data2.name)throw new Error(`Fetched SKILL.md has no "name" in its frontmatter: ${url}`);let skillName=sanitizeName(data2.name),baseDir=await mkdtemp(join10(tmpdir2(),"agent-install-url-")),skillDir=join10(baseDir,skillName);return await mkdir(dirname6(join10(skillDir,SKILL_MANIFEST_FILE)),{recursive:!0}),await writeFile(join10(skillDir,SKILL_MANIFEST_FILE),content2,"utf-8"),baseDir}finally{clearTimeout(timer)}},"fetchSkillManifestFromUrl"),isPathSafe=__name((basePath,targetPath)=>{let normalizedBase=normalize(resolve8(basePath)),normalizedTarget=normalize(resolve8(targetPath));return normalizedTarget.startsWith(normalizedBase+sep)||normalizedTarget===normalizedBase},"isPathSafe"),stripTrailingSlash=__name(input=>input.endsWith("/")?input.slice(0,-1):input,"stripTrailingSlash"),TEMP_PREFIX="agent-install-well-known-",SKILL_NAME_PATTERN=/^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/,WellKnownTimeoutError=class extends Error{static{__name(this,"WellKnownTimeoutError")}constructor(message){super(message),this.name="WellKnownTimeoutError"}},isValidWellKnownEntry=__name(value=>{if(!isPlainObject(value)||typeof value.name!="string"||!value.name||typeof value.description!="string"||!value.description||!Array.isArray(value.files)||value.files.length===0||value.name.length>1&&!SKILL_NAME_PATTERN.test(value.name)||value.name.length===1&&!/^[a-z0-9]$/.test(value.name))return!1;for(let file of value.files)if(typeof file!="string"||file.startsWith("/")||file.startsWith("\\")||file.includes(".."))return!1;return value.files.some(file=>typeof file=="string"&&file.toLowerCase()==="skill.md")},"isValidWellKnownEntry"),fetchOk=__name(async url=>{try{let response=await fetch(url,{signal:AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS)});return response.ok?response:null}catch(error){if(error instanceof DOMException&&error.name==="TimeoutError")throw new WellKnownTimeoutError(`Request timed out: ${url}`);return null}},"fetchOk"),buildIndexCandidates=__name(inputUrl=>{let parsed=new URL(inputUrl),basePath=stripTrailingSlash(parsed.pathname),candidates=[];for(let wellKnownPath of WELL_KNOWN_PATHS)candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}${basePath}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}${basePath}`,wellKnownPath}),basePath&&candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}`,wellKnownPath});return candidates},"buildIndexCandidates"),extractRequestedSkillName=__name(inputUrl=>{try{let name=new URL(inputUrl).pathname.match(/\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/)?.[1];return name&&name!=="index.json"?name:void 0}catch{return}},"extractRequestedSkillName"),validateIndexEntries=__name(payload=>{if(!isPlainObject(payload))return null;let{skills:skills2}=payload;return!Array.isArray(skills2)||!skills2.every(isValidWellKnownEntry)?null:skills2},"validateIndexEntries"),resolveIndex=__name(async inputUrl=>{for(let candidate of buildIndexCandidates(inputUrl)){let response=await fetchOk(candidate.indexUrl);if(!response)continue;let payload;try{payload=await response.json()}catch{continue}let entries2=validateIndexEntries(payload);if(entries2)return{entries:entries2,baseUrl:candidate.baseUrl,wellKnownPath:candidate.wellKnownPath,requestedSkillName:extractRequestedSkillName(inputUrl)}}return null},"resolveIndex"),writeSkillFiles=__name(async(resolved,entry,rootDir)=>{let skillDir=join10(rootDir,sanitizeName(entry.name));await mkdir(skillDir,{recursive:!0});let skillBaseUrl=`${stripTrailingSlash(resolved.baseUrl)}/${resolved.wellKnownPath}/${entry.name}`,installedAny=!1;return await Promise.all(entry.files.map(async relativePath=>{let targetPath=join10(skillDir,relativePath);if(!isPathSafe(skillDir,targetPath))return;let response=await fetchOk(`${skillBaseUrl}/${relativePath}`);if(!response)return;let content2=await response.text();await mkdir(dirname6(targetPath),{recursive:!0}),await writeFile(targetPath,content2,"utf-8"),installedAny=!0})),installedAny},"writeSkillFiles"),fetchWellKnownSkills=__name(async inputUrl=>{let resolved=await resolveIndex(inputUrl).catch(error=>{throw error instanceof WellKnownTimeoutError?new Error(`Timed out resolving well-known skills index at ${inputUrl}. Set the source's HTTP server to respond faster, or pass a local path.`):error});if(!resolved)throw new Error(`No /.well-known/agent-skills/index.json (or fallback /.well-known/skills/index.json) found at ${inputUrl}`);let entries2=resolved.requestedSkillName?resolved.entries.filter(entry=>entry.name===resolved.requestedSkillName):resolved.entries;if(entries2.length===0)throw new Error(resolved.requestedSkillName?`Skill "${resolved.requestedSkillName}" not found in well-known index at ${inputUrl}`:`Well-known index at ${inputUrl} declares no skills`);let baseDir=await mkdtemp(join10(tmpdir2(),TEMP_PREFIX));if(!(await Promise.all(entries2.map(entry=>writeSkillFiles(resolved,entry,baseDir)))).some(Boolean))throw new Error(`Failed to fetch any skill files from well-known index at ${inputUrl}`);return baseDir},"fetchWellKnownSkills"),readJsonObjectIfExists=__name(async path49=>{try{let content2=await readFile4(path49,"utf-8"),parsed=JSON.parse(content2);return isPlainObject(parsed)?parsed:null}catch{return null}},"readJsonObjectIfExists"),MARKETPLACE_RELATIVE_PATH=".claude-plugin/marketplace.json",PLUGIN_RELATIVE_PATH=".claude-plugin/plugin.json",PLUGIN_SKILLS_SUBDIR="skills",isClaudeRelativePath=__name(input=>typeof input=="string"&&input.startsWith("./"),"isClaudeRelativePath"),stringValueOrEmpty=__name(input=>typeof input=="string"?input:"","stringValueOrEmpty"),resolvePluginRoot=__name(manifest=>{if(!isPlainObject(manifest.metadata))return"";let rawPluginRoot=manifest.metadata.pluginRoot;return rawPluginRoot===void 0?"":isClaudeRelativePath(rawPluginRoot)?rawPluginRoot:null},"resolvePluginRoot"),collectPluginSkillSearchDirs=__name((basePath,pluginBase,rawSkills,searchDirs)=>{if(isPathSafe(basePath,pluginBase)){if(Array.isArray(rawSkills))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=dirname6(join10(pluginBase,entry));isPathSafe(basePath,skillDir)&&searchDirs.push(skillDir)}searchDirs.push(join10(pluginBase,PLUGIN_SKILLS_SUBDIR))}},"collectPluginSkillSearchDirs"),collectPluginGroupings=__name((basePath,pluginBase,pluginName,rawSkills,groupings)=>{if(!(!isPathSafe(basePath,pluginBase)||!Array.isArray(rawSkills)))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=join10(pluginBase,entry);isPathSafe(basePath,skillDir)&&groupings.set(resolve8(skillDir),pluginName)}},"collectPluginGroupings"),getPluginSkillPaths=__name(async basePath=>{let searchDirs=[],marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginSkillSearchDirs(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.skills,searchDirs))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&collectPluginSkillSearchDirs(basePath,basePath,single.skills,searchDirs),searchDirs},"getPluginSkillPaths"),getPluginGroupings=__name(async basePath=>{let groupings=new Map,marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(typeof plugin.name!="string"||!plugin.name||plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginGroupings(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.name,plugin.skills,groupings))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&typeof single.name=="string"&&single.name&&collectPluginGroupings(basePath,basePath,single.name,single.skills,groupings),groupings},"getPluginGroupings"),CLONE_TIMEOUT_ENV_VAR="AGENT_INSTALL_CLONE_TIMEOUT_MS",LEGACY_CLONE_TIMEOUT_ENV_VAR="SKILL_INSTALL_CLONE_TIMEOUT_MS",TEMP_CLONE_PREFIX="agent-install-",GitCloneError=class extends Error{static{__name(this,"GitCloneError")}url;kind;constructor(message,url,kind="unknown"){super(message),this.name="GitCloneError",this.url=url,this.kind=kind}get isTimeout(){return this.kind==="timeout"}get isAuthError(){return this.kind==="auth"}},resolveCloneTimeoutMs=__name(()=>{let raw=process.env[CLONE_TIMEOUT_ENV_VAR]??process.env[LEGACY_CLONE_TIMEOUT_ENV_VAR];if(!raw)return DEFAULT_CLONE_TIMEOUT_MS;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:DEFAULT_CLONE_TIMEOUT_MS},"resolveCloneTimeoutMs"),runGit2=__name((args,timeoutMs)=>new Promise(resolvePromise=>{let child=spawn2("git",args,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_LFS_SKIP_SMUDGE:"1"}}),stderr="",timedOut=!1,timer=setTimeout(()=>{timedOut=!0,child.kill("SIGKILL")},timeoutMs);child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code2=>{clearTimeout(timer),resolvePromise({code:code2??1,stderr,timedOut})}),child.on("error",err=>{clearTimeout(timer),stderr+=err.message,resolvePromise({code:1,stderr,timedOut})})}),"runGit"),AUTH_ERROR_MARKERS=["Authentication failed","could not read Username","Permission denied","Repository not found"],isAuthErrorMessage=__name(stderr=>AUTH_ERROR_MARKERS.some(marker=>stderr.includes(marker)),"isAuthErrorMessage"),cloneRepo2=__name(async(url,ref)=>{let tempDir=await mkdtemp(join10(tmpdir2(),TEMP_CLONE_PREFIX)),timeoutMs=resolveCloneTimeoutMs(),args=["-c","filter.lfs.required=false","-c","filter.lfs.smudge=","-c","filter.lfs.clean=","-c","filter.lfs.process=","clone","--depth","1"];ref&&args.push("--branch",ref),args.push(url,tempDir);let{code:code2,stderr,timedOut}=await runGit2(args,timeoutMs);if(code2===0)return tempDir;throw await rm(tempDir,{recursive:!0,force:!0}).catch(()=>{}),timedOut?new GitCloneError([`Clone timed out after ${Math.round(timeoutMs/MS_PER_SECOND)}s. Common causes:`,` - Large repository: raise the timeout with ${CLONE_TIMEOUT_ENV_VAR}=600000 (10m)`," - Slow network: retry, or clone manually and pass the local path to 'skill add'"," - Private repo without credentials:"," - For SSH: ssh-add -l (to check loaded keys)"," - For HTTPS: gh auth status (if using GitHub CLI)"].join(`
515
+ `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser2}});var require_public_api2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),errors=require_errors2(),log=require_log2(),identity2=require_identity2(),lineCounter=require_line_counter2(),parser=require_parser2();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse13(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse13,"parse");function stringify5(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify5,"stringify");exports2.parse=parse13;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify5}});var require_dist3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),Schema=require_Schema2(),errors=require_errors2(),Alias=require_Alias2(),identity2=require_identity2(),Pair=require_Pair2(),Scalar=require_Scalar2(),YAMLMap=require_YAMLMap2(),YAMLSeq=require_YAMLSeq2(),cst=require_cst2(),lexer=require_lexer2(),lineCounter=require_line_counter2(),parser=require_parser2(),publicApi=require_public_api2(),visit2=require_visit2();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import{existsSync as existsSync9}from"node:fs";import{homedir as homedir2,platform as platform2,tmpdir as tmpdir2}from"node:os";import{basename as basename3,dirname as dirname6,isAbsolute as isAbsolute3,join as join10,normalize,relative as relative2,resolve as resolve8,sep}from"node:path";import{cp,lstat,mkdir,mkdtemp,readFile as readFile4,readdir,readlink,realpath,rm,stat,symlink,writeFile}from"node:fs/promises";import{spawn as spawn2}from"node:child_process";var import_yaml4,xdgConfigHome,CANONICAL_SKILLS_DIR,SKILL_MANIFEST_FILE,DEFAULT_CLONE_TIMEOUT_MS,DEFAULT_FETCH_TIMEOUT_MS,MS_PER_SECOND,SKIP_DISCOVERY_DIRS,COPY_EXCLUDE_FILES,COPY_EXCLUDE_DIRS,WELL_KNOWN_INDEX_FILE,WELL_KNOWN_PATHS,home,configHome,codexHome,claudeHome,vibeHome,resolveOpenClawGlobalSkillsDir,detectOpenClaw,skillAgents,getSkillAgentConfig,isUniversalSkillAgent,getSkillAgentDir,agentConfigEntries,getSkillAgentTypes,isSkillAgentType,getUniversalSkillAgents,detectInstalledSkillAgents,parseFrontmatter,sanitizeName,fetchSkillManifestFromUrl,isPathSafe,stripTrailingSlash,TEMP_PREFIX,SKILL_NAME_PATTERN,WellKnownTimeoutError,isValidWellKnownEntry,fetchOk,buildIndexCandidates,extractRequestedSkillName,validateIndexEntries,resolveIndex,writeSkillFiles,fetchWellKnownSkills,readJsonObjectIfExists,MARKETPLACE_RELATIVE_PATH,PLUGIN_RELATIVE_PATH,PLUGIN_SKILLS_SUBDIR,isClaudeRelativePath,stringValueOrEmpty,resolvePluginRoot,collectPluginSkillSearchDirs,collectPluginGroupings,getPluginSkillPaths,getPluginGroupings,CLONE_TIMEOUT_ENV_VAR,LEGACY_CLONE_TIMEOUT_ENV_VAR,TEMP_CLONE_PREFIX,GitCloneError,resolveCloneTimeoutMs,runGit2,AUTH_ERROR_MARKERS,isAuthErrorMessage,cloneRepo2,cleanupTempDir,getCanonicalSkillsDir,getSkillAgentBaseDir,cleanAndCreateDirectory,resolveSymlinkTarget,resolveParentSymlinks,isPathInsideBase,copyDirectory,isLoopError,createSymlink,installByCopy,installBySymlink,installSkillForAgent,OSC_RE,DCS_PM_APC_RE,CSI_RE,SIMPLE_ESC_RE,C1_RE,CONTROL_RE2,stripTerminalEscapes,sanitizeMetadata,PRIORITY_RELATIVE_PATHS,hasSkillManifest,parseSkillManifest,findSkillDirs,discoverSkills,getSkillDisplayName,filterSkillsByName,escapeRegex,sanitizeSubpath,HOST_CONFIGS,HOST_BY_NAME,HOST_BY_DOMAIN,SSH_URL_PATTERN,isLocalPath,isShorthandCandidate,buildHostedSource,buildHostUrlPatterns,HOST_URL_PATTERNS,decodeFragmentValue,looksLikeGitSource,parseFragmentRef,isDirectSkillMdUrl,EXCLUDED_WELL_KNOWN_HOSTS,isWellKnownCandidate,parseHostedShorthand,isHostnameAuthoritative,parseHostUrl,parseSshUrl,parseSkillSource,resolveSource,resolveTargetAgents,resolveSkillFilters,installSkillsFromSource,init_skill_DRd1jW7a=__esm({"../../node_modules/.pnpm/agent-install@0.0.5/node_modules/agent-install/dist/skill-DRd1jW7a.js"(){init_chunk_pbuEa_1d();init_to_error_message_Bg0SEUet();import_yaml4=__toESM(require_dist3(),1),xdgConfigHome=__name(()=>{let explicit=process.env.XDG_CONFIG_HOME?.trim();if(explicit)return explicit;if(platform2()==="win32"){let localAppData=process.env.LOCALAPPDATA?.trim();if(localAppData)return localAppData}return join10(homedir2(),".config")},"xdgConfigHome"),CANONICAL_SKILLS_DIR=".agents/skills",SKILL_MANIFEST_FILE="SKILL.md",DEFAULT_CLONE_TIMEOUT_MS=3e5,DEFAULT_FETCH_TIMEOUT_MS=3e4,MS_PER_SECOND=1e3,SKIP_DISCOVERY_DIRS=new Set(["node_modules",".git","dist","build","__pycache__","coverage",".next",".turbo"]),COPY_EXCLUDE_FILES=new Set(["metadata.json"]),COPY_EXCLUDE_DIRS=new Set([".git","__pycache__","__pypackages__"]),WELL_KNOWN_INDEX_FILE="index.json",WELL_KNOWN_PATHS=[".well-known/agent-skills",".well-known/skills"],home=homedir2(),configHome=xdgConfigHome(),codexHome=process.env.CODEX_HOME?.trim()||join10(home,".codex"),claudeHome=process.env.CLAUDE_CONFIG_DIR?.trim()||join10(home,".claude"),vibeHome=process.env.VIBE_HOME?.trim()||join10(home,".vibe"),resolveOpenClawGlobalSkillsDir=__name(()=>existsSync9(join10(home,".openclaw"))?join10(home,".openclaw/skills"):existsSync9(join10(home,".clawdbot"))?join10(home,".clawdbot/skills"):existsSync9(join10(home,".moltbot"))?join10(home,".moltbot/skills"):join10(home,".openclaw/skills"),"resolveOpenClawGlobalSkillsDir"),detectOpenClaw=__name(()=>existsSync9(join10(home,".openclaw"))||existsSync9(join10(home,".clawdbot"))||existsSync9(join10(home,".moltbot")),"detectOpenClaw"),skillAgents={adal:{name:"adal",displayName:"AdaL",skillsDir:".adal/skills",globalSkillsDir:join10(home,".adal/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".adal")),"detectInstalled")},"aider-desk":{name:"aider-desk",displayName:"AiderDesk",skillsDir:".aider-desk/skills",globalSkillsDir:join10(home,".aider-desk/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".aider-desk")),"detectInstalled")},amp:{name:"amp",displayName:"Amp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"amp")),"detectInstalled"),isUniversal:!0},antigravity:{name:"antigravity",displayName:"Antigravity",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/antigravity/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini/antigravity")),"detectInstalled"),isUniversal:!0},augment:{name:"augment",displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:join10(home,".augment/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".augment")),"detectInstalled")},bob:{name:"bob",displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:join10(home,".bob/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".bob")),"detectInstalled")},"claude-code":{name:"claude-code",displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:join10(claudeHome,"skills"),detectInstalled:__name(async()=>existsSync9(claudeHome),"detectInstalled")},cline:{name:"cline",displayName:"Cline",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cline")),"detectInstalled"),isUniversal:!0},"codearts-agent":{name:"codearts-agent",displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:join10(home,".codeartsdoer/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeartsdoer")),"detectInstalled")},codebuddy:{name:"codebuddy",displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:join10(home,".codebuddy/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".codebuddy"))||existsSync9(join10(home,".codebuddy")),"detectInstalled")},codemaker:{name:"codemaker",displayName:"Codemaker",skillsDir:".codemaker/skills",globalSkillsDir:join10(home,".codemaker/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codemaker")),"detectInstalled")},codestudio:{name:"codestudio",displayName:"Code Studio",skillsDir:".codestudio/skills",globalSkillsDir:join10(home,".codestudio/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codestudio")),"detectInstalled")},codex:{name:"codex",displayName:"Codex",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(codexHome,"skills"),detectInstalled:__name(async()=>existsSync9(codexHome)||existsSync9("/etc/codex"),"detectInstalled"),isUniversal:!0},"command-code":{name:"command-code",displayName:"Command Code",skillsDir:".commandcode/skills",globalSkillsDir:join10(home,".commandcode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".commandcode")),"detectInstalled")},continue:{name:"continue",displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:join10(home,".continue/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".continue"))||existsSync9(join10(home,".continue")),"detectInstalled")},cortex:{name:"cortex",displayName:"Cortex Code",skillsDir:".cortex/skills",globalSkillsDir:join10(home,".snowflake/cortex/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".snowflake/cortex")),"detectInstalled")},crush:{name:"crush",displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:join10(configHome,"crush/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"crush")),"detectInstalled")},cursor:{name:"cursor",displayName:"Cursor",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".cursor/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cursor")),"detectInstalled"),isUniversal:!0},deepagents:{name:"deepagents",displayName:"Deep Agents",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".deepagents/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".deepagents")),"detectInstalled"),isUniversal:!0},devin:{name:"devin",displayName:"Devin",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"devin/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"devin")),"detectInstalled"),isUniversal:!0},dexto:{name:"dexto",displayName:"Dexto",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".dexto")),"detectInstalled"),isUniversal:!0},droid:{name:"droid",displayName:"Factory Droid",skillsDir:".factory/skills",globalSkillsDir:join10(home,".factory/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".factory")),"detectInstalled")},firebender:{name:"firebender",displayName:"Firebender",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".firebender/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".firebender")),"detectInstalled"),isUniversal:!0},forgecode:{name:"forgecode",displayName:"ForgeCode",skillsDir:".forge/skills",globalSkillsDir:join10(home,".forge/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".forge")),"detectInstalled")},"gemini-cli":{name:"gemini-cli",displayName:"Gemini CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini")),"detectInstalled"),isUniversal:!0},"github-copilot":{name:"github-copilot",displayName:"GitHub Copilot",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".copilot/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".copilot")),"detectInstalled"),isUniversal:!0},goose:{name:"goose",displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:join10(configHome,"goose/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"goose")),"detectInstalled")},"iflow-cli":{name:"iflow-cli",displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:join10(home,".iflow/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".iflow")),"detectInstalled")},junie:{name:"junie",displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:join10(home,".junie/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".junie")),"detectInstalled")},kilo:{name:"kilo",displayName:"Kilo Code",skillsDir:".kilocode/skills",globalSkillsDir:join10(home,".kilocode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kilocode")),"detectInstalled")},"kimi-cli":{name:"kimi-cli",displayName:"Kimi Code CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kimi")),"detectInstalled"),isUniversal:!0},"kiro-cli":{name:"kiro-cli",displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:join10(home,".kiro/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kiro")),"detectInstalled")},kode:{name:"kode",displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:join10(home,".kode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kode")),"detectInstalled")},mcpjam:{name:"mcpjam",displayName:"MCPJam",skillsDir:".mcpjam/skills",globalSkillsDir:join10(home,".mcpjam/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mcpjam")),"detectInstalled")},"mistral-vibe":{name:"mistral-vibe",displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:join10(vibeHome,"skills"),detectInstalled:__name(async()=>existsSync9(vibeHome),"detectInstalled")},mux:{name:"mux",displayName:"Mux",skillsDir:".mux/skills",globalSkillsDir:join10(home,".mux/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mux")),"detectInstalled")},neovate:{name:"neovate",displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:join10(home,".neovate/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".neovate")),"detectInstalled")},openclaw:{name:"openclaw",displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:resolveOpenClawGlobalSkillsDir(),detectInstalled:__name(async()=>detectOpenClaw(),"detectInstalled")},opencode:{name:"opencode",displayName:"OpenCode",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"opencode/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"opencode")),"detectInstalled"),isUniversal:!0},openhands:{name:"openhands",displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:join10(home,".openhands/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".openhands")),"detectInstalled")},pi:{name:"pi",displayName:"Pi",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".pi/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pi")),"detectInstalled"),isUniversal:!0},pochi:{name:"pochi",displayName:"Pochi",skillsDir:".pochi/skills",globalSkillsDir:join10(home,".pochi/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pochi")),"detectInstalled")},qoder:{name:"qoder",displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:join10(home,".qoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qoder")),"detectInstalled")},"qwen-code":{name:"qwen-code",displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:join10(home,".qwen/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qwen")),"detectInstalled")},replit:{name:"replit",displayName:"Replit",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".replit")),"detectInstalled"),isUniversal:!0},roo:{name:"roo",displayName:"Roo Code",skillsDir:".roo/skills",globalSkillsDir:join10(home,".roo/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".roo")),"detectInstalled")},rovodev:{name:"rovodev",displayName:"Rovo Dev",skillsDir:".rovodev/skills",globalSkillsDir:join10(home,".rovodev/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".rovodev")),"detectInstalled")},"tabnine-cli":{name:"tabnine-cli",displayName:"Tabnine CLI",skillsDir:".tabnine/agent/skills",globalSkillsDir:join10(home,".tabnine/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".tabnine")),"detectInstalled")},trae:{name:"trae",displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae")),"detectInstalled")},"trae-cn":{name:"trae-cn",displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae-cn/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae-cn")),"detectInstalled")},universal:{name:"universal",displayName:"Universal",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>!1,"detectInstalled"),isUniversal:!0},warp:{name:"warp",displayName:"Warp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".warp")),"detectInstalled"),isUniversal:!0},windsurf:{name:"windsurf",displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:join10(home,".codeium/windsurf/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeium/windsurf")),"detectInstalled")},zencoder:{name:"zencoder",displayName:"Zencoder",skillsDir:".zencoder/skills",globalSkillsDir:join10(home,".zencoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".zencoder")),"detectInstalled")}},getSkillAgentConfig=__name(agentType=>skillAgents[agentType],"getSkillAgentConfig"),isUniversalSkillAgent=__name(agentType=>!!skillAgents[agentType].isUniversal,"isUniversalSkillAgent"),getSkillAgentDir=__name((agentType,options={})=>{let agent=skillAgents[agentType];return options.global??!1?agent.globalSkillsDir??join10(home,agent.skillsDir):join10(options.cwd??process.cwd(),agent.skillsDir)},"getSkillAgentDir"),agentConfigEntries=__name(()=>Object.values(skillAgents).map(config=>[config.name,config]),"agentConfigEntries"),getSkillAgentTypes=__name(()=>agentConfigEntries().map(([name])=>name),"getSkillAgentTypes"),isSkillAgentType=__name(value=>value in skillAgents,"isSkillAgentType"),getUniversalSkillAgents=__name(()=>agentConfigEntries().filter(([name,config])=>config.isUniversal&&name!=="universal").map(([name])=>name),"getUniversalSkillAgents"),detectInstalledSkillAgents=__name(async()=>(await Promise.all(Object.values(skillAgents).map(async config=>({name:config.name,installed:await config.detectInstalled()})))).filter(entry=>entry.installed).map(entry=>entry.name),"detectInstalledSkillAgents"),parseFrontmatter=__name(raw=>{let match=raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!match)return{data:{},content:raw};let parsed=(0,import_yaml4.parse)(match[1]??"");return{data:isPlainObject(parsed)?parsed:{},content:match[2]??""}},"parseFrontmatter"),sanitizeName=__name(name=>name.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill","sanitizeName"),fetchSkillManifestFromUrl=__name(async url=>{let controller=new AbortController,timer=setTimeout(()=>controller.abort(),DEFAULT_FETCH_TIMEOUT_MS);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch ${url}: HTTP ${response.status}`);let content2=await response.text(),{data:data2}=parseFrontmatter(content2);if(typeof data2.name!="string"||!data2.name)throw new Error(`Fetched SKILL.md has no "name" in its frontmatter: ${url}`);let skillName=sanitizeName(data2.name),baseDir=await mkdtemp(join10(tmpdir2(),"agent-install-url-")),skillDir=join10(baseDir,skillName);return await mkdir(dirname6(join10(skillDir,SKILL_MANIFEST_FILE)),{recursive:!0}),await writeFile(join10(skillDir,SKILL_MANIFEST_FILE),content2,"utf-8"),baseDir}finally{clearTimeout(timer)}},"fetchSkillManifestFromUrl"),isPathSafe=__name((basePath,targetPath)=>{let normalizedBase=normalize(resolve8(basePath)),normalizedTarget=normalize(resolve8(targetPath));return normalizedTarget.startsWith(normalizedBase+sep)||normalizedTarget===normalizedBase},"isPathSafe"),stripTrailingSlash=__name(input=>input.endsWith("/")?input.slice(0,-1):input,"stripTrailingSlash"),TEMP_PREFIX="agent-install-well-known-",SKILL_NAME_PATTERN=/^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/,WellKnownTimeoutError=class extends Error{static{__name(this,"WellKnownTimeoutError")}constructor(message){super(message),this.name="WellKnownTimeoutError"}},isValidWellKnownEntry=__name(value=>{if(!isPlainObject(value)||typeof value.name!="string"||!value.name||typeof value.description!="string"||!value.description||!Array.isArray(value.files)||value.files.length===0||value.name.length>1&&!SKILL_NAME_PATTERN.test(value.name)||value.name.length===1&&!/^[a-z0-9]$/.test(value.name))return!1;for(let file of value.files)if(typeof file!="string"||file.startsWith("/")||file.startsWith("\\")||file.includes(".."))return!1;return value.files.some(file=>typeof file=="string"&&file.toLowerCase()==="skill.md")},"isValidWellKnownEntry"),fetchOk=__name(async url=>{try{let response=await fetch(url,{signal:AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS)});return response.ok?response:null}catch(error){if(error instanceof DOMException&&error.name==="TimeoutError")throw new WellKnownTimeoutError(`Request timed out: ${url}`);return null}},"fetchOk"),buildIndexCandidates=__name(inputUrl=>{let parsed=new URL(inputUrl),basePath=stripTrailingSlash(parsed.pathname),candidates=[];for(let wellKnownPath of WELL_KNOWN_PATHS)candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}${basePath}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}${basePath}`,wellKnownPath}),basePath&&candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}`,wellKnownPath});return candidates},"buildIndexCandidates"),extractRequestedSkillName=__name(inputUrl=>{try{let name=new URL(inputUrl).pathname.match(/\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/)?.[1];return name&&name!=="index.json"?name:void 0}catch{return}},"extractRequestedSkillName"),validateIndexEntries=__name(payload=>{if(!isPlainObject(payload))return null;let{skills:skills2}=payload;return!Array.isArray(skills2)||!skills2.every(isValidWellKnownEntry)?null:skills2},"validateIndexEntries"),resolveIndex=__name(async inputUrl=>{for(let candidate of buildIndexCandidates(inputUrl)){let response=await fetchOk(candidate.indexUrl);if(!response)continue;let payload;try{payload=await response.json()}catch{continue}let entries2=validateIndexEntries(payload);if(entries2)return{entries:entries2,baseUrl:candidate.baseUrl,wellKnownPath:candidate.wellKnownPath,requestedSkillName:extractRequestedSkillName(inputUrl)}}return null},"resolveIndex"),writeSkillFiles=__name(async(resolved,entry,rootDir)=>{let skillDir=join10(rootDir,sanitizeName(entry.name));await mkdir(skillDir,{recursive:!0});let skillBaseUrl=`${stripTrailingSlash(resolved.baseUrl)}/${resolved.wellKnownPath}/${entry.name}`,installedAny=!1;return await Promise.all(entry.files.map(async relativePath=>{let targetPath=join10(skillDir,relativePath);if(!isPathSafe(skillDir,targetPath))return;let response=await fetchOk(`${skillBaseUrl}/${relativePath}`);if(!response)return;let content2=await response.text();await mkdir(dirname6(targetPath),{recursive:!0}),await writeFile(targetPath,content2,"utf-8"),installedAny=!0})),installedAny},"writeSkillFiles"),fetchWellKnownSkills=__name(async inputUrl=>{let resolved=await resolveIndex(inputUrl).catch(error=>{throw error instanceof WellKnownTimeoutError?new Error(`Timed out resolving well-known skills index at ${inputUrl}. Set the source's HTTP server to respond faster, or pass a local path.`):error});if(!resolved)throw new Error(`No /.well-known/agent-skills/index.json (or fallback /.well-known/skills/index.json) found at ${inputUrl}`);let entries2=resolved.requestedSkillName?resolved.entries.filter(entry=>entry.name===resolved.requestedSkillName):resolved.entries;if(entries2.length===0)throw new Error(resolved.requestedSkillName?`Skill "${resolved.requestedSkillName}" not found in well-known index at ${inputUrl}`:`Well-known index at ${inputUrl} declares no skills`);let baseDir=await mkdtemp(join10(tmpdir2(),TEMP_PREFIX));if(!(await Promise.all(entries2.map(entry=>writeSkillFiles(resolved,entry,baseDir)))).some(Boolean))throw new Error(`Failed to fetch any skill files from well-known index at ${inputUrl}`);return baseDir},"fetchWellKnownSkills"),readJsonObjectIfExists=__name(async path49=>{try{let content2=await readFile4(path49,"utf-8"),parsed=JSON.parse(content2);return isPlainObject(parsed)?parsed:null}catch{return null}},"readJsonObjectIfExists"),MARKETPLACE_RELATIVE_PATH=".claude-plugin/marketplace.json",PLUGIN_RELATIVE_PATH=".claude-plugin/plugin.json",PLUGIN_SKILLS_SUBDIR="skills",isClaudeRelativePath=__name(input=>typeof input=="string"&&input.startsWith("./"),"isClaudeRelativePath"),stringValueOrEmpty=__name(input=>typeof input=="string"?input:"","stringValueOrEmpty"),resolvePluginRoot=__name(manifest=>{if(!isPlainObject(manifest.metadata))return"";let rawPluginRoot=manifest.metadata.pluginRoot;return rawPluginRoot===void 0?"":isClaudeRelativePath(rawPluginRoot)?rawPluginRoot:null},"resolvePluginRoot"),collectPluginSkillSearchDirs=__name((basePath,pluginBase,rawSkills,searchDirs)=>{if(isPathSafe(basePath,pluginBase)){if(Array.isArray(rawSkills))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=dirname6(join10(pluginBase,entry));isPathSafe(basePath,skillDir)&&searchDirs.push(skillDir)}searchDirs.push(join10(pluginBase,PLUGIN_SKILLS_SUBDIR))}},"collectPluginSkillSearchDirs"),collectPluginGroupings=__name((basePath,pluginBase,pluginName,rawSkills,groupings)=>{if(!(!isPathSafe(basePath,pluginBase)||!Array.isArray(rawSkills)))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=join10(pluginBase,entry);isPathSafe(basePath,skillDir)&&groupings.set(resolve8(skillDir),pluginName)}},"collectPluginGroupings"),getPluginSkillPaths=__name(async basePath=>{let searchDirs=[],marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginSkillSearchDirs(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.skills,searchDirs))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&collectPluginSkillSearchDirs(basePath,basePath,single.skills,searchDirs),searchDirs},"getPluginSkillPaths"),getPluginGroupings=__name(async basePath=>{let groupings=new Map,marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(typeof plugin.name!="string"||!plugin.name||plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginGroupings(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.name,plugin.skills,groupings))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&typeof single.name=="string"&&single.name&&collectPluginGroupings(basePath,basePath,single.name,single.skills,groupings),groupings},"getPluginGroupings"),CLONE_TIMEOUT_ENV_VAR="AGENT_INSTALL_CLONE_TIMEOUT_MS",LEGACY_CLONE_TIMEOUT_ENV_VAR="SKILL_INSTALL_CLONE_TIMEOUT_MS",TEMP_CLONE_PREFIX="agent-install-",GitCloneError=class extends Error{static{__name(this,"GitCloneError")}url;kind;constructor(message,url,kind="unknown"){super(message),this.name="GitCloneError",this.url=url,this.kind=kind}get isTimeout(){return this.kind==="timeout"}get isAuthError(){return this.kind==="auth"}},resolveCloneTimeoutMs=__name(()=>{let raw=process.env[CLONE_TIMEOUT_ENV_VAR]??process.env[LEGACY_CLONE_TIMEOUT_ENV_VAR];if(!raw)return DEFAULT_CLONE_TIMEOUT_MS;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:DEFAULT_CLONE_TIMEOUT_MS},"resolveCloneTimeoutMs"),runGit2=__name((args,timeoutMs)=>new Promise(resolvePromise=>{let child=spawn2("git",args,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_LFS_SKIP_SMUDGE:"1"}}),stderr="",timedOut=!1,timer=setTimeout(()=>{timedOut=!0,child.kill("SIGKILL")},timeoutMs);child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code2=>{clearTimeout(timer),resolvePromise({code:code2??1,stderr,timedOut})}),child.on("error",err=>{clearTimeout(timer),stderr+=err.message,resolvePromise({code:1,stderr,timedOut})})}),"runGit"),AUTH_ERROR_MARKERS=["Authentication failed","could not read Username","Permission denied","Repository not found"],isAuthErrorMessage=__name(stderr=>AUTH_ERROR_MARKERS.some(marker=>stderr.includes(marker)),"isAuthErrorMessage"),cloneRepo2=__name(async(url,ref)=>{let tempDir=await mkdtemp(join10(tmpdir2(),TEMP_CLONE_PREFIX)),timeoutMs=resolveCloneTimeoutMs(),args=["-c","filter.lfs.required=false","-c","filter.lfs.smudge=","-c","filter.lfs.clean=","-c","filter.lfs.process=","clone","--depth","1"];ref&&args.push("--branch",ref),args.push(url,tempDir);let{code:code2,stderr,timedOut}=await runGit2(args,timeoutMs);if(code2===0)return tempDir;throw await rm(tempDir,{recursive:!0,force:!0}).catch(()=>{}),timedOut?new GitCloneError([`Clone timed out after ${Math.round(timeoutMs/MS_PER_SECOND)}s. Common causes:`,` - Large repository: raise the timeout with ${CLONE_TIMEOUT_ENV_VAR}=600000 (10m)`," - Slow network: retry, or clone manually and pass the local path to 'skill add'"," - Private repo without credentials:"," - For SSH: ssh-add -l (to check loaded keys)"," - For HTTPS: gh auth status (if using GitHub CLI)"].join(`
516
516
  `),url,"timeout"):isAuthErrorMessage(stderr)?new GitCloneError([`Authentication failed for ${url}.`," - For private repos, ensure you have access"," - For SSH: check your keys with 'ssh -T git@github.com'"," - For HTTPS: run 'gh auth login' or configure git credentials"].join(`
517
517
  `),url,"auth"):new GitCloneError(`Failed to clone ${url}: ${stderr.trim()||"unknown error"}`,url)},"cloneRepo"),cleanupTempDir=__name(async dir=>{let normalizedDir=normalize(resolve8(dir)),normalizedTmpDir=normalize(resolve8(tmpdir2()));if(!normalizedDir.startsWith(normalizedTmpDir+sep)&&normalizedDir!==normalizedTmpDir)throw new Error("Attempted to clean up directory outside of temp directory");await rm(dir,{recursive:!0,force:!0})},"cleanupTempDir"),getCanonicalSkillsDir=__name((isGlobal,cwd)=>join10(isGlobal?homedir2():cwd||process.cwd(),CANONICAL_SKILLS_DIR),"getCanonicalSkillsDir"),getSkillAgentBaseDir=__name((agentType,isGlobal,cwd)=>{if(isUniversalSkillAgent(agentType))return getCanonicalSkillsDir(isGlobal,cwd);let agent=getSkillAgentConfig(agentType),baseDir=isGlobal?homedir2():cwd||process.cwd();return isGlobal?agent.globalSkillsDir??join10(baseDir,agent.skillsDir):join10(baseDir,agent.skillsDir)},"getSkillAgentBaseDir"),cleanAndCreateDirectory=__name(async path49=>{await rm(path49,{recursive:!0,force:!0}).catch(()=>{}),await mkdir(path49,{recursive:!0})},"cleanAndCreateDirectory"),resolveSymlinkTarget=__name((linkPath,linkTarget)=>resolve8(dirname6(linkPath),linkTarget),"resolveSymlinkTarget"),resolveParentSymlinks=__name(async path49=>{let resolved=resolve8(path49),parentDir=dirname6(resolved),name=basename3(resolved);try{return join10(await realpath(parentDir),name)}catch{return resolved}},"resolveParentSymlinks"),isPathInsideBase=__name((basePath,targetPath)=>{let normalizedBase=resolve8(basePath),normalizedTarget=resolve8(targetPath);return normalizedTarget===normalizedBase||normalizedTarget.startsWith(normalizedBase+sep)},"isPathInsideBase"),copyDirectory=__name(async(src,dest,rootSrc=src)=>{await mkdir(dest,{recursive:!0});let entries2=await readdir(src,{withFileTypes:!0});await Promise.all(entries2.filter(entry=>!COPY_EXCLUDE_FILES.has(entry.name)&&!(entry.isDirectory()&&COPY_EXCLUDE_DIRS.has(entry.name))).map(async entry=>{let srcPath=join10(src,entry.name),destPath=join10(dest,entry.name);if(entry.isSymbolicLink()){let linkRealPath=await realpath(srcPath).catch(()=>null);if(!linkRealPath||!isPathInsideBase(rootSrc,linkRealPath))return;await cp(srcPath,destPath,{dereference:!0,recursive:!0});return}if(entry.isDirectory()){await copyDirectory(srcPath,destPath,rootSrc);return}await cp(srcPath,destPath,{dereference:!1,recursive:!0})}))},"copyDirectory"),isLoopError=__name(error=>!!(error&&typeof error=="object"&&"code"in error&&error.code==="ELOOP"),"isLoopError"),createSymlink=__name(async(target,linkPath)=>{try{let resolvedTarget=resolve8(target),resolvedLinkPath=resolve8(linkPath),[realTarget,realLinkPath]=await Promise.all([realpath(resolvedTarget).catch(()=>resolvedTarget),realpath(resolvedLinkPath).catch(()=>resolvedLinkPath)]);if(realTarget===realLinkPath)return!0;let[realTargetWithParents,realLinkPathWithParents]=await Promise.all([resolveParentSymlinks(target),resolveParentSymlinks(linkPath)]);if(realTargetWithParents===realLinkPathWithParents)return!0;try{if((await lstat(linkPath)).isSymbolicLink()){if(resolveSymlinkTarget(linkPath,await readlink(linkPath))===resolvedTarget)return!0;await rm(linkPath)}else await rm(linkPath,{recursive:!0})}catch(error){isLoopError(error)&&await rm(linkPath,{force:!0}).catch(()=>{})}let linkDir=dirname6(linkPath);return await mkdir(linkDir,{recursive:!0}),await symlink(relative2(await resolveParentSymlinks(linkDir),target),linkPath,platform2()==="win32"?"junction":void 0),!0}catch{return!1}},"createSymlink"),installByCopy=__name(async(skill,destination)=>(await cleanAndCreateDirectory(destination),await copyDirectory(skill.path,destination),{success:!0,path:destination,mode:"copy"}),"installByCopy"),installBySymlink=__name(async(skill,agentType,canonicalDir,agentDir,isGlobal)=>(await cleanAndCreateDirectory(canonicalDir),await copyDirectory(skill.path,canonicalDir),isGlobal&&isUniversalSkillAgent(agentType)?{success:!0,path:canonicalDir,canonicalPath:canonicalDir,mode:"symlink"}:await createSymlink(canonicalDir,agentDir)?{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink"}:(await cleanAndCreateDirectory(agentDir),await copyDirectory(skill.path,agentDir),{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink",symlinkFailed:!0})),"installBySymlink"),installSkillForAgent=__name(async(skill,agentType,options={})=>{let agent=skillAgents[agentType],isGlobal=options.global??!1,cwd=options.cwd||process.cwd(),installMode=options.mode??"symlink";if(isGlobal&&agent.globalSkillsDir===void 0)return{success:!1,path:"",mode:installMode,error:`${agent.displayName} does not support global skill installation`};let skillName=sanitizeName(skill.name||basename3(skill.path)),canonicalBase=getCanonicalSkillsDir(isGlobal,cwd),canonicalDir=join10(canonicalBase,skillName),agentBase=getSkillAgentBaseDir(agentType,isGlobal,cwd),agentDir=join10(agentBase,skillName);if(!isPathSafe(canonicalBase,canonicalDir)||!isPathSafe(agentBase,agentDir))return{success:!1,path:agentDir,mode:installMode,error:"Invalid skill name: potential path traversal detected"};try{return installMode==="copy"?await installByCopy(skill,agentDir):await installBySymlink(skill,agentType,canonicalDir,agentDir,isGlobal)}catch(error){return{success:!1,path:agentDir,mode:installMode,error:toErrorMessage(error)}}},"installSkillForAgent"),OSC_RE=/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g,DCS_PM_APC_RE=/\x1b[P^_][\s\S]*?(?:\x1b\\)/g,CSI_RE=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/g,SIMPLE_ESC_RE=/\x1b[\x20-\x7e]/g,C1_RE=/[\x80-\x9f]/g,CONTROL_RE2=/[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1a\x1c-\x1f\x7f]/g,stripTerminalEscapes=__name(input=>input.replace(OSC_RE,"").replace(DCS_PM_APC_RE,"").replace(CSI_RE,"").replace(SIMPLE_ESC_RE,"").replace(C1_RE,"").replace(CONTROL_RE2,""),"stripTerminalEscapes"),sanitizeMetadata=__name(input=>stripTerminalEscapes(input).replace(/[\r\n]+/g," ").trim(),"sanitizeMetadata"),PRIORITY_RELATIVE_PATHS=["","skills","skills/.curated","skills/.experimental","skills/.system",".agents/skills",".aider-desk/skills",".augment/skills",".bob/skills",".claude/skills",".cline/skills",".codeartsdoer/skills",".codebuddy/skills",".codemaker/skills",".codestudio/skills",".codex/skills",".commandcode/skills",".continue/skills",".cortex/skills",".crush/skills",".cursor/skills",".factory/skills",".forge/skills",".gemini/skills",".github/skills",".goose/skills",".iflow/skills",".junie/skills",".kilocode/skills",".kiro/skills",".kode/skills",".mcpjam/skills",".mux/skills",".neovate/skills",".openhands/skills",".pi/skills",".pochi/skills",".qoder/skills",".qwen/skills",".roo/skills",".rovodev/skills",".tabnine/agent/skills",".trae/skills",".vibe/skills",".windsurf/skills",".zencoder/skills"],hasSkillManifest=__name(async dir=>{try{return(await stat(join10(dir,SKILL_MANIFEST_FILE))).isFile()}catch{return!1}},"hasSkillManifest"),parseSkillManifest=__name(async manifestPath=>{try{let content2=await readFile4(manifestPath,"utf-8"),{data:data2}=parseFrontmatter(content2);if(typeof data2.name!="string"||typeof data2.description!="string"||!data2.name||!data2.description)return null;let metadata=isPlainObject(data2.metadata)?data2.metadata:void 0;return{name:sanitizeMetadata(data2.name),description:sanitizeMetadata(data2.description),path:dirname6(manifestPath),rawContent:content2,metadata}}catch{return null}},"parseSkillManifest"),findSkillDirs=__name(async(dir,depth=0)=>{if(depth>5)return[];try{let[hasManifest,entries2]=await Promise.all([hasSkillManifest(dir),readdir(dir,{withFileTypes:!0}).catch(()=>[])]),currentDir=hasManifest?[dir]:[],subDirResults=await Promise.all(entries2.filter(entry=>entry.isDirectory()&&!SKIP_DISCOVERY_DIRS.has(entry.name)).map(entry=>findSkillDirs(join10(dir,entry.name),depth+1)));return[...currentDir,...subDirResults.flat()]}catch{return[]}},"findSkillDirs"),discoverSkills=__name(async(basePath,subpath,options)=>{if(subpath&&!isPathSafe(basePath,join10(basePath,subpath)))throw new Error(`Invalid subpath: "${subpath}" resolves outside the base directory. Subpath must not contain ".." segments that escape the base path.`);let searchPath=subpath?join10(basePath,subpath):basePath,seenNames=new Set,results=[],pluginGroupings=await getPluginGroupings(searchPath),enhanceSkill=__name(skill=>{let pluginName=pluginGroupings.get(resolve8(skill.path));return pluginName?{...skill,pluginName}:skill},"enhanceSkill"),pluginExtraDirs=await getPluginSkillPaths(searchPath);if(await hasSkillManifest(searchPath)){let skill=await parseSkillManifest(join10(searchPath,SKILL_MANIFEST_FILE));if(skill&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name),!options?.fullDepth))return results}let prioritySearchDirs=[...PRIORITY_RELATIVE_PATHS.map(relative3=>relative3?join10(searchPath,relative3):searchPath),...pluginExtraDirs];for(let dir of prioritySearchDirs)try{let entries2=await readdir(dir,{withFileTypes:!0});for(let entry of entries2){if(!entry.isDirectory())continue;let skillDir=join10(dir,entry.name);if(!await hasSkillManifest(skillDir))continue;let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}catch{}if(results.length===0||options?.fullDepth){let allSkillDirs=await findSkillDirs(searchPath);for(let skillDir of allSkillDirs){let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}return results},"discoverSkills"),getSkillDisplayName=__name(skill=>skill.name||basename3(skill.path),"getSkillDisplayName"),filterSkillsByName=__name((skills2,inputNames)=>{let normalizedInputs=inputNames.map(inputName=>inputName.toLowerCase());return skills2.filter(skill=>{let name=skill.name.toLowerCase(),displayName=getSkillDisplayName(skill).toLowerCase();return normalizedInputs.some(inputName=>inputName===name||inputName===displayName)})},"filterSkillsByName"),escapeRegex=__name(input=>input.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegex"),sanitizeSubpath=__name(subpath=>{let segments=subpath.replace(/\\/g,"/").split("/");for(let segment of segments)if(segment==="..")throw new Error(`Unsafe subpath: "${subpath}" contains path traversal segments. Subpaths must not contain ".." components.`);return subpath},"sanitizeSubpath"),HOST_CONFIGS=[{host:"github",domain:"github.com",prefix:"github:",treePrefix:"/tree/",anchorRepo:!1},{host:"gitlab",domain:"gitlab.com",prefix:"gitlab:",treePrefix:"/-/tree/",anchorRepo:!0}],HOST_BY_NAME=new Map(HOST_CONFIGS.map(config=>[config.host,config])),HOST_BY_DOMAIN=new Map(HOST_CONFIGS.map(config=>[config.domain,config])),SSH_URL_PATTERN=/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/,isLocalPath=__name(input=>isAbsolute3(input)||input.startsWith("./")||input.startsWith("../")||input==="."||input===".."||/^[a-zA-Z]:[/\\]/.test(input),"isLocalPath"),isShorthandCandidate=__name(input=>!input.includes(":")&&!input.startsWith(".")&&!input.startsWith("/"),"isShorthandCandidate"),buildHostedSource=__name(({host,owner,repo,ref,subpath,skillFilter})=>{let config=HOST_BY_NAME.get(host);if(!config)throw new Error(`Unknown host: ${host}`);let cleanRepo=repo.replace(/\.git$/,""),result={type:host,url:`https://${config.domain}/${owner}/${cleanRepo}.git`};return ref&&(result.ref=ref),subpath&&(result.subpath=sanitizeSubpath(subpath)),skillFilter&&(result.skillFilter=skillFilter),result},"buildHostedSource"),buildHostUrlPatterns=__name(config=>{let domain=escapeRegex(config.domain),treePrefix=escapeRegex(config.treePrefix),repoPattern=config.anchorRepo?`${domain}/([^/]+)/([^/]+?)(?:\\.git)?/?$`:`${domain}/([^/]+)/([^/]+)`;return{treeWithPath:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)/(.+)`),tree:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)$`),repo:new RegExp(repoPattern)}},"buildHostUrlPatterns"),HOST_URL_PATTERNS=new Map(HOST_CONFIGS.map(config=>[config.host,buildHostUrlPatterns(config)])),decodeFragmentValue=__name(value=>{try{return decodeURIComponent(value)}catch{return value}},"decodeFragmentValue"),looksLikeGitSource=__name(input=>{if(input.startsWith("git@")||HOST_CONFIGS.some(config=>input.startsWith(config.prefix)))return!0;if(input.startsWith("http://")||input.startsWith("https://"))try{let parsed=new URL(input),config=HOST_BY_DOMAIN.get(parsed.hostname);if(config){let treePrefix=escapeRegex(config.treePrefix);return new RegExp(`^/[^/]+/[^/]+(?:\\.git)?(?:${treePrefix}[^/]+(?:/.*)?)?/?$`).test(parsed.pathname)}}catch{return!1}return/^https?:\/\/.+\.git(?:$|[/?])/i.test(input)?!0:isShorthandCandidate(input)&&/^([^/]+)\/([^/]+)(?:\/(.+)|@(.+))?$/.test(input)},"looksLikeGitSource"),parseFragmentRef=__name(input=>{let hashIndex=input.indexOf("#");if(hashIndex<0)return{inputWithoutFragment:input};let inputWithoutFragment=input.slice(0,hashIndex),fragment=input.slice(hashIndex+1);if(!fragment||!looksLikeGitSource(inputWithoutFragment))return{inputWithoutFragment:input};let atIndex=fragment.indexOf("@");if(atIndex===-1)return{inputWithoutFragment,ref:decodeFragmentValue(fragment)};let ref=fragment.slice(0,atIndex),skillFilter=fragment.slice(atIndex+1);return{inputWithoutFragment,ref:ref?decodeFragmentValue(ref):void 0,skillFilter:skillFilter?decodeFragmentValue(skillFilter):void 0}},"parseFragmentRef"),isDirectSkillMdUrl=__name(input=>/^https?:\/\//.test(input)&&/\bSKILL\.md(?:$|\?|#)/i.test(input),"isDirectSkillMdUrl"),EXCLUDED_WELL_KNOWN_HOSTS=new Set(["raw.githubusercontent.com"]),isWellKnownCandidate=__name(input=>{if(!/^https?:\/\//.test(input))return!1;let parsed;try{parsed=new URL(input)}catch{return!1}return!(HOST_BY_DOMAIN.has(parsed.hostname)||EXCLUDED_WELL_KNOWN_HOSTS.has(parsed.hostname)||input.endsWith(".git")||isDirectSkillMdUrl(input))},"isWellKnownCandidate"),parseHostedShorthand=__name((rest,host,fragmentRef,fragmentSkillFilter)=>{let atSkillMatch=rest.match(/^([^/]+)\/([^/@]+)@(.+)$/);if(atSkillMatch){let[,owner,repo,skillFilter]=atSkillMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,skillFilter:fragmentSkillFilter??skillFilter})}let shorthandMatch=rest.match(/^([^/]+)\/([^/]+)(?:\/(.+?))?\/?$/);if(shorthandMatch){let[,owner,repo,subpath]=shorthandMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,subpath,skillFilter:fragmentSkillFilter})}return null},"parseHostedShorthand"),isHostnameAuthoritative=__name((input,expectedHostname)=>{if(!input.startsWith("http://")&&!input.startsWith("https://"))return!1;try{return new URL(input).hostname===expectedHostname}catch{return!1}},"isHostnameAuthoritative"),parseHostUrl=__name((input,host,fragmentRef)=>{let config=HOST_BY_NAME.get(host);if(!config||!isHostnameAuthoritative(input,config.domain))return null;let patterns=HOST_URL_PATTERNS.get(host);if(!patterns)return null;let treeWithPathMatch=input.match(patterns.treeWithPath);if(treeWithPathMatch){let[,owner,repo,ref,subpath]=treeWithPathMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef,subpath})}let treeMatch=input.match(patterns.tree);if(treeMatch){let[,owner,repo,ref]=treeMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef})}let repoMatch=input.match(patterns.repo);if(repoMatch){let[,owner,repo]=repoMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef})}return null},"parseHostUrl"),parseSshUrl=__name((input,fragmentRef,fragmentSkillFilter)=>{let match=input.match(SSH_URL_PATTERN);if(!match)return null;let[,sshHost]=match,result={type:HOST_BY_DOMAIN.get(sshHost)?.host??"git",url:input};return fragmentRef&&(result.ref=fragmentRef),fragmentSkillFilter&&(result.skillFilter=fragmentSkillFilter),result},"parseSshUrl"),parseSkillSource=__name(input=>{if(!input||input.trim().length===0)throw new Error("Invalid skill source: input is empty. Expected a local path, owner/repo shorthand, or URL.");if(isLocalPath(input)){let resolvedPath=resolve8(input);return{type:"local",url:resolvedPath,localPath:resolvedPath}}let{inputWithoutFragment,ref:fragmentRef,skillFilter:fragmentSkillFilter}=parseFragmentRef(input),normalized=inputWithoutFragment;for(let config of HOST_CONFIGS)if(normalized.startsWith(config.prefix)){let result2=parseHostedShorthand(normalized.slice(config.prefix.length),config.host,fragmentRef,fragmentSkillFilter);if(result2)return result2}if(normalized.startsWith("git@")){let sshResult=parseSshUrl(normalized,fragmentRef,fragmentSkillFilter);if(sshResult)return sshResult}for(let config of HOST_CONFIGS){let result2=parseHostUrl(normalized,config.host,fragmentRef);if(result2)return result2}if(isDirectSkillMdUrl(normalized))return{type:"url",url:normalized};if(isShorthandCandidate(normalized)){let result2=parseHostedShorthand(normalized,"github",fragmentRef,fragmentSkillFilter);if(result2)return result2}if(isWellKnownCandidate(normalized)){let wellKnownResult={type:"well-known",url:normalized};return fragmentSkillFilter&&(wellKnownResult.skillFilter=fragmentSkillFilter),wellKnownResult}let result={type:"git",url:normalized};return fragmentRef&&(result.ref=fragmentRef),result},"parseSkillSource"),resolveSource=__name(async parsed=>{if(parsed.type==="local"){if(!parsed.localPath)throw new Error("Local source is missing a resolved path");return{basePath:parsed.localPath}}if(parsed.type==="url"){let baseDir=await fetchSkillManifestFromUrl(parsed.url);return{basePath:baseDir,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}if(parsed.type==="well-known"){let baseDir=await fetchWellKnownSkills(parsed.url);return{basePath:baseDir,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}let cloneDir=await cloneRepo2(parsed.url,parsed.ref);return{basePath:cloneDir,subpath:parsed.subpath,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(cloneDir),"cleanup")}},"resolveSource"),resolveTargetAgents=__name(async requested=>{if(requested&&requested.length>0)return requested;let installed=await detectInstalledSkillAgents();return installed.length>0?installed:getUniversalSkillAgents()},"resolveTargetAgents"),resolveSkillFilters=__name((explicit,fromSource)=>{if(explicit&&explicit.length>0)return explicit;if(fromSource)return[fromSource]},"resolveSkillFilters"),installSkillsFromSource=__name(async options=>{let resolved=await resolveSource(parseSkillSource(options.source));try{let filters2=resolveSkillFilters(options.skills,resolved.skillFilter),discovered=await discoverSkills(resolved.basePath,resolved.subpath),skills2=filters2?filterSkillsByName(discovered,filters2):discovered;if(skills2.length===0)return{installed:[],failed:[],skills:[]};let targetAgents=await resolveTargetAgents(options.agents),installed=[],failed=[];for(let skill of skills2)for(let agent of targetAgents){let result=await installSkillForAgent(skill,agent,{global:options.global,cwd:options.cwd,mode:options.mode});result.success?installed.push({skill:skill.name,agent,path:result.path,canonicalPath:result.canonicalPath,mode:result.mode,symlinkFailed:result.symlinkFailed}):failed.push({skill:skill.name,agent,error:result.error??"Unknown error"})}return{installed,failed,skills:skills2}}finally{await resolved.cleanup?.().catch(()=>{})}},"installSkillsFromSource")}});var CharacterCodes,init_scanner=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js"(){"use strict";(function(CharacterCodes2){CharacterCodes2[CharacterCodes2.lineFeed=10]="lineFeed",CharacterCodes2[CharacterCodes2.carriageReturn=13]="carriageReturn",CharacterCodes2[CharacterCodes2.space=32]="space",CharacterCodes2[CharacterCodes2._0=48]="_0",CharacterCodes2[CharacterCodes2._1=49]="_1",CharacterCodes2[CharacterCodes2._2=50]="_2",CharacterCodes2[CharacterCodes2._3=51]="_3",CharacterCodes2[CharacterCodes2._4=52]="_4",CharacterCodes2[CharacterCodes2._5=53]="_5",CharacterCodes2[CharacterCodes2._6=54]="_6",CharacterCodes2[CharacterCodes2._7=55]="_7",CharacterCodes2[CharacterCodes2._8=56]="_8",CharacterCodes2[CharacterCodes2._9=57]="_9",CharacterCodes2[CharacterCodes2.a=97]="a",CharacterCodes2[CharacterCodes2.b=98]="b",CharacterCodes2[CharacterCodes2.c=99]="c",CharacterCodes2[CharacterCodes2.d=100]="d",CharacterCodes2[CharacterCodes2.e=101]="e",CharacterCodes2[CharacterCodes2.f=102]="f",CharacterCodes2[CharacterCodes2.g=103]="g",CharacterCodes2[CharacterCodes2.h=104]="h",CharacterCodes2[CharacterCodes2.i=105]="i",CharacterCodes2[CharacterCodes2.j=106]="j",CharacterCodes2[CharacterCodes2.k=107]="k",CharacterCodes2[CharacterCodes2.l=108]="l",CharacterCodes2[CharacterCodes2.m=109]="m",CharacterCodes2[CharacterCodes2.n=110]="n",CharacterCodes2[CharacterCodes2.o=111]="o",CharacterCodes2[CharacterCodes2.p=112]="p",CharacterCodes2[CharacterCodes2.q=113]="q",CharacterCodes2[CharacterCodes2.r=114]="r",CharacterCodes2[CharacterCodes2.s=115]="s",CharacterCodes2[CharacterCodes2.t=116]="t",CharacterCodes2[CharacterCodes2.u=117]="u",CharacterCodes2[CharacterCodes2.v=118]="v",CharacterCodes2[CharacterCodes2.w=119]="w",CharacterCodes2[CharacterCodes2.x=120]="x",CharacterCodes2[CharacterCodes2.y=121]="y",CharacterCodes2[CharacterCodes2.z=122]="z",CharacterCodes2[CharacterCodes2.A=65]="A",CharacterCodes2[CharacterCodes2.B=66]="B",CharacterCodes2[CharacterCodes2.C=67]="C",CharacterCodes2[CharacterCodes2.D=68]="D",CharacterCodes2[CharacterCodes2.E=69]="E",CharacterCodes2[CharacterCodes2.F=70]="F",CharacterCodes2[CharacterCodes2.G=71]="G",CharacterCodes2[CharacterCodes2.H=72]="H",CharacterCodes2[CharacterCodes2.I=73]="I",CharacterCodes2[CharacterCodes2.J=74]="J",CharacterCodes2[CharacterCodes2.K=75]="K",CharacterCodes2[CharacterCodes2.L=76]="L",CharacterCodes2[CharacterCodes2.M=77]="M",CharacterCodes2[CharacterCodes2.N=78]="N",CharacterCodes2[CharacterCodes2.O=79]="O",CharacterCodes2[CharacterCodes2.P=80]="P",CharacterCodes2[CharacterCodes2.Q=81]="Q",CharacterCodes2[CharacterCodes2.R=82]="R",CharacterCodes2[CharacterCodes2.S=83]="S",CharacterCodes2[CharacterCodes2.T=84]="T",CharacterCodes2[CharacterCodes2.U=85]="U",CharacterCodes2[CharacterCodes2.V=86]="V",CharacterCodes2[CharacterCodes2.W=87]="W",CharacterCodes2[CharacterCodes2.X=88]="X",CharacterCodes2[CharacterCodes2.Y=89]="Y",CharacterCodes2[CharacterCodes2.Z=90]="Z",CharacterCodes2[CharacterCodes2.asterisk=42]="asterisk",CharacterCodes2[CharacterCodes2.backslash=92]="backslash",CharacterCodes2[CharacterCodes2.closeBrace=125]="closeBrace",CharacterCodes2[CharacterCodes2.closeBracket=93]="closeBracket",CharacterCodes2[CharacterCodes2.colon=58]="colon",CharacterCodes2[CharacterCodes2.comma=44]="comma",CharacterCodes2[CharacterCodes2.dot=46]="dot",CharacterCodes2[CharacterCodes2.doubleQuote=34]="doubleQuote",CharacterCodes2[CharacterCodes2.minus=45]="minus",CharacterCodes2[CharacterCodes2.openBrace=123]="openBrace",CharacterCodes2[CharacterCodes2.openBracket=91]="openBracket",CharacterCodes2[CharacterCodes2.plus=43]="plus",CharacterCodes2[CharacterCodes2.slash=47]="slash",CharacterCodes2[CharacterCodes2.formFeed=12]="formFeed",CharacterCodes2[CharacterCodes2.tab=9]="tab"})(CharacterCodes||(CharacterCodes={}))}});var cachedSpaces,maxCachedValues,cachedBreakLinesWithSpaces,init_string_intern=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js"(){cachedSpaces=new Array(20).fill(0).map((_,index2)=>" ".repeat(index2)),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index2)=>`
518
518
  `+" ".repeat(index2)),"\r":new Array(maxCachedValues).fill(0).map((_,index2)=>"\r"+" ".repeat(index2)),"\r\n":new Array(maxCachedValues).fill(0).map((_,index2)=>`\r
@@ -685,7 +685,7 @@ Aborted. Deleting project ${projectName}\u2026
685
685
  `),outcome={area:planned.area,status:"complete",durationMs:Date.now()-started}}catch(error){outcome={area:planned.area,status:error instanceof TimeoutError?"timed-out":"failed",durationMs:Date.now()-started,error:error instanceof Error?error.message:"Analyzer failed before completion."},fs38.rmSync(path40.join(source.projectRoot,planned.fragmentPath),{force:!0})}return writeAtomic(receiptPath(source.projectRoot,planned.area),`${JSON.stringify(outcome,null,2)}
686
686
  `),outcome}function reconcileMigrationInventory(projectRootInput){let source=readSourceContract(projectRootInput),plan=readPlan(source);try{let fragments=plan.areas.map(item=>{let fragment=readJson3(path40.join(source.projectRoot,item.fragmentPath));return validateFragment(fragment,item),fragment}).sort((left,right)=>compareStrings(left.area,right.area)),inventory=mergeFragments(source,plan,fragments);return writeAtomic(source.inventoryOutputPath,`${JSON.stringify(inventory,null,2)}
687
687
  `),writeRunReceipt(source,plan,{status:"complete"}),inventory}catch(error){throw writeRunReceipt(source,plan,{status:"rejected",error:error instanceof Error?error.message:"Fan-in rejected."}),error}}async function runAreasSequential(projectRoot,areas,timeoutMs){for(let area of areas)await runMigrationInventoryArea(projectRoot,area,timeoutMs)}async function analyzeRuntimeConfig(sourceRoot){let framework=await detectProjectFramework(sourceRoot),packagePath=path40.join(sourceRoot,"package.json"),configPath=path40.join(sourceRoot,".fimo","config.json"),evidence=existingRelativePaths(sourceRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"]).map(file=>({claim:"framework.config",path:file}));return fs38.existsSync(packagePath)&&evidence.push({claim:"package.manifest",path:"package.json"}),fs38.existsSync(configPath)&&evidence.push({claim:"fimo.config",path:".fimo/config.json"}),{version:1,area:"runtime-config",facts:{framework:framework?.slug??null,frameworkName:framework?.name??null,fimoConfigExists:fs38.existsSync(configPath)},evidence:evidence.sort(compareEvidence),unresolved:framework?[]:[{code:"framework-not-detected",claim:"Generic framework detection did not identify the source framework."}]}}async function analyzeLocales(sourceRoot){let result=await execFileAsync8(process.execPath,[NEXT_INTL_ANALYZER,sourceRoot],{maxBuffer:2e6}),parsed=JSON.parse(result.stdout);if(parsed.version!==1||parsed.area!=="locales"||!isRecord2(parsed.facts)||!Array.isArray(parsed.evidence)||!Array.isArray(parsed.unresolved))throw new Error("Invalid next-intl analyzer output.");return{version:1,area:"locales",facts:parsed.facts,evidence:parsed.evidence,unresolved:parsed.unresolved}}function mergeFragments(source,plan,fragments){let plannedAreas=new Set(plan.areas.map(item=>item.area));if(new Set(fragments.map(fragment=>fragment.area)).size!==fragments.length||fragments.some(fragment=>!plannedAreas.has(fragment.area)))throw new Error("Fragment ownership does not match the inventory plan.");let facts={};for(let fragment of fragments)for(let[key,value]of Object.entries(fragment.facts)){if(key in facts&&JSON.stringify(facts[key])!==JSON.stringify(value))throw new Error(`Conflicting fact: ${key}`);facts[key]=value}let evidence=fragments.flatMap(fragment=>fragment.evidence.map(item=>({area:fragment.area,...item}))).sort(compareEvidenceWithArea),unresolved=fragments.flatMap(fragment=>fragment.unresolved.map(item=>({area:fragment.area,...item}))).sort((a,b)=>compareStrings(`${a.area}\0${a.code}\0${a.claim}`,`${b.area}\0${b.code}\0${b.claim}`));return{version:1,source:{rootPath:source.rootPath,inventoryPath:source.inventoryPath},facts,evidence,unresolved,fragments}}function validateFragment(input,planned){if(!isRecord2(input)||input.version!==1||input.area!==planned.area||planned.owner!==input.area||!isRecord2(input.facts)||!Array.isArray(input.evidence)||!Array.isArray(input.unresolved))throw new Error(`Invalid fragment for area: ${planned.area}`);if(Object.keys(input).some(key=>!["version","area","facts","evidence","unresolved"].includes(key)))throw new Error("Fragments may contain source evidence only.");if(!Object.values(input.facts).every(isJsonValue))throw new Error(`Invalid fragment facts for area: ${planned.area}`);if(!input.evidence.every(isEvidence)||!input.unresolved.every(isUnresolved))throw new Error(`Invalid fragment for area: ${planned.area}`);for(let item of input.evidence)if(!isSafeEvidencePath(item.path))throw new Error(`Unsafe evidence path: ${item.path}`)}function readSourceContract(projectRootInput){let projectRoot=path40.resolve(projectRootInput),manifest=readJson3(path40.join(projectRoot,MIGRATION_DIR,"manifest.json"));if(!isRecord2(manifest)||manifest.version!==1||!isRecord2(manifest.source))throw new Error("Invalid canonical migration manifest.");let rootPath=manifest.source.rootPath,inventoryPath=manifest.source.inventoryPath;if(typeof rootPath!="string"||typeof inventoryPath!="string"||path40.isAbsolute(rootPath)||path40.isAbsolute(inventoryPath)||!isSafeEvidencePath(rootPath)||!isSafeEvidencePath(inventoryPath))throw new Error("Migration manifest paths must be safe relative paths.");let sourceRoot=path40.resolve(projectRoot,rootPath);if(!fs38.existsSync(sourceRoot)||!fs38.statSync(sourceRoot).isDirectory()||!isWithin(projectRoot,sourceRoot))throw new Error(`Migration source root does not exist: ${sourceRoot}`);return{projectRoot,sourceRoot,rootPath:toPosix(rootPath),inventoryPath:toPosix(inventoryPath),inventoryOutputPath:path40.resolve(projectRoot,inventoryPath),planPath:path40.join(projectRoot,MIGRATION_DIR,"inventory-plan.json"),runPath:path40.join(projectRoot,MIGRATION_DIR,"inventory-run.json")}}function readPlan(source){let plan=readJson3(source.planPath);if(!isRecord2(plan)||plan.version!==1||!isRecord2(plan.source)||!Array.isArray(plan.areas)||plan.areas.length===0)throw new Error("Invalid or missing inventory plan. Run prepare first.");if(plan.source.rootPath!==source.rootPath||plan.source.inventoryPath!==source.inventoryPath)throw new Error("Inventory plan source no longer matches the migration manifest. Run prepare again.");let areas=plan.areas;if(!areas.every(item=>isRecord2(item)&&ANALYZER_AREAS.includes(item.area)&&item.owner===item.area&&typeof item.fragmentPath=="string"&&item.fragmentPath===`${FRAGMENT_DIR}/${item.area}.json`))throw new Error("Invalid inventory plan area ownership.");if(new Set(areas.map(item=>item.area)).size!==areas.length)throw new Error("Duplicate area in inventory plan.");let packageManifest=readJson3(path40.join(source.sourceRoot,"package.json")),expectedAreas=declaredPackageVersion(packageManifest,"next-intl")?["runtime-config","locales"]:["runtime-config"];if(JSON.stringify(areas.map(item=>item.area))!==JSON.stringify(expectedAreas))throw new Error("Inventory plan areas no longer match the source. Run prepare again.");return plan}function writeRunReceipt(source,plan,reconcile){let outcomes=plan.areas.map(item=>readJsonIfPresent(receiptPath(source.projectRoot,item.area))?readAreaOutcome(source.projectRoot,item.area):{area:item.area,status:"failed",durationMs:0,error:`Missing execution receipt: ${item.area}`});writeAtomic(source.runPath,`${JSON.stringify({version:1,outcomes,reconcile},null,2)}
688
- `)}function receiptPath(projectRoot,area){return path40.join(projectRoot,MIGRATION_DIR,`inventory-run-${area}.json`)}function readAreaOutcome(projectRoot,area){let outcome=readJson3(receiptPath(projectRoot,area));if(!isRecord2(outcome)||outcome.area!==area||!["complete","failed","timed-out"].includes(String(outcome.status))||typeof outcome.durationMs!="number"||!Number.isInteger(outcome.durationMs)||outcome.durationMs<0||outcome.error!==void 0&&typeof outcome.error!="string")throw new Error(`Invalid execution receipt: ${area}`);return outcome}function writeAtomic(filePath,bytes){fs38.mkdirSync(path40.dirname(filePath),{recursive:!0});let temporaryPath=`${filePath}.${process.pid}.tmp`;try{fs38.writeFileSync(temporaryPath,bytes),fs38.renameSync(temporaryPath,filePath)}catch(error){throw fs38.rmSync(temporaryPath,{force:!0}),error}}function readJson3(filePath){try{return JSON.parse(fs38.readFileSync(filePath,"utf8"))}catch{throw new Error(`Unable to read JSON file: ${filePath}`)}}function readJsonIfPresent(filePath){return fs38.existsSync(filePath)?readJson3(filePath):null}function declaredPackageVersion(manifest,packageName){if(!isRecord2(manifest))return null;for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let packages=manifest[group];if(isRecord2(packages)&&typeof packages[packageName]=="string")return packages[packageName]}return null}function existingRelativePaths(root2,candidates){return candidates.filter(candidate=>fs38.existsSync(path40.join(root2,candidate))).map(toPosix).sort()}function isRecord2(input){return typeof input=="object"&&input!==null&&!Array.isArray(input)}function isEvidence(input){return isRecord2(input)&&typeof input.claim=="string"&&typeof input.path=="string"&&(input.line===void 0||typeof input.line=="number"&&Number.isInteger(input.line)&&input.line>0)&&(input.value===void 0||isJsonValue(input.value))}function isUnresolved(input){return isRecord2(input)&&typeof input.code=="string"&&typeof input.claim=="string"&&(input.locale===void 0||typeof input.locale=="string")}function isJsonValue(input){return input===null||["boolean","string"].includes(typeof input)?!0:typeof input=="number"?Number.isFinite(input):Array.isArray(input)?input.every(isJsonValue):isRecord2(input)&&Object.values(input).every(isJsonValue)}function isSafeEvidencePath(value){return value!==""&&!path40.isAbsolute(value)&&!value.split(/[\\/]/).some(part=>part==="..")}function isWithin(parent2,candidate){let relative3=path40.relative(parent2,candidate);return relative3===""||!relative3.startsWith(`..${path40.sep}`)&&relative3!==".."&&!path40.isAbsolute(relative3)}function toPosix(value){return value.split(path40.sep).join("/")}function compareStrings(left,right){return left<right?-1:left>right?1:0}function compareEvidence(left,right){return compareStrings(`${left.path}\0${left.line??0}\0${left.claim}\0${JSON.stringify(left.value)}`,`${right.path}\0${right.line??0}\0${right.claim}\0${JSON.stringify(right.value)}`)}function compareEvidenceWithArea(left,right){return compareStrings(`${left.area}\0${left.path}\0${left.line??0}\0${left.claim}`,`${right.area}\0${right.path}\0${right.line??0}\0${right.claim}`)}async function withTimeout(promise,timeoutMs){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new TimeoutError(`Analyzer timed out after ${timeoutMs}ms.`)),timeoutMs)});try{return await Promise.race([promise,timeout])}finally{timer&&clearTimeout(timer)}}var execFileAsync8,INVENTORY_VERSION,DEFAULT_ANALYZER_TIMEOUT_MS,ANALYZER_AREAS,MIGRATION_DIR,FRAGMENT_DIR,NEXT_INTL_ANALYZER,TimeoutError,init_migration_inventory=__esm({"src/cli/migration-inventory.ts"(){init_dist7();execFileAsync8=promisify9(execFile9),INVENTORY_VERSION=1,DEFAULT_ANALYZER_TIMEOUT_MS=5e3,ANALYZER_AREAS=["runtime-config","locales"],MIGRATION_DIR=path40.join(".fimo","migration"),FRAGMENT_DIR=path40.join(MIGRATION_DIR,"inventory-fragments"),NEXT_INTL_ANALYZER=path40.resolve(path40.dirname(fileURLToPath6(import.meta.url)),"../../assets/skills/fimo-migration/scripts/inventory/locales/next-intl.mjs");__name(runMigrationInventory,"runMigrationInventory");__name(prepareMigrationInventory,"prepareMigrationInventory");__name(runMigrationInventoryArea,"runMigrationInventoryArea");__name(reconcileMigrationInventory,"reconcileMigrationInventory");__name(runAreasSequential,"runAreasSequential");__name(analyzeRuntimeConfig,"analyzeRuntimeConfig");__name(analyzeLocales,"analyzeLocales");__name(mergeFragments,"mergeFragments");__name(validateFragment,"validateFragment");__name(readSourceContract,"readSourceContract");__name(readPlan,"readPlan");__name(writeRunReceipt,"writeRunReceipt");__name(receiptPath,"receiptPath");__name(readAreaOutcome,"readAreaOutcome");__name(writeAtomic,"writeAtomic");__name(readJson3,"readJson");__name(readJsonIfPresent,"readJsonIfPresent");__name(declaredPackageVersion,"declaredPackageVersion");__name(existingRelativePaths,"existingRelativePaths");__name(isRecord2,"isRecord");__name(isEvidence,"isEvidence");__name(isUnresolved,"isUnresolved");__name(isJsonValue,"isJsonValue");__name(isSafeEvidencePath,"isSafeEvidencePath");__name(isWithin,"isWithin");__name(toPosix,"toPosix");__name(compareStrings,"compareStrings");__name(compareEvidence,"compareEvidence");__name(compareEvidenceWithArea,"compareEvidenceWithArea");TimeoutError=class extends Error{static{__name(this,"TimeoutError")}};__name(withTimeout,"withTimeout")}});import fs39 from"node:fs";import path41 from"node:path";function applyMigrationManifest(options){let{cwd,manifest}=options,written=[],warnings=[],previousArtifacts=readArtifactIndex(cwd);cleanupPreviousArtifacts(cwd,previousArtifacts),resetDir(path41.join(cwd,GENERATED_PAGES_DIR)),resetDir(path41.join(cwd,GENERATED_COMPONENTS_DIR)),resetDir(path41.join(cwd,GENERATED_ROOT)),ensureDir(path41.join(cwd,SCHEMAS_DIR)),ensureDir(path41.join(cwd,FORMS_DIR));let theme=pickThemePalette(manifest),siteName=deriveSiteName(manifest),navPages=selectNavPages(manifest.pages),legalRoutes=selectLegalRoutes(manifest.pages),plannedPages=planPages(manifest.pages);manifest.forms.length>0&&warnings.push("Draft form JSON files were generated, but they still need `fimo forms push` before they can submit live data."),manifest.collections.length>0&&warnings.push("Collection schemas and seed entries were generated but NOT imported. The migration is not complete until you `fimo schemas push` and `fimo entries create` them into Fimo (or mark them unresolved)."),writeFile2(cwd,"design.md",buildDesignDoc(manifest,theme,siteName),written),writeFile2(cwd,"src/index.css",buildThemeCss(theme),written),writeFile2(cwd,path41.join(GENERATED_COMPONENTS_DIR,"MigrationShell.tsx"),buildMigrationShellComponent(),written),writeFile2(cwd,path41.join(GENERATED_COMPONENTS_DIR,"MigrationPageTemplate.tsx"),buildMigrationPageTemplateComponent(),written);for(let plannedPage of plannedPages)writeFile2(cwd,plannedPage.modulePath,buildPageModule(plannedPage,navPages,legalRoutes,siteName),written);writeFile2(cwd,"src/routes.ts",buildRoutesFile(plannedPages,legalRoutes),written),writeFile2(cwd,path41.relative(cwd,resolveProjectConfigPath(cwd)),buildFimoConfig(manifest,plannedPages,legalRoutes,siteName),written);let schemaFiles=writeSchemas(cwd,manifest.collections,written),formFiles=writeForms(cwd,manifest.forms,written),generatedNotes=writeGeneratedNotes(cwd,manifest,siteName,warnings,written);writeCollectionSeeds(cwd,manifest,written);let schemasResult=syncSchemas({cwd,framework:"react-router",verbose:!1}),formsResult=syncForms({cwd,verbose:!1}),translations2={created:[],updated:[],deleted:[]},artifactIndex={pageFiles:plannedPages.map(page=>toPosix2(page.modulePath)),componentFiles:[toPosix2(path41.join(GENERATED_COMPONENTS_DIR,"MigrationShell.tsx")),toPosix2(path41.join(GENERATED_COMPONENTS_DIR,"MigrationPageTemplate.tsx"))],schemaFiles:schemaFiles.map(toPosix2),formFiles:formFiles.map(toPosix2),generatedFiles:generatedNotes.map(toPosix2)};return writeFile2(cwd,path41.join(GENERATED_ROOT,"artifacts.json"),JSON.stringify(artifactIndex,null,2)+`
688
+ `)}function receiptPath(projectRoot,area){return path40.join(projectRoot,MIGRATION_DIR,`inventory-run-${area}.json`)}function readAreaOutcome(projectRoot,area){let outcome=readJson3(receiptPath(projectRoot,area));if(!isRecord2(outcome)||outcome.area!==area||!["complete","failed","timed-out"].includes(String(outcome.status))||typeof outcome.durationMs!="number"||!Number.isInteger(outcome.durationMs)||outcome.durationMs<0||outcome.error!==void 0&&typeof outcome.error!="string")throw new Error(`Invalid execution receipt: ${area}`);return outcome}function writeAtomic(filePath,bytes){fs38.mkdirSync(path40.dirname(filePath),{recursive:!0});let temporaryPath=`${filePath}.${process.pid}.tmp`;try{fs38.writeFileSync(temporaryPath,bytes),fs38.renameSync(temporaryPath,filePath)}catch(error){throw fs38.rmSync(temporaryPath,{force:!0}),error}}function readJson3(filePath){try{return JSON.parse(fs38.readFileSync(filePath,"utf8"))}catch{throw new Error(`Unable to read JSON file: ${filePath}`)}}function readJsonIfPresent(filePath){return fs38.existsSync(filePath)?readJson3(filePath):null}function declaredPackageVersion(manifest,packageName){if(!isRecord2(manifest))return null;for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let packages=manifest[group];if(isRecord2(packages)&&typeof packages[packageName]=="string")return packages[packageName]}return null}function existingRelativePaths(root2,candidates){return candidates.filter(candidate=>fs38.existsSync(path40.join(root2,candidate))).map(toPosix).sort()}function isRecord2(input){return typeof input=="object"&&input!==null&&!Array.isArray(input)}function isEvidence(input){return isRecord2(input)&&typeof input.claim=="string"&&typeof input.path=="string"&&(input.line===void 0||typeof input.line=="number"&&Number.isInteger(input.line)&&input.line>0)&&(input.value===void 0||isJsonValue(input.value))}function isUnresolved(input){return isRecord2(input)&&typeof input.code=="string"&&typeof input.claim=="string"&&(input.locale===void 0||typeof input.locale=="string")}function isJsonValue(input){return input===null||["boolean","string"].includes(typeof input)?!0:typeof input=="number"?Number.isFinite(input):Array.isArray(input)?input.every(isJsonValue):isRecord2(input)&&Object.values(input).every(isJsonValue)}function isSafeEvidencePath(value){return value!==""&&!path40.isAbsolute(value)&&!value.split(/[\\/]/).some(part=>part==="..")}function isWithin(parent2,candidate){let relative3=path40.relative(parent2,candidate);return relative3===""||!relative3.startsWith(`..${path40.sep}`)&&relative3!==".."&&!path40.isAbsolute(relative3)}function toPosix(value){return value.split(path40.sep).join("/")}function compareStrings(left,right){return left<right?-1:left>right?1:0}function compareEvidence(left,right){return compareStrings(`${left.path}\0${left.line??0}\0${left.claim}\0${JSON.stringify(left.value)}`,`${right.path}\0${right.line??0}\0${right.claim}\0${JSON.stringify(right.value)}`)}function compareEvidenceWithArea(left,right){return compareStrings(`${left.area}\0${left.path}\0${left.line??0}\0${left.claim}`,`${right.area}\0${right.path}\0${right.line??0}\0${right.claim}`)}async function withTimeout(promise,timeoutMs){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new TimeoutError(`Analyzer timed out after ${timeoutMs}ms.`)),timeoutMs)});try{return await Promise.race([promise,timeout])}finally{timer&&clearTimeout(timer)}}var execFileAsync8,INVENTORY_VERSION,DEFAULT_ANALYZER_TIMEOUT_MS,ANALYZER_AREAS,MIGRATION_DIR,FRAGMENT_DIR,NEXT_INTL_ANALYZER,TimeoutError,init_migration_inventory=__esm({"src/cli/migration-inventory.ts"(){init_dist7();execFileAsync8=promisify9(execFile9),INVENTORY_VERSION=1,DEFAULT_ANALYZER_TIMEOUT_MS=5e3,ANALYZER_AREAS=["runtime-config","locales"],MIGRATION_DIR=path40.join(".fimo","migration"),FRAGMENT_DIR=path40.join(MIGRATION_DIR,"inventory-fragments"),NEXT_INTL_ANALYZER=path40.resolve(path40.dirname(fileURLToPath6(import.meta.url)),"../../assets/skills/fimo-migration/scripts/inventory/locales/next-intl.mjs");__name(runMigrationInventory,"runMigrationInventory");__name(prepareMigrationInventory,"prepareMigrationInventory");__name(runMigrationInventoryArea,"runMigrationInventoryArea");__name(reconcileMigrationInventory,"reconcileMigrationInventory");__name(runAreasSequential,"runAreasSequential");__name(analyzeRuntimeConfig,"analyzeRuntimeConfig");__name(analyzeLocales,"analyzeLocales");__name(mergeFragments,"mergeFragments");__name(validateFragment,"validateFragment");__name(readSourceContract,"readSourceContract");__name(readPlan,"readPlan");__name(writeRunReceipt,"writeRunReceipt");__name(receiptPath,"receiptPath");__name(readAreaOutcome,"readAreaOutcome");__name(writeAtomic,"writeAtomic");__name(readJson3,"readJson");__name(readJsonIfPresent,"readJsonIfPresent");__name(declaredPackageVersion,"declaredPackageVersion");__name(existingRelativePaths,"existingRelativePaths");__name(isRecord2,"isRecord");__name(isEvidence,"isEvidence");__name(isUnresolved,"isUnresolved");__name(isJsonValue,"isJsonValue");__name(isSafeEvidencePath,"isSafeEvidencePath");__name(isWithin,"isWithin");__name(toPosix,"toPosix");__name(compareStrings,"compareStrings");__name(compareEvidence,"compareEvidence");__name(compareEvidenceWithArea,"compareEvidenceWithArea");TimeoutError=class extends Error{static{__name(this,"TimeoutError")}};__name(withTimeout,"withTimeout")}});import fs39 from"node:fs";import path41 from"node:path";function applyMigrationManifest(options){let{cwd,manifest}=options,written=[],warnings=[],previousArtifacts=readArtifactIndex(cwd);cleanupPreviousArtifacts(cwd,previousArtifacts),resetDir(path41.join(cwd,GENERATED_PAGES_DIR)),resetDir(path41.join(cwd,GENERATED_COMPONENTS_DIR)),resetDir(path41.join(cwd,GENERATED_ROOT)),ensureDir(path41.join(cwd,SCHEMAS_DIR)),ensureDir(path41.join(cwd,FORMS_DIR));let theme=pickThemePalette(manifest),siteName=deriveSiteName(manifest),navPages=selectNavPages(manifest.pages),legalRoutes=selectLegalRoutes(manifest.pages),plannedPages=planPages(manifest.pages);manifest.forms.length>0&&warnings.push("Draft form JSON files were generated, but they still need `fimo forms push` before they can submit live data."),manifest.collections.length>0&&warnings.push("Collection schemas and seed entries were generated but NOT imported. The migration is not complete until you `fimo schemas push` and `fimo entries create` them into Fimo (or mark them unresolved)."),writeFile2(cwd,"design.md",buildDesignDoc(manifest,theme,siteName),written),writeFile2(cwd,"src/index.css",buildThemeCss(theme),written),writeFile2(cwd,path41.join(GENERATED_COMPONENTS_DIR,"MigrationShell.tsx"),buildMigrationShellComponent(),written),writeFile2(cwd,path41.join(GENERATED_COMPONENTS_DIR,"MigrationPageTemplate.tsx"),buildMigrationPageTemplateComponent(),written);for(let plannedPage of plannedPages)writeFile2(cwd,plannedPage.modulePath,buildPageModule(plannedPage,navPages,legalRoutes,siteName),written);writeFile2(cwd,"src/routes.ts",buildRoutesFile(plannedPages,legalRoutes),written),writeFile2(cwd,path41.relative(cwd,resolveProjectConfigPath(cwd)),buildFimoConfig(manifest,plannedPages,legalRoutes,siteName),written);let schemaFiles=writeSchemas(cwd,manifest.collections,written),formFiles=writeForms(cwd,manifest.forms,written),generatedNotes=writeGeneratedNotes(cwd,manifest,siteName,warnings,written);writeCollectionSeeds(cwd,manifest,written);let schemasResult=syncSchemas({cwd,framework:"react-router",verbose:!1}),formsResult=syncForms({cwd,framework:"react-router",verbose:!1}),translations2={created:[],updated:[],deleted:[]},artifactIndex={pageFiles:plannedPages.map(page=>toPosix2(page.modulePath)),componentFiles:[toPosix2(path41.join(GENERATED_COMPONENTS_DIR,"MigrationShell.tsx")),toPosix2(path41.join(GENERATED_COMPONENTS_DIR,"MigrationPageTemplate.tsx"))],schemaFiles:schemaFiles.map(toPosix2),formFiles:formFiles.map(toPosix2),generatedFiles:generatedNotes.map(toPosix2)};return writeFile2(cwd,path41.join(GENERATED_ROOT,"artifacts.json"),JSON.stringify(artifactIndex,null,2)+`
689
689
  `,written),{written,warnings,pagesWritten:plannedPages.length,schemasWritten:manifest.collections.length,formsWritten:manifest.forms.length,translations:{created:translations2.created.length,updated:translations2.updated.length,deleted:translations2.deleted.length},codegen:{schemas:schemasResult,forms:formsResult}}}function pickThemePalette(manifest){let colors=unique(manifest.design.tokens.colors.map(color=>normalizeColorToken(color)).filter(color=>!!color)),lightColors=colors.filter(color=>{let luminance=getLuminance(color);return luminance!==null&&luminance>=.74}),darkColors=colors.filter(color=>{let luminance=getLuminance(color);return luminance!==null&&luminance<=.28}),midColors=colors.filter(color=>!lightColors.includes(color)&&!darkColors.includes(color)),background=lightColors[0]??"#f7f1e8",foreground=darkColors[0]??"#1a1612",primary=midColors[0]??colors[1]??"#b56b42",accent=midColors[1]??colors[2]??"#d79f6a",secondary=lightColors[1]??"#efe4d6",radius=manifest.design.tokens.radius[0]??"20px",bodyFont=pickBodyFont(manifest),displayFont=pickDisplayFont(manifest,bodyFont),importFamilies=unique([bodyFont,displayFont].filter(family=>shouldImportFont(family)));return{background,foreground,primary,accent,secondary,border:withAlpha(foreground,.12),input:withAlpha(foreground,.12),muted:secondary,mutedForeground:withAlpha(foreground,.68),ring:primary,radius,bodyFont,displayFont,fontImport:importFamilies.length>0?buildGoogleFontImport(importFamilies):null}}function buildSchemaDefinition(collection){let fields={};for(let field of collection.fields)fields[field]={type:fieldTypeForSchemaField(field)};return{uid:collection.suggestedSchema,name:pluralLabelForSchema(collection),fields}}function buildFormDefinition(form){let fields=Object.fromEntries(form.fields.map(field=>[field.name,{type:normalizeFormFieldType(field.kind),label:field.label||titleize2(field.name),required:field.required||void 0,placeholder:field.placeholder||void 0,...field.options&&field.options.length>0?{options:field.options}:{}}]));return{name:form.name,label:titleize2(form.name),fields}}function writeSchemas(cwd,collections,written){let filePaths=[];for(let collection of collections){let definition=buildSchemaDefinition(collection),relativePath=path41.join(SCHEMAS_DIR,`${definition.uid}.json`);writeFile2(cwd,relativePath,JSON.stringify(definition,null,2)+`
690
690
  `,written),filePaths.push(relativePath)}return filePaths}function writeForms(cwd,forms3,written){let filePaths=[];for(let form of forms3){let definition=buildFormDefinition(form),relativePath=path41.join(FORMS_DIR,`${definition.name}.json`);writeFile2(cwd,relativePath,JSON.stringify(definition,null,2)+`
691
691
  `,written),filePaths.push(relativePath)}return filePaths}function writeCollectionSeeds(cwd,manifest,written){let entriesDir=path41.join(GENERATED_ROOT,"entries");ensureDir(path41.join(cwd,entriesDir));for(let collection of manifest.collections){let entries2=manifest.pages.filter(page=>collection.sourceRoutes.includes(page.route)).map(page=>({data:buildEntrySeed(cwd,page,collection)}));writeFile2(cwd,path41.join(entriesDir,`${collection.suggestedSchema}.json`),JSON.stringify(entries2,null,2)+`
@@ -1178,7 +1178,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1178
1178
  ${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(`
1179
1179
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path49=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path49,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,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(api,ctx.projectId,ctx.env,cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),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 server=serverResult.value,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)}
1180
1180
 
1181
- ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_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 fs46 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z64}from"zod";var CapabilityTokenSchema=z64.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z64.array(CapabilityTokenSchema);import{z as z65}from"zod";var CronTriggerSchema=z65.object({type:z65.literal("schedule"),cron:z65.string().min(1,"cron expression required"),tz:z65.string().optional()}),ManualTriggerSchema2=z65.object({type:z65.literal("manual")}),WebhookTriggerSchema2=z65.object({type:z65.literal("webhook"),path:z65.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z65.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z65.object({name:z65.string().min(1),capability_grant:z65.enum(["inherit","explicit"]).optional(),explicit_grants:z65.array(z65.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=z65.object({"sub-agents":z65.array(SubAgentRefSchema)}),RuntimeConfigSchema=z65.object({cloud:z65.boolean().optional(),dev:z65.boolean().optional(),long_running:z65.boolean().optional()}),DataSourceSchema=z65.enum(["main","prod"]),ConfigValueKeySchema=z65.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=z65.preprocess(value=>typeof value=="string"?{key:value}:value,z65.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z65.boolean().default(!0),delivery:z65.literal("process_env").default("process_env")})),IntegrationKeySchema=z65.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z65.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=z65.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z65.object({enabled:z65.boolean().default(!0),tools:z65.record(IntegrationToolKeySchema,z65.boolean()).optional()})),IntegrationPolicySchema=z65.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z65.object({version:z65.literal(1),description:z65.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z65.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z65.array(DataSourceSchema).optional(),secrets:z65.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"]});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 path4.relative(dir,path4.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=path4.basename(bundlePath),goalPath=path4.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=path4.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(path4.join(bundlePath,"SOUL.md")),capsPath=path4.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=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.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=createHash2("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=path4.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=path4.join(agentsDir,entry.name);if(await fileExists(path4.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 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 production 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;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 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 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])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,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 z66}from"zod";var SurfaceGuardPolicySchema=z66.enum(["block","warn","allow"]),ClassificationSchema=z66.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z66.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z66.object({enabled:z66.boolean(),allowed_skills:z66.array(z66.string().min(1)).default([]),allowed_classifications:z66.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z66.enum(["off","daily","weekly"]),NotificationFormatSchema=z66.object({markdown:z66.boolean().default(!0),html:z66.boolean().default(!1)}),NotificationsPolicySchema=z66.object({email_recipients:z66.array(z66.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z66.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z66.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 z67}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=z67.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z67.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.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 union2=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)&&union2.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(union2).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
1181
+ ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_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 fs46 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z65}from"zod";var CapabilityTokenSchema=z65.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z65.array(CapabilityTokenSchema);import{z as z66}from"zod";var CronTriggerSchema=z66.object({type:z66.literal("schedule"),cron:z66.string().min(1,"cron expression required"),tz:z66.string().optional()}),ManualTriggerSchema2=z66.object({type:z66.literal("manual")}),WebhookTriggerSchema2=z66.object({type:z66.literal("webhook"),path:z66.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z66.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z66.object({name:z66.string().min(1),capability_grant:z66.enum(["inherit","explicit"]).optional(),explicit_grants:z66.array(z66.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=z66.object({"sub-agents":z66.array(SubAgentRefSchema)}),RuntimeConfigSchema=z66.object({cloud:z66.boolean().optional(),dev:z66.boolean().optional(),long_running:z66.boolean().optional()}),DataSourceSchema=z66.enum(["main","prod"]),ConfigValueKeySchema=z66.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=z66.preprocess(value=>typeof value=="string"?{key:value}:value,z66.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z66.boolean().default(!0),delivery:z66.literal("process_env").default("process_env")})),IntegrationKeySchema=z66.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z66.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=z66.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z66.object({enabled:z66.boolean().default(!0),tools:z66.record(IntegrationToolKeySchema,z66.boolean()).optional()})),IntegrationPolicySchema=z66.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z66.object({version:z66.literal(1),description:z66.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z66.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z66.array(DataSourceSchema).optional(),secrets:z66.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"]});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 path4.relative(dir,path4.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=path4.basename(bundlePath),goalPath=path4.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=path4.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(path4.join(bundlePath,"SOUL.md")),capsPath=path4.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=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.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=createHash2("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=path4.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=path4.join(agentsDir,entry.name);if(await fileExists(path4.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 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 production 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;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 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 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])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,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 z67}from"zod";var SurfaceGuardPolicySchema=z67.enum(["block","warn","allow"]),ClassificationSchema=z67.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z67.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z67.object({enabled:z67.boolean(),allowed_skills:z67.array(z67.string().min(1)).default([]),allowed_classifications:z67.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z67.enum(["off","daily","weekly"]),NotificationFormatSchema=z67.object({markdown:z67.boolean().default(!0),html:z67.boolean().default(!1)}),NotificationsPolicySchema=z67.object({email_recipients:z67.array(z67.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z67.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z67.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 z68}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=z68.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z68.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.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 union2=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)&&union2.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(union2).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
1182
1182
  ${line}`):next2=(content2.endsWith(`
1183
1183
  `)?content2:content2+`
1184
1184
  `)+line+`
@@ -1240,9 +1240,9 @@ This breaks source tracking for inline editing. Translation keys must be statica
1240
1240
  `)}`),console.error(`
1241
1241
  `+"\u2500".repeat(80));console.error(`
1242
1242
  \u274C Found ${errors.length} error(s) in ${reactFiles.length} files.
1243
- `),process.exit(1)}}import fs22 from"node:fs";import path25 from"node:path";var SCAN_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs"],SCAN_EXTENSIONS_SET=new Set(SCAN_EXTENSIONS),SKIP_DIRS=new Set(["node_modules","dist",".next",".fimo",".git","public"]),GLOBAL_PATTERNS=[/\.css$/,/\.scss$/,/tailwind\.config/,/postcss\.config/,/vite\.config/,/tsconfig/,/package\.json$/,/src\/main\.[tj]sx?$/,/src\/index\.[tj]sx?$/,/src\/root\.[tj]sx?$/,/react-router\.config/];function isGlobalFile(filePath){return GLOBAL_PATTERNS.some(p2=>p2.test(filePath))}__name(isGlobalFile,"isGlobalFile");function collectFiles(dir){let files=[];if(!fs22.existsSync(dir))return files;let entries2=fs22.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path25.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path25.extname(entry.name))&&files.push(fullPath)}return files}__name(collectFiles,"collectFiles");function extractImports(content2){let imports=[],staticRegex=/(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;for(let match of content2.matchAll(staticRegex))imports.push(match[1]);let dynamicRegex=/import\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(dynamicRegex))imports.push(match[1]);let requireRegex=/require\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(requireRegex))imports.push(match[1]);return imports.filter(s=>s.startsWith(".")||s.startsWith("@/"))}__name(extractImports,"extractImports");function resolveImport(specifier,fromDir,srcDir){let targetPath;if(specifier.startsWith("@/"))targetPath=path25.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path25.resolve(fromDir,specifier);else return null;if(fs22.existsSync(targetPath)&&fs22.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs22.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path25.join(targetPath,"index"+ext);if(fs22.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root2){let routesFilePath=path25.resolve(srcDir,"routes.ts");if(!fs22.existsSync(routesFilePath))return new Map;let source=fs22.readFileSync(routesFilePath,"utf-8"),parsed=parseRoutesSource(source),fileToRoutes=new Map;for(let r of parsed){if(r.isLayout||!r.path||!r.file)continue;let resolved=resolveImport(r.file,srcDir,srcDir);if(!resolved)continue;let rel=path25.relative(root2,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root2){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs22.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path25.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path25.relative(root2,resolved),importerRel=path25.relative(root2,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root2=options.cwd??process.cwd(),srcDir=path25.resolve(root2,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root2),fileToImporters=buildReverseImportGraph(srcDir,root2),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");init_sync_forms();init_sync_schemas();function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");function syncFormsCommand(options){let result=syncForms({cwd:resolveCwd(options)});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
1243
+ `),process.exit(1)}}import fs22 from"node:fs";import path25 from"node:path";var SCAN_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs"],SCAN_EXTENSIONS_SET=new Set(SCAN_EXTENSIONS),SKIP_DIRS=new Set(["node_modules","dist",".next",".fimo",".git","public"]),GLOBAL_PATTERNS=[/\.css$/,/\.scss$/,/tailwind\.config/,/postcss\.config/,/vite\.config/,/tsconfig/,/package\.json$/,/src\/main\.[tj]sx?$/,/src\/index\.[tj]sx?$/,/src\/root\.[tj]sx?$/,/react-router\.config/];function isGlobalFile(filePath){return GLOBAL_PATTERNS.some(p2=>p2.test(filePath))}__name(isGlobalFile,"isGlobalFile");function collectFiles(dir){let files=[];if(!fs22.existsSync(dir))return files;let entries2=fs22.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path25.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path25.extname(entry.name))&&files.push(fullPath)}return files}__name(collectFiles,"collectFiles");function extractImports(content2){let imports=[],staticRegex=/(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;for(let match of content2.matchAll(staticRegex))imports.push(match[1]);let dynamicRegex=/import\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(dynamicRegex))imports.push(match[1]);let requireRegex=/require\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(requireRegex))imports.push(match[1]);return imports.filter(s=>s.startsWith(".")||s.startsWith("@/"))}__name(extractImports,"extractImports");function resolveImport(specifier,fromDir,srcDir){let targetPath;if(specifier.startsWith("@/"))targetPath=path25.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path25.resolve(fromDir,specifier);else return null;if(fs22.existsSync(targetPath)&&fs22.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs22.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path25.join(targetPath,"index"+ext);if(fs22.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root2){let routesFilePath=path25.resolve(srcDir,"routes.ts");if(!fs22.existsSync(routesFilePath))return new Map;let source=fs22.readFileSync(routesFilePath,"utf-8"),parsed=parseRoutesSource(source),fileToRoutes=new Map;for(let r of parsed){if(r.isLayout||!r.path||!r.file)continue;let resolved=resolveImport(r.file,srcDir,srcDir);if(!resolved)continue;let rel=path25.relative(root2,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root2){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs22.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path25.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path25.relative(root2,resolved),importerRel=path25.relative(root2,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root2=options.cwd??process.cwd(),srcDir=path25.resolve(root2,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root2),fileToImporters=buildReverseImportGraph(srcDir,root2),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");init_sync_forms();init_sync_schemas();function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");async function syncFormsCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncForms({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
1244
1244
  ${result.errors.map(e=>` - ${e}`).join(`
1245
- `)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){let framework=await detectProjectFramework(opts.cwd);return framework&&framework.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,[schemasResult,formsResult,labelsResult]=await Promise.allSettled([detectProjectFramework(cwd).then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>syncForms({cwd,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path26.join(cwd,".env")),...await readEnvFile(path26.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
1245
+ `)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){let framework=await detectProjectFramework(opts.cwd);return framework&&framework.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,frameworkResult=detectProjectFramework(cwd),[schemasResult,formsResult,labelsResult]=await Promise.allSettled([frameworkResult.then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),frameworkResult.then(framework=>syncForms({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path26.join(cwd,".env")),...await readEnvFile(path26.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
1246
1246
  `),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),dashboardUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewEnabled=(await api.getProject(local.projectId)).previewEnabled!==!1,remoteSp=spinner("Checking the Fimo branch"),remote;try{remote=await api.getGitRemote(local.projectId,ctx.env),await ensureFimoRemote(cwd,remote.url);let preparation=await prepareDeployCheckout({cwd,remoteBranch:remote.branch});remoteSp.succeed(preparation==="missing-remote"?`Fimo branch ${remote.branch} will be created by this deploy`:`Checkout ready for fimo/${remote.branch}`)}catch(error){if(remoteSp.fail("Checkout is not ready to deploy"),error instanceof EnvironmentCheckoutError){ui.error({command:"deploy",code:error.code,message:error.message,hint:error.hint});return}rethrowCliAuthError(error),ui.error({command:"deploy",code:"ENV_GIT_PREFLIGHT_FAILED",message:`Could not compare this checkout with the Fimo branch: ${errorMessage(error)}`});return}let validateSp=spinner("Validating project"),report=await runValidate({cwd,envOverride:envOverride2});if(report.ok)validateSp.succeed("Validation passed");else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteBranch=remote.branch,pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep");try{await api.sandboxPull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.env,{noRestart:options.restart===!1}),finalizeStep("ok")}catch(error){rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}await syncDisplayNameIfRenamed({cwd,projectId:local.projectId,api});let previewUrl=null;if(previewEnabled)try{previewUrl=(await api.getPreviewUrl(local.projectId,ctx.env)).url}catch(error){isPretty2&&O2.warn(`Could not fetch preview URL: ${errorMessage(error)}`)}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewUrl,dashboard_url:dashboardUrl,published:!1},render:__name(context=>renderDeployResult({previewUrl,dashboardUrl,appUrl:null,previewEnabled,published:!1},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)");try{await api.publishProject(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail(),ui.error({command:"deploy",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage(error)}`});return}publishSp.succeed("Published");let appUrl=null;try{appUrl=(await api.getProject(local.projectId)).appUrl}catch(error){isPretty2&&O2.warn(`Could not fetch published URL: ${errorMessage(error)}`)}ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewUrl,dashboard_url:dashboardUrl,published:!0,app_url:appUrl},render:__name(context=>renderDeployResult({previewUrl,dashboardUrl,appUrl,previewEnabled,published:!0},context),"render")})}__name(deployCommand,"deployCommand");function renderDeployResult(result,context){let lines=[];return result.previewUrl&&lines.push(`Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),result.appUrl&&lines.push(`Live: ${terminalLink("Open site",result.appUrl,context.hyperlinks)}`),lines.push(`Fimo: ${terminalLink("Open in Fimo",result.dashboardUrl,context.hyperlinks)}`),result.published?lines.push(result.appUrl?"Your site is live.":"Publish completed. Check Fimo for the live URL."):lines.push(result.previewEnabled?"Deployed to preview. Run `fimo deploy --publish` or `fimo publish` to publish a new version.":"Changes synced. Preview is disabled for this project."),lines.join(`
1247
1247
  `)}__name(renderDeployResult,"renderDeployResult");function emitPushFailure(failure,env){switch(failure.kind){case"non-fast-forward":ui.error({command:"deploy",code:"PUSH_NON_FAST_FORWARD",message:`The remote \`fimo/${env}\` has commits your local branch does not.`,hint:`Fix it manually, then re-run \`fimo deploy\`:
1248
1248
  1. git pull --rebase fimo ${env}
@@ -1339,11 +1339,11 @@ Run \`fimo integrations <command> --help\` for command-specific help.
1339
1339
  `)}__name(renderLocaleStats,"renderLocaleStats");async function localesListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("i18n.list",{projectId:ctx.projectId,env:ctx.env});let stats=await api.getProjectLocaleStats(ctx.projectId);ui.result({command:"locales list",data:{env:ctx.env,...stats},render:__name(()=>renderLocaleStats(ctx.env,stats),"render")})}__name(localesListCommand,"localesListCommand");function confirmationDetails(spec,locale,env,plan){let movement=plan.state.relation==="behind"?`Fimo will first fast-forward '${plan.state.localBranch}' by ${plan.state.behind} commit${plan.state.behind===1?"":"s"}, then commit this change to fimo/${plan.state.remoteBranch} and synchronize it back.`:`Fimo will commit this change to fimo/${plan.state.remoteBranch}, then fast-forward '${plan.state.localBranch}' to that commit.`;return[`${spec.verb} locale '${locale}' in environment '${env}'.`,movement,...spec.destructive?[`This permanently deletes stored entries and labels for '${locale}' from this environment.`]:[]].join(`
1340
1340
  `)}__name(confirmationDetails,"confirmationDetails");function rejectMissingConfirmation(spec,options){return options.yes||currentMode().format!=="json"&&isInteractive()?!1:(ui.error({command:`locales ${spec.operation}`,code:"CONFIRMATION_REQUIRED",message:"Locale lifecycle changes require confirmation.",hint:"Review the operation, then pass --yes to apply it non-interactively."}),!0)}__name(rejectMissingConfirmation,"rejectMissingConfirmation");async function confirmMutation(spec,locale,env,plan,options){if(options.yes)return!0;wt(confirmationDetails(spec,locale,env,plan),"What will happen");let confirmed=await ot2({message:"Continue?",initialValue:!1});return q(confirmed)||!confirmed?(ui.info({command:`locales ${spec.operation}`,message:"Cancelled."}),!1):!0}__name(confirmMutation,"confirmMutation");function emitPreflightError(command,error){return error instanceof EnvironmentCheckoutError?(ui.error({command,code:error.code,message:error.message,hint:error.hint}),!0):!1}__name(emitPreflightError,"emitPreflightError");function emitApiError(command,error){return rethrowCliAuthError(error),error instanceof ApiRequestError?(ui.error({command,code:error.code?.toUpperCase()??"LOCALE_MUTATION_FAILED",message:error.detail}),!0):!1}__name(emitApiError,"emitApiError");function renderMutationResult(spec,response,env,sync){if(sync.status==="required")return[`Locale '${response.locale}' was changed in '${env}', but this checkout could not be synchronized.`,"The remote change succeeded. Do not retry the locale command.","",sync.reason,"","Recover the checkout:",...sync.recovery.map(command=>` ${command}`)].join(`
1341
1341
  `);let removal="entriesDeleted"in response?` Deleted ${response.entriesDeleted} entr${response.entriesDeleted===1?"y":"ies"} and ${response.labelsDeleted} label${response.labelsDeleted===1?"":"s"}.`:"";return`${spec.verb} locale '${response.locale}' in '${env}'.${removal}
1342
- Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_esm();import{z as z71}from"zod";var projectScopeShape={projectId:z71.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z71.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z71.string().min(1).optional().describe("The locale to read or write."),entryDataField=z71.record(z71.string(),z71.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z71.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z71.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z71.uuid().describe("The Fimo media asset ID."),formIdField=z71.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z71.record(z71.string().min(1),z71.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z71.string().min(1).max(255).describe("Stable form name."),label:z71.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z71.object({...envScopeShape,task:z71.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z71.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z71.record(z71.string(),z71.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z71.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z71.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z71.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z71.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&&params.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z71.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z71.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z71.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z71.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z71.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z71.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,id:z71.uuid().describe("The entry ID."),locale:localeField,populate:z71.array(z71.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z71.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z71.object({...envScopeShape,search:z71.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z71.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z71.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z71.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,id:z71.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,id:z71.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,entries:z71.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,selection:z71.union([z71.object({ids:z71.array(z71.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z71.object({where:EntryWhereSchema}),z71.object({updates:z71.array(z71.object({id:z71.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,selection:z71.union([z71.object({ids:z71.array(z71.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z71.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z71.array(z71.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z71.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z71.object({...envScopeShape,locale:z71.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z71.object({...envScopeShape,locale:z71.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z71.object({...envScopeShape,key:labelKeyField,value:z71.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z71.object({...envScopeShape,records:z71.array(z71.object({key:labelKeyField,value:z71.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z71.object({...envScopeShape,locale:z71.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z71.object({...envScopeShape,parentId:z71.uuid().optional().describe("Limit results to one media-library folder."),search:z71.string().max(200).optional(),type:z71.enum(["file","folder"]).optional(),mimePrefix:z71.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z71.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z71.enum(["asc","desc"]).optional(),includePath:z71.boolean().optional(),excludeHidden:z71.boolean().optional(),limit:z71.number().int().min(1).max(100).optional(),offset:z71.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z71.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z71.object({...envScopeShape,name:z71.string().min(1).max(255).describe("Folder name."),parentId:z71.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z71.object({...envScopeShape,id:assetIdField,parentId:z71.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z71.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z71.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z71.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z71.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z71.object({...envScopeShape,id:formIdField,...z71.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z71.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z71.object({...envScopeShape,id:formIdField,limit:z71.number().int().min(1).max(100).optional(),offset:z71.number().int().min(0).optional(),searchQuery:z71.string().max(200).optional(),sortDirection:z71.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z71.object({...envScopeShape,id:formIdField,submissionId:z71.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z71.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z71.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z71.object({...envScopeShape,pattern:z71.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z71.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z71.object({...envScopeShape,pattern:z71.string().min(1).max(200).describe("Regular expression to search for."),include:z71.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z71.boolean().optional().describe("Case-insensitive matching."),maxMatches:z71.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z71.object({...envScopeShape,path:filePathField,content:z71.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z71.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z71.object({...envScopeShape,path:filePathField,oldString:z71.string().min(1).describe("Exact text to replace."),newString:z71.string().describe("Replacement text."),replaceAll:z71.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z71.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z71.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z71.object({...envScopeShape,agentName:z71.string().min(1).max(120).describe("The agent bundle name."),args:z71.record(z71.string(),z71.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z71.object({...projectScopeShape,sessionId:z71.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z72 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z72.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z72.union([z72.string(),z72.number().int()]),CursorSchema=z72.string(),TaskCreationParamsSchema=z72.looseObject({ttl:z72.union([z72.number(),z72.null()]).optional(),pollInterval:z72.number().optional()}),TaskMetadataSchema=z72.object({ttl:z72.number().optional()}),RelatedTaskMetadataSchema=z72.object({taskId:z72.string()}),RequestMetaSchema=z72.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z72.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z72.object({method:z72.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z72.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z72.object({method:z72.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z72.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z72.union([z72.string(),z72.number().int()]),JSONRPCRequestSchema=z72.object({jsonrpc:z72.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z72.object({jsonrpc:z72.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z72.object({jsonrpc:z72.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z72.object({jsonrpc:z72.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z72.object({code:z72.number().int(),message:z72.string(),data:z72.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z72.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z72.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z72.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z72.object({src:z72.string(),mimeType:z72.string().optional(),sizes:z72.array(z72.string()).optional(),theme:z72.enum(["light","dark"]).optional()}),IconsSchema=z72.object({icons:z72.array(IconSchema).optional()}),BaseMetadataSchema=z72.object({name:z72.string(),title:z72.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z72.string(),websiteUrl:z72.string().optional(),description:z72.string().optional()}),FormElicitationCapabilitySchema=z72.intersection(z72.object({applyDefaults:z72.boolean().optional()}),z72.record(z72.string(),z72.unknown())),ElicitationCapabilitySchema=z72.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z72.intersection(z72.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z72.record(z72.string(),z72.unknown()).optional())),ClientTasksCapabilitySchema=z72.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z72.looseObject({sampling:z72.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z72.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z72.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z72.looseObject({tools:z72.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z72.object({experimental:z72.record(z72.string(),AssertObjectSchema).optional(),sampling:z72.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z72.object({listChanged:z72.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z72.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z72.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z72.object({experimental:z72.record(z72.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z72.object({listChanged:z72.boolean().optional()}).optional(),resources:z72.object({subscribe:z72.boolean().optional(),listChanged:z72.boolean().optional()}).optional(),tools:z72.object({listChanged:z72.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z72.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z72.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z72.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z72.object({progress:z72.number(),total:z72.optional(z72.number()),message:z72.optional(z72.string())}),ProgressNotificationParamsSchema=z72.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z72.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z72.object({taskId:z72.string(),status:TaskStatusSchema,ttl:z72.union([z72.number(),z72.null()]),createdAt:z72.string(),lastUpdatedAt:z72.string(),pollInterval:z72.optional(z72.number()),statusMessage:z72.optional(z72.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z72.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z72.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z72.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z72.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z72.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z72.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z72.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z72.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z72.object({uri:z72.string(),mimeType:z72.optional(z72.string()),_meta:z72.record(z72.string(),z72.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z72.string()}),Base64Schema=z72.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z72.enum(["user","assistant"]),AnnotationsSchema=z72.object({audience:z72.array(RoleSchema).optional(),priority:z72.number().min(0).max(1).optional(),lastModified:z72.iso.datetime({offset:!0}).optional()}),ResourceSchema=z72.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z72.string(),description:z72.optional(z72.string()),mimeType:z72.optional(z72.string()),annotations:AnnotationsSchema.optional(),_meta:z72.optional(z72.looseObject({}))}),ResourceTemplateSchema=z72.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z72.string(),description:z72.optional(z72.string()),mimeType:z72.optional(z72.string()),annotations:AnnotationsSchema.optional(),_meta:z72.optional(z72.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z72.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z72.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z72.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z72.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z72.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z72.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z72.array(z72.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z72.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z72.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z72.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z72.object({name:z72.string(),description:z72.optional(z72.string()),required:z72.optional(z72.boolean())}),PromptSchema=z72.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z72.optional(z72.string()),arguments:z72.optional(z72.array(PromptArgumentSchema)),_meta:z72.optional(z72.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z72.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z72.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z72.string(),arguments:z72.record(z72.string(),z72.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z72.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z72.object({type:z72.literal("text"),text:z72.string(),annotations:AnnotationsSchema.optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),ImageContentSchema=z72.object({type:z72.literal("image"),data:Base64Schema,mimeType:z72.string(),annotations:AnnotationsSchema.optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),AudioContentSchema=z72.object({type:z72.literal("audio"),data:Base64Schema,mimeType:z72.string(),annotations:AnnotationsSchema.optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),ToolUseContentSchema=z72.object({type:z72.literal("tool_use"),name:z72.string(),id:z72.string(),input:z72.record(z72.string(),z72.unknown()),_meta:z72.record(z72.string(),z72.unknown()).optional()}),EmbeddedResourceSchema=z72.object({type:z72.literal("resource"),resource:z72.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z72.literal("resource_link")}),ContentBlockSchema=z72.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z72.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z72.string().optional(),messages:z72.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z72.object({title:z72.string().optional(),readOnlyHint:z72.boolean().optional(),destructiveHint:z72.boolean().optional(),idempotentHint:z72.boolean().optional(),openWorldHint:z72.boolean().optional()}),ToolExecutionSchema=z72.object({taskSupport:z72.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z72.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z72.string().optional(),inputSchema:z72.object({type:z72.literal("object"),properties:z72.record(z72.string(),AssertObjectSchema).optional(),required:z72.array(z72.string()).optional()}).catchall(z72.unknown()),outputSchema:z72.object({type:z72.literal("object"),properties:z72.record(z72.string(),AssertObjectSchema).optional(),required:z72.array(z72.string()).optional()}).catchall(z72.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z72.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z72.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z72.array(ContentBlockSchema).default([]),structuredContent:z72.record(z72.string(),z72.unknown()).optional(),isError:z72.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z72.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z72.string(),arguments:z72.record(z72.string(),z72.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z72.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z72.object({autoRefresh:z72.boolean().default(!0),debounceMs:z72.number().int().nonnegative().default(300)}),LoggingLevelSchema=z72.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z72.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z72.string().optional(),data:z72.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z72.object({name:z72.string().optional()}),ModelPreferencesSchema=z72.object({hints:z72.array(ModelHintSchema).optional(),costPriority:z72.number().min(0).max(1).optional(),speedPriority:z72.number().min(0).max(1).optional(),intelligencePriority:z72.number().min(0).max(1).optional()}),ToolChoiceSchema=z72.object({mode:z72.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z72.object({type:z72.literal("tool_result"),toolUseId:z72.string().describe("The unique identifier for the corresponding tool call."),content:z72.array(ContentBlockSchema).default([]),structuredContent:z72.object({}).loose().optional(),isError:z72.boolean().optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),SamplingContentSchema=z72.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z72.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z72.object({role:RoleSchema,content:z72.union([SamplingMessageContentBlockSchema,z72.array(SamplingMessageContentBlockSchema)]),_meta:z72.record(z72.string(),z72.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z72.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z72.string().optional(),includeContext:z72.enum(["none","thisServer","allServers"]).optional(),temperature:z72.number().optional(),maxTokens:z72.number().int(),stopSequences:z72.array(z72.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z72.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z72.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z72.string(),stopReason:z72.optional(z72.enum(["endTurn","stopSequence","maxTokens"]).or(z72.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z72.string(),stopReason:z72.optional(z72.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z72.string())),role:RoleSchema,content:z72.union([SamplingMessageContentBlockSchema,z72.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z72.object({type:z72.literal("boolean"),title:z72.string().optional(),description:z72.string().optional(),default:z72.boolean().optional()}),StringSchemaSchema=z72.object({type:z72.literal("string"),title:z72.string().optional(),description:z72.string().optional(),minLength:z72.number().optional(),maxLength:z72.number().optional(),format:z72.enum(["email","uri","date","date-time"]).optional(),default:z72.string().optional()}),NumberSchemaSchema=z72.object({type:z72.enum(["number","integer"]),title:z72.string().optional(),description:z72.string().optional(),minimum:z72.number().optional(),maximum:z72.number().optional(),default:z72.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z72.object({type:z72.literal("string"),title:z72.string().optional(),description:z72.string().optional(),enum:z72.array(z72.string()),default:z72.string().optional()}),TitledSingleSelectEnumSchemaSchema=z72.object({type:z72.literal("string"),title:z72.string().optional(),description:z72.string().optional(),oneOf:z72.array(z72.object({const:z72.string(),title:z72.string()})),default:z72.string().optional()}),LegacyTitledEnumSchemaSchema=z72.object({type:z72.literal("string"),title:z72.string().optional(),description:z72.string().optional(),enum:z72.array(z72.string()),enumNames:z72.array(z72.string()).optional(),default:z72.string().optional()}),SingleSelectEnumSchemaSchema=z72.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z72.object({type:z72.literal("array"),title:z72.string().optional(),description:z72.string().optional(),minItems:z72.number().optional(),maxItems:z72.number().optional(),items:z72.object({type:z72.literal("string"),enum:z72.array(z72.string())}),default:z72.array(z72.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z72.object({type:z72.literal("array"),title:z72.string().optional(),description:z72.string().optional(),minItems:z72.number().optional(),maxItems:z72.number().optional(),items:z72.object({anyOf:z72.array(z72.object({const:z72.string(),title:z72.string()}))}),default:z72.array(z72.string()).optional()}),MultiSelectEnumSchemaSchema=z72.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z72.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z72.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z72.literal("form").optional(),message:z72.string(),requestedSchema:z72.object({type:z72.literal("object"),properties:z72.record(z72.string(),PrimitiveSchemaDefinitionSchema),required:z72.array(z72.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z72.literal("url"),message:z72.string(),elicitationId:z72.string(),url:z72.string().url()}),ElicitRequestParamsSchema=z72.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z72.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z72.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z72.enum(["accept","decline","cancel"]),content:z72.preprocess(val2=>val2===null?void 0:val2,z72.record(z72.string(),z72.union([z72.string(),z72.number(),z72.boolean(),z72.array(z72.string())])).optional())}),ResourceTemplateReferenceSchema=z72.object({type:z72.literal("ref/resource"),uri:z72.string()});var PromptReferenceSchema=z72.object({type:z72.literal("ref/prompt"),name:z72.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z72.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z72.object({name:z72.string(),value:z72.string()}),context:z72.object({arguments:z72.record(z72.string(),z72.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z72.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z72.looseObject({values:z72.array(z72.string()).max(100),total:z72.optional(z72.number().int()),hasMore:z72.optional(z72.boolean())})}),RootSchema=z72.object({uri:z72.string().startsWith("file://"),name:z72.string().optional(),_meta:z72.record(z72.string(),z72.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z72.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z72.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z72.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z72.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z72.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z72.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z72.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z72.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z72.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage3,refs){refs?.errorMessages&&errorMessage3&&(res.errorMessage={...res.errorMessage,[key]:errorMessage3})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage3,refs){res[key]=value,addErrorMessage(res,key,errorMessage3,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
1342
+ Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_esm();import{z as z72}from"zod";var projectScopeShape={projectId:z72.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z72.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z72.string().min(1).optional().describe("The locale to read or write."),entryDataField=z72.record(z72.string(),z72.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z72.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z72.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z72.uuid().describe("The Fimo media asset ID."),formIdField=z72.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z72.record(z72.string().min(1),z72.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z72.string().min(1).max(255).describe("Stable form name."),label:z72.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z72.object({...envScopeShape,task:z72.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z72.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z72.record(z72.string(),z72.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z72.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z72.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z72.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z72.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&&params.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z72.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z72.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z72.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z72.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z72.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),locale:localeField,populate:z72.array(z72.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z72.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z72.object({...envScopeShape,search:z72.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z72.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z72.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z72.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,entries:z72.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,selection:z72.union([z72.object({ids:z72.array(z72.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z72.object({where:EntryWhereSchema}),z72.object({updates:z72.array(z72.object({id:z72.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,selection:z72.union([z72.object({ids:z72.array(z72.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z72.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z72.array(z72.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z72.object({...envScopeShape,key:labelKeyField,value:z72.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z72.object({...envScopeShape,records:z72.array(z72.object({key:labelKeyField,value:z72.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z72.object({...envScopeShape,parentId:z72.uuid().optional().describe("Limit results to one media-library folder."),search:z72.string().max(200).optional(),type:z72.enum(["file","folder"]).optional(),mimePrefix:z72.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z72.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z72.enum(["asc","desc"]).optional(),includePath:z72.boolean().optional(),excludeHidden:z72.boolean().optional(),limit:z72.number().int().min(1).max(100).optional(),offset:z72.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z72.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z72.object({...envScopeShape,name:z72.string().min(1).max(255).describe("Folder name."),parentId:z72.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z72.object({...envScopeShape,id:assetIdField,parentId:z72.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z72.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z72.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z72.object({...envScopeShape,id:formIdField,...z72.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z72.object({...envScopeShape,id:formIdField,limit:z72.number().int().min(1).max(100).optional(),offset:z72.number().int().min(0).optional(),searchQuery:z72.string().max(200).optional(),sortDirection:z72.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField,submissionId:z72.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,pattern:z72.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z72.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,pattern:z72.string().min(1).max(200).describe("Regular expression to search for."),include:z72.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z72.boolean().optional().describe("Case-insensitive matching."),maxMatches:z72.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField,content:z72.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z72.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField,oldString:z72.string().min(1).describe("Exact text to replace."),newString:z72.string().describe("Replacement text."),replaceAll:z72.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z72.object({...envScopeShape,agentName:z72.string().min(1).max(120).describe("The agent bundle name."),args:z72.record(z72.string(),z72.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z72.object({...projectScopeShape,sessionId:z72.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z73 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z73.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z73.union([z73.string(),z73.number().int()]),CursorSchema=z73.string(),TaskCreationParamsSchema=z73.looseObject({ttl:z73.union([z73.number(),z73.null()]).optional(),pollInterval:z73.number().optional()}),TaskMetadataSchema=z73.object({ttl:z73.number().optional()}),RelatedTaskMetadataSchema=z73.object({taskId:z73.string()}),RequestMetaSchema=z73.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z73.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z73.object({method:z73.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z73.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z73.object({method:z73.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z73.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z73.union([z73.string(),z73.number().int()]),JSONRPCRequestSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z73.object({code:z73.number().int(),message:z73.string(),data:z73.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z73.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z73.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z73.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z73.object({src:z73.string(),mimeType:z73.string().optional(),sizes:z73.array(z73.string()).optional(),theme:z73.enum(["light","dark"]).optional()}),IconsSchema=z73.object({icons:z73.array(IconSchema).optional()}),BaseMetadataSchema=z73.object({name:z73.string(),title:z73.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z73.string(),websiteUrl:z73.string().optional(),description:z73.string().optional()}),FormElicitationCapabilitySchema=z73.intersection(z73.object({applyDefaults:z73.boolean().optional()}),z73.record(z73.string(),z73.unknown())),ElicitationCapabilitySchema=z73.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z73.intersection(z73.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z73.record(z73.string(),z73.unknown()).optional())),ClientTasksCapabilitySchema=z73.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z73.looseObject({sampling:z73.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z73.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z73.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z73.looseObject({tools:z73.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z73.object({experimental:z73.record(z73.string(),AssertObjectSchema).optional(),sampling:z73.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z73.object({listChanged:z73.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z73.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z73.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z73.object({experimental:z73.record(z73.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z73.object({listChanged:z73.boolean().optional()}).optional(),resources:z73.object({subscribe:z73.boolean().optional(),listChanged:z73.boolean().optional()}).optional(),tools:z73.object({listChanged:z73.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z73.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z73.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z73.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z73.object({progress:z73.number(),total:z73.optional(z73.number()),message:z73.optional(z73.string())}),ProgressNotificationParamsSchema=z73.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z73.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z73.object({taskId:z73.string(),status:TaskStatusSchema,ttl:z73.union([z73.number(),z73.null()]),createdAt:z73.string(),lastUpdatedAt:z73.string(),pollInterval:z73.optional(z73.number()),statusMessage:z73.optional(z73.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z73.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z73.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z73.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z73.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z73.object({uri:z73.string(),mimeType:z73.optional(z73.string()),_meta:z73.record(z73.string(),z73.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z73.string()}),Base64Schema=z73.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z73.enum(["user","assistant"]),AnnotationsSchema=z73.object({audience:z73.array(RoleSchema).optional(),priority:z73.number().min(0).max(1).optional(),lastModified:z73.iso.datetime({offset:!0}).optional()}),ResourceSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z73.string(),description:z73.optional(z73.string()),mimeType:z73.optional(z73.string()),annotations:AnnotationsSchema.optional(),_meta:z73.optional(z73.looseObject({}))}),ResourceTemplateSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z73.string(),description:z73.optional(z73.string()),mimeType:z73.optional(z73.string()),annotations:AnnotationsSchema.optional(),_meta:z73.optional(z73.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z73.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z73.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z73.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z73.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z73.array(z73.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z73.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z73.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z73.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z73.object({name:z73.string(),description:z73.optional(z73.string()),required:z73.optional(z73.boolean())}),PromptSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z73.optional(z73.string()),arguments:z73.optional(z73.array(PromptArgumentSchema)),_meta:z73.optional(z73.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z73.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z73.string(),arguments:z73.record(z73.string(),z73.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z73.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z73.object({type:z73.literal("text"),text:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ImageContentSchema=z73.object({type:z73.literal("image"),data:Base64Schema,mimeType:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),AudioContentSchema=z73.object({type:z73.literal("audio"),data:Base64Schema,mimeType:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ToolUseContentSchema=z73.object({type:z73.literal("tool_use"),name:z73.string(),id:z73.string(),input:z73.record(z73.string(),z73.unknown()),_meta:z73.record(z73.string(),z73.unknown()).optional()}),EmbeddedResourceSchema=z73.object({type:z73.literal("resource"),resource:z73.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z73.literal("resource_link")}),ContentBlockSchema=z73.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z73.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z73.string().optional(),messages:z73.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z73.object({title:z73.string().optional(),readOnlyHint:z73.boolean().optional(),destructiveHint:z73.boolean().optional(),idempotentHint:z73.boolean().optional(),openWorldHint:z73.boolean().optional()}),ToolExecutionSchema=z73.object({taskSupport:z73.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z73.string().optional(),inputSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),AssertObjectSchema).optional(),required:z73.array(z73.string()).optional()}).catchall(z73.unknown()),outputSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),AssertObjectSchema).optional(),required:z73.array(z73.string()).optional()}).catchall(z73.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z73.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z73.array(ContentBlockSchema).default([]),structuredContent:z73.record(z73.string(),z73.unknown()).optional(),isError:z73.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z73.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z73.string(),arguments:z73.record(z73.string(),z73.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z73.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z73.object({autoRefresh:z73.boolean().default(!0),debounceMs:z73.number().int().nonnegative().default(300)}),LoggingLevelSchema=z73.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z73.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z73.string().optional(),data:z73.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z73.object({name:z73.string().optional()}),ModelPreferencesSchema=z73.object({hints:z73.array(ModelHintSchema).optional(),costPriority:z73.number().min(0).max(1).optional(),speedPriority:z73.number().min(0).max(1).optional(),intelligencePriority:z73.number().min(0).max(1).optional()}),ToolChoiceSchema=z73.object({mode:z73.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z73.object({type:z73.literal("tool_result"),toolUseId:z73.string().describe("The unique identifier for the corresponding tool call."),content:z73.array(ContentBlockSchema).default([]),structuredContent:z73.object({}).loose().optional(),isError:z73.boolean().optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),SamplingContentSchema=z73.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z73.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z73.object({role:RoleSchema,content:z73.union([SamplingMessageContentBlockSchema,z73.array(SamplingMessageContentBlockSchema)]),_meta:z73.record(z73.string(),z73.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z73.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z73.string().optional(),includeContext:z73.enum(["none","thisServer","allServers"]).optional(),temperature:z73.number().optional(),maxTokens:z73.number().int(),stopSequences:z73.array(z73.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z73.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z73.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z73.string(),stopReason:z73.optional(z73.enum(["endTurn","stopSequence","maxTokens"]).or(z73.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z73.string(),stopReason:z73.optional(z73.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z73.string())),role:RoleSchema,content:z73.union([SamplingMessageContentBlockSchema,z73.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z73.object({type:z73.literal("boolean"),title:z73.string().optional(),description:z73.string().optional(),default:z73.boolean().optional()}),StringSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),minLength:z73.number().optional(),maxLength:z73.number().optional(),format:z73.enum(["email","uri","date","date-time"]).optional(),default:z73.string().optional()}),NumberSchemaSchema=z73.object({type:z73.enum(["number","integer"]),title:z73.string().optional(),description:z73.string().optional(),minimum:z73.number().optional(),maximum:z73.number().optional(),default:z73.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),enum:z73.array(z73.string()),default:z73.string().optional()}),TitledSingleSelectEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),oneOf:z73.array(z73.object({const:z73.string(),title:z73.string()})),default:z73.string().optional()}),LegacyTitledEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),enum:z73.array(z73.string()),enumNames:z73.array(z73.string()).optional(),default:z73.string().optional()}),SingleSelectEnumSchemaSchema=z73.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z73.object({type:z73.literal("array"),title:z73.string().optional(),description:z73.string().optional(),minItems:z73.number().optional(),maxItems:z73.number().optional(),items:z73.object({type:z73.literal("string"),enum:z73.array(z73.string())}),default:z73.array(z73.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z73.object({type:z73.literal("array"),title:z73.string().optional(),description:z73.string().optional(),minItems:z73.number().optional(),maxItems:z73.number().optional(),items:z73.object({anyOf:z73.array(z73.object({const:z73.string(),title:z73.string()}))}),default:z73.array(z73.string()).optional()}),MultiSelectEnumSchemaSchema=z73.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z73.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z73.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z73.literal("form").optional(),message:z73.string(),requestedSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),PrimitiveSchemaDefinitionSchema),required:z73.array(z73.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z73.literal("url"),message:z73.string(),elicitationId:z73.string(),url:z73.string().url()}),ElicitRequestParamsSchema=z73.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z73.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z73.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z73.enum(["accept","decline","cancel"]),content:z73.preprocess(val2=>val2===null?void 0:val2,z73.record(z73.string(),z73.union([z73.string(),z73.number(),z73.boolean(),z73.array(z73.string())])).optional())}),ResourceTemplateReferenceSchema=z73.object({type:z73.literal("ref/resource"),uri:z73.string()});var PromptReferenceSchema=z73.object({type:z73.literal("ref/prompt"),name:z73.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z73.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z73.object({name:z73.string(),value:z73.string()}),context:z73.object({arguments:z73.record(z73.string(),z73.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z73.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z73.looseObject({values:z73.array(z73.string()).max(100),total:z73.optional(z73.number().int()),hasMore:z73.optional(z73.boolean())})}),RootSchema=z73.object({uri:z73.string().startsWith("file://"),name:z73.string().optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z73.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z73.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z73.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z73.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z73.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z73.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z73.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z73.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage3,refs){refs?.errorMessages&&errorMessage3&&(res.errorMessage={...res.errorMessage,[key]:errorMessage3})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage3,refs){res[key]=value,addErrorMessage(res,key,errorMessage3,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
1343
1343
  ]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
1344
1344
  ]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
1345
1345
  `:`[${source[i]}\r
1346
- ]`;continue}pattern+=source[i],source[i]==="\\"?isEscaped2=!0:inCharGroup&&source[i]==="]"?inCharGroup=!1:!inCharGroup&&source[i]==="["&&(inCharGroup=!0)}try{new RegExp(pattern)}catch{return console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),regex.source}return pattern}__name(stringifyRegExpWithFlags,"stringifyRegExpWithFlags");function parseRecordDef(def,refs){if(refs.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties};let schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3")return schema;if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.checks?.length){let{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else{if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{...schema,propertyNames:{enum:def.keyType._def.values}};if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.type._def.checks?.length){let{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}}return schema}__name(parseRecordDef,"parseRecordDef");function parseMapDef(def,refs){if(refs.mapStrategy==="record")return parseRecordDef(def,refs);let keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs),values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}__name(parseMapDef,"parseMapDef");function parseNativeEnumDef(def){let object4=def.values,actualValues=Object.keys(def.values).filter(key=>typeof object4[object4[key]]!="number").map(key=>object4[key]),parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}__name(parseNativeEnumDef,"parseNativeEnumDef");function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}__name(parseNeverDef,"parseNeverDef");function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}__name(parseNullDef,"parseNullDef");var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);let options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x=>x._def.typeName in primitiveMappings&&(!x._def.checks||!x._def.checks.length))){let types=options.reduce((types2,x)=>{let type=primitiveMappings[x._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x=>x._def.typeName==="ZodLiteral"&&!x.description)){let types=options.reduce((acc,x)=>{let type=typeof x._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x._def.value===null)return[...acc,"null"];case"symbol":case"undefined":case"function":default:return acc}},[]);if(types.length===options.length){let uniqueTypes=types.filter((x,i,a)=>a.indexOf(x)===i);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x)=>acc.includes(x._def.value)?acc:[...acc,x._def.value],[])}}}else if(options.every(x=>x._def.typeName==="ZodEnum"))return{type:"string",enum:options.reduce((acc,x)=>[...acc,...x._def.values.filter(x2=>!acc.includes(x2))],[])};return asAnyOf(def,refs)}__name(parseUnionDef,"parseUnionDef");var asAnyOf=__name((def,refs)=>{let anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i}`]})).filter(x=>!!x&&(!refs.strictUnions||typeof x=="object"&&Object.keys(x).length>0));return anyOf.length?{anyOf}:void 0},"asAnyOf");function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length))return refs.target==="openApi3"?{type:primitiveMappings[def.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[def.innerType._def.typeName],"null"]};if(refs.target==="openApi3"){let base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});return base2&&"$ref"in base2?{allOf:[base2],nullable:!0}:base2&&{...base2,nullable:!0}}let base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}__name(parseNullableDef,"parseNullableDef");function parseNumberDef(def,refs){let res={type:"number"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"int":res.type="integer",addErrorMessage(res,"type",check.message,refs);break;case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseNumberDef,"parseNumberDef");function parseObjectDef(def,refs){let forceOptionalIntoNullable=refs.target==="openAi",result={type:"object",properties:{}},required=[],shape=def.shape();for(let propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0)continue;let propOptional=safeIsOptional(propDef);propOptional&&forceOptionalIntoNullable&&(propDef._def.typeName==="ZodOptional"&&(propDef=propDef._def.innerType),propDef.isNullable()||(propDef=propDef.nullable()),propOptional=!1);let parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});parsedDef!==void 0&&(result.properties[propName]=parsedDef,propOptional||required.push(propName))}required.length&&(result.required=required);let additionalProperties=decideAdditionalProperties(def,refs);return additionalProperties!==void 0&&(result.additionalProperties=additionalProperties),result}__name(parseObjectDef,"parseObjectDef");function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever")return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]});switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}__name(decideAdditionalProperties,"decideAdditionalProperties");function safeIsOptional(schema){try{return schema.isOptional()}catch{return!0}}__name(safeIsOptional,"safeIsOptional");var parseOptionalDef=__name((def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString())return parseDef(def.innerType._def,refs);let innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)},"parseOptionalDef");var parsePipelineDef=__name((def,refs)=>{if(refs.pipeStrategy==="input")return parseDef(def.in._def,refs);if(refs.pipeStrategy==="output")return parseDef(def.out._def,refs);let a=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),b=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a?"1":"0"]});return{allOf:[a,b].filter(x=>x!==void 0)}},"parsePipelineDef");function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}__name(parsePromiseDef,"parsePromiseDef");function parseSetDef(def,refs){let schema={type:"array",uniqueItems:!0,items:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]})};return def.minSize&&setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs),def.maxSize&&setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs),schema}__name(parseSetDef,"parseSetDef");function parseTupleDef(def,refs){return def.rest?{type:"array",minItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}:{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[])}}__name(parseTupleDef,"parseTupleDef");function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}__name(parseUndefinedDef,"parseUndefinedDef");function parseUnknownDef(refs){return parseAnyDef(refs)}__name(parseUnknownDef,"parseUnknownDef");var parseReadonlyDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseReadonlyDef");var selectParser=__name((def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind3.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind3.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind3.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind3.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind3.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind3.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind3.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind3.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind3.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind3.ZodUnion:case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind3.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind3.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind3.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind3.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind3.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind3.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind3.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind3.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind3.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind3.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind3.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind3.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind3.ZodNaN:case ZodFirstPartyTypeKind3.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind3.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind3.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind3.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind3.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind3.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind3.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind3.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind3.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind3.ZodFunction:case ZodFirstPartyTypeKind3.ZodVoid:case ZodFirstPartyTypeKind3.ZodSymbol:return;default:return(_=>{})(typeName)}},"selectParser");function parseDef(def,refs,forceResolution=!1){let seenItem=refs.seen.get(def);if(refs.override){let overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride)return overrideResult}if(seenItem&&!forceResolution){let seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0)return seenSchema}let newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);let jsonSchemaOrGetter=selectParser(def,def.typeName,refs),jsonSchema=typeof jsonSchemaOrGetter=="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema&&addMeta(def,refs,jsonSchema),refs.postProcess){let postProcessResult=refs.postProcess(jsonSchema,def,refs);return newItem.jsonSchema=jsonSchema,postProcessResult}return newItem.jsonSchema=jsonSchema,jsonSchema}__name(parseDef,"parseDef");var get$ref=__name((item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":return item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)?(console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`),parseAnyDef(refs)):refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}},"get$ref"),addMeta=__name((def,refs,jsonSchema)=>(def.description&&(jsonSchema.description=def.description,refs.markdownDescription&&(jsonSchema.markdownDescription=def.description)),jsonSchema),"addMeta");var zodToJsonSchema=__name((schema,options)=>{let refs=getRefs(options),definitions=typeof options=="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name2,schema2])=>({...acc,[name2]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},!0)??parseAnyDef(refs)}),{}):void 0,name=typeof options=="string"?options:options?.nameStrategy==="title"?void 0:options?.name,main=parseDef(schema._def,name===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name]},!1)??parseAnyDef(refs),title=typeof options=="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;title!==void 0&&(main.title=title),refs.flags.hasReferencedOpenAiAnyType&&(definitions||(definitions={}),definitions[refs.openAiAnyTypeName]||(definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}));let combined=name===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};return refs.target==="jsonSchema7"?combined.$schema="http://json-schema.org/draft-07/schema#":(refs.target==="jsonSchema2019-09"||refs.target==="openAi")&&(combined.$schema="https://json-schema.org/draft/2019-09/schema#"),refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),combined},"zodToJsonSchema");function mapMiniTarget(t2){return!t2||t2==="jsonSchema7"||t2==="draft-7"?"draft-7":t2==="jsonSchema2019-09"||t2==="draft-2020-12"?"draft-2020-12":"draft-7"}__name(mapMiniTarget,"mapMiniTarget");function toJsonSchemaCompat(schema,opts){return isZ4Schema(schema)?z4mini2.toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"}):zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??!0,pipeStrategy:opts?.pipeStrategy??"input"})}__name(toJsonSchemaCompat,"toJsonSchemaCompat");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}__name(getMethodLiteral,"getMethodLiteral");function parseWithCompat(schema,data2){let result=safeParse3(schema,data2);if(!result.success)throw result.error;return result.data}__name(parseWithCompat,"parseWithCompat");var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{static{__name(this,"Protocol")}constructor(_options){this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=__name(async()=>{let taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage3=message,error=new McpError(errorMessage3.error.code,errorMessage3.error.message,errorMessage3.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()},"handleTaskResult");return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error=>this._onerror(new Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error=>this._onerror(new Error(`Failed to enqueue error response: ${error}`))):capturedTransport?.send(errorResponse).catch(error=>this._onerror(new Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:__name(async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},"sendNotification"),sendRequest:__name(async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},"sendRequest"),authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error=>this._onerror(new Error(`Failed to send response: ${error}`))).finally(()=>{this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve10=>setTimeout(resolve10,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve10,reject)=>{let earlyReject=__name(error=>{reject(error)},"earlyReject");if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=__name(reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>this._onerror(new Error(`Failed to send cancellation: ${error2}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)},"cancel");this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);parseResult.success?resolve10(parseResult.data):reject(parseResult.error)}catch(error){reject(error)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=__name(()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout})),"timeoutHandler");this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=__name(response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))},"responseResolver");this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve10,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve10,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:__name(async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},"createTask"),getTask:__name(async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},"getTask"),storeTaskResult:__name(async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},"storeTaskResult"),getTaskResult:__name(taskId=>taskStore.getTaskResult(taskId,sessionId),"getTaskResult"),updateTaskStatus:__name(async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},"updateTaskStatus"),listTasks:__name(cursor=>taskStore.listTasks(cursor,sessionId),"listTasks")}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}__name(isPlainObject2,"isPlainObject");function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}__name(mergeCapabilities,"mergeCapabilities");var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist4(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}__name(createDefaultAjvInstance,"createDefaultAjvInstance");var AjvJsonSchemaValidator=class{static{__name(this,"AjvJsonSchemaValidator")}constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{static{__name(this,"ExperimentalServerTasks")}constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode2=params.mode??"form";switch(mode2){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode2==="form"&&params.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}__name(assertToolsCallTaskCapability,"assertToolsCallTaskCapability");function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}__name(assertClientRequestTaskCapability,"assertClientRequestTaskCapability");var Server=class extends Protocol{static{__name(this,"Server")}constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue;if(isZ4Schema(methodSchema)){let v4Schema=methodSchema;methodValue=v4Schema._zod?.def?.value??v4Schema.value}else{let v3Schema=methodSchema;methodValue=v3Schema._def?.value??v3Schema.value}if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=__name(async(request,extra)=>{let validatedRequest=safeParse3(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage3=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage3}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage3=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage3}`)}return taskValidationResult.data}let validationResult=safeParse3(CallToolResultSchema,result);if(!validationResult.success){let errorMessage3=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage3}`)}return validationResult.data},"wrappedHandler");return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error instanceof Error?error.message:String(error)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema=="object"&&COMPLETABLE_SYMBOL in schema}__name(isCompletable,"isCompletable");function getCompleter(schema){return schema[COMPLETABLE_SYMBOL]?.complete}__name(getCompleter,"getCompleter");var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2.Completable="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=name.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c2=>`"${c2}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}__name(validateToolName,"validateToolName");function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}__name(issueToolNameWarning,"issueToolNameWarning");function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}__name(validateAndWarnToolName,"validateAndWarnToolName");var ExperimentalMcpServerTasks=class{static{__name(this,"ExperimentalMcpServerTasks")}constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name,config,handler){let execution={taskSupport:"required",...config.execution};if(execution.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(name,config.title,config.description,config.inputSchema,config.outputSchema,config.annotations,execution,config._meta,handler)}};import{ZodOptional}from"zod";var McpServer=class{static{__name(this,"McpServer")}constructor(serverInfo,options){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(serverInfo,options)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalMcpServerTasks(this)}),this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:(()=>{let obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){let obj=normalizeObjectSchema(tool.outputSchema);obj&&(toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"output"}))}return toolDefinition})})),this.server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{try{let tool=this._registeredTools[request.params.name];if(!tool)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);let isTaskRequest=!!request.params.task,taskSupport=tool.execution?.taskSupport,isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler)throw new McpError(ErrorCode.InternalError,`Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);if(taskSupport==="required"&&!isTaskRequest)throw new McpError(ErrorCode.MethodNotFound,`Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler)return await this.handleAutomaticTaskPolling(tool,request,extra);let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,extra);return isTaskRequest||await this.validateToolOutput(tool,result,request.params.name),result}catch(error){if(error instanceof McpError&&error.code===ErrorCode.UrlElicitationRequired)throw error;return this.createToolError(error instanceof Error?error.message:String(error))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage3){return{content:[{type:"text",text:errorMessage3}],isError:!0}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema)return;let schemaToParse=normalizeObjectSchema(tool.inputSchema)??tool.inputSchema,parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage3}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||!("content"in result)||result.isError)return;if(!result.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let outputObj=normalizeObjectSchema(tool.outputSchema),parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage3}`)}}async executeToolHandler(tool,args,extra){let handler=tool.handler;if("createTask"in handler){if(!extra.taskStore)throw new Error("No task store provided.");let taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request,extra){if(!extra.taskStore)throw new Error("No task store provided for task-capable tool.");let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),handler=tool.handler,taskExtra={...extra,taskStore:extra.taskStore},createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra)),taskId=createTaskResult.task.taskId,task=createTaskResult.task,pollInterval=task.pollInterval??5e3;for(;task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled";){await new Promise(resolve10=>setTimeout(resolve10,pollInterval));let updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask)throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`);task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=getObjectShape(prompt.argsSchema)?.[request.params.argument.name];if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(request,extra)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(extra);for(let resource of result.resources)templateResources.push({...template.metadata,...resource})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(request,extra)=>{let uri=new URL(request.params.uri),resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`);return resource.readCallback(uri,extra)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables)return template.readCallback(uri,variables,extra)}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(request,extra)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);if(prompt.argsSchema){let argsObj=normalizeObjectSchema(prompt.argsSchema),parseResult=await safeParseAsync2(argsObj,request.params.arguments);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request.params.name}: ${errorMessage3}`)}let args=parseResult.data,cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{let cb=prompt.callback;return await Promise.resolve(cb(extra))}}),this._promptHandlersInitialized=!0)}resource(name,uriOrTemplate,...rest){let metadata;typeof rest[0]=="object"&&(metadata=rest.shift());let readCallback=rest[0];if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}registerResource(name,uriOrTemplate,config,readCallback){if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,readCallback){let registeredResource={name,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResource.update({enabled:!1}),"disable"),enable:__name(()=>registeredResource.update({enabled:!0}),"enable"),remove:__name(()=>registeredResource.update({uri:null}),"remove"),update:__name(updates=>{typeof updates.uri<"u"&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),typeof updates.name<"u"&&(registeredResource.name=updates.name),typeof updates.title<"u"&&(registeredResource.title=updates.title),typeof updates.metadata<"u"&&(registeredResource.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResource.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()},"update")};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResourceTemplate.update({enabled:!1}),"disable"),enable:__name(()=>registeredResourceTemplate.update({enabled:!0}),"enable"),remove:__name(()=>registeredResourceTemplate.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),typeof updates.title<"u"&&(registeredResourceTemplate.title=updates.title),typeof updates.template<"u"&&(registeredResourceTemplate.resourceTemplate=updates.template),typeof updates.metadata<"u"&&(registeredResourceTemplate.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResourceTemplate.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()},"update")};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback){let registeredPrompt={title,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:!0,disable:__name(()=>registeredPrompt.update({enabled:!1}),"disable"),enable:__name(()=>registeredPrompt.update({enabled:!0}),"enable"),remove:__name(()=>registeredPrompt.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),typeof updates.title<"u"&&(registeredPrompt.title=updates.title),typeof updates.description<"u"&&(registeredPrompt.description=updates.description),typeof updates.argsSchema<"u"&&(registeredPrompt.argsSchema=objectFromShape(updates.argsSchema)),typeof updates.callback<"u"&&(registeredPrompt.callback=updates.callback),typeof updates.enabled<"u"&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()},"update")};return this._registeredPrompts[name]=registeredPrompt,argsSchema&&Object.values(argsSchema).some(field=>{let inner=field instanceof ZodOptional?field._def?.innerType:field;return isCompletable(inner)})&&this.setCompletionRequestHandler(),registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,execution,_meta,handler){validateAndWarnToolName(name);let registeredTool={title,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations:annotations2,execution,_meta,handler,enabled:!0,disable:__name(()=>registeredTool.update({enabled:!1}),"disable"),enable:__name(()=>registeredTool.update({enabled:!0}),"enable"),remove:__name(()=>registeredTool.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],updates.name&&(this._registeredTools[updates.name]=registeredTool)),typeof updates.title<"u"&&(registeredTool.title=updates.title),typeof updates.description<"u"&&(registeredTool.description=updates.description),typeof updates.paramsSchema<"u"&&(registeredTool.inputSchema=objectFromShape(updates.paramsSchema)),typeof updates.outputSchema<"u"&&(registeredTool.outputSchema=objectFromShape(updates.outputSchema)),typeof updates.callback<"u"&&(registeredTool.handler=updates.callback),typeof updates.annotations<"u"&&(registeredTool.annotations=updates.annotations),typeof updates._meta<"u"&&(registeredTool._meta=updates._meta),typeof updates.enabled<"u"&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()},"update")};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}tool(name,...rest){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let description,inputSchema,outputSchema,annotations2;if(typeof rest[0]=="string"&&(description=rest.shift()),rest.length>1){let firstArg=rest[0];isZodRawShapeCompat(firstArg)?(inputSchema=rest.shift(),rest.length>1&&typeof rest[0]=="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])&&(annotations2=rest.shift())):typeof firstArg=="object"&&firstArg!==null&&(annotations2=rest.shift())}let callback=rest[0];return this._createRegisteredTool(name,void 0,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},void 0,callback)}registerTool(name,config,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema,outputSchema,annotations:annotations2,_meta}=config;return this._createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},_meta,cb)}prompt(name,...rest){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let description;typeof rest[0]=="string"&&(description=rest.shift());let argsSchema;rest.length>1&&(argsSchema=rest.shift());let cb=rest[0],registeredPrompt=this._createRegisteredPrompt(name,void 0,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}registerPrompt(name,config,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema}=config,registeredPrompt=this._createRegisteredPrompt(name,title,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value=="object"&&"parse"in value&&typeof value.parse=="function"&&"safeParse"in value&&typeof value.safeParse=="function"}__name(isZodTypeLike,"isZodTypeLike");function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}__name(isZodSchemaInstance,"isZodSchemaInstance");function isZodRawShapeCompat(obj){return typeof obj!="object"||obj===null||isZodSchemaInstance(obj)?!1:Object.keys(obj).length===0?!0:Object.values(obj).some(isZodTypeLike)}__name(isZodRawShapeCompat,"isZodRawShapeCompat");function getZodSchemaObject(schema){if(schema)return isZodRawShapeCompat(schema)?objectFromShape(schema):schema}__name(getZodSchemaObject,"getZodSchemaObject");function promptArgumentsFromSchema(schema){let shape=getObjectShape(schema);return shape?Object.entries(shape).map(([name,field])=>{let description=getSchemaDescription(field),isOptional=isSchemaOptional(field);return{name,description,required:!isOptional}}):[]}__name(promptArgumentsFromSchema,"promptArgumentsFromSchema");function getMethodValue(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value=="string")return value;throw new Error("Schema method literal must be a string")}__name(getMethodValue,"getMethodValue");function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}__name(createCompletionResult,"createCompletionResult");var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var MCP_SERVER_NAME="fimo",MCP_SERVER_VERSION="0.2.0";function toolError(code2,message){return{content:[{type:"text",text:JSON.stringify({code:code2,message})}],isError:!0}}__name(toolError,"toolError");function toolResult(payload){return{content:[{type:"text",text:JSON.stringify(payload)}]}}__name(toolResult,"toolResult");async function responseBody(response){let text3=await response.text();if(!text3)return null;try{return JSON.parse(text3)}catch{return{message:text3}}}__name(responseBody,"responseBody");async function mapResponse(response){let body=await responseBody(response);if(!response.ok){let payload=body&&typeof body=="object"?body:null,code2=payload&&typeof payload.code=="string"?payload.code:`http_${response.status}`,message=payload&&typeof payload.message=="string"?payload.message:`Fimo API request failed with status ${response.status}.`;return toolError(code2,message)}return{content:[{type:"text",text:JSON.stringify(body)}]}}__name(mapResponse,"mapResponse");function resolveScope2(tool,input,host){if(tool.scope==="none")return{ok:!0,scope:{projectId:"",env:""}};let projectId=typeof input.projectId=="string"?input.projectId:host.defaults?.projectId;if(!projectId)return{ok:!1,error:toolError("missing_project","Pass projectId \u2014 this MCP server is not bound to a project.")};if(tool.scope==="project")return{ok:!0,scope:{projectId,env:""}};let env=typeof input.env=="string"?input.env:host.defaults?.env;return env?{ok:!0,scope:{projectId,env}}:{ok:!1,error:toolError("missing_env","Pass env (for example 'main') \u2014 this MCP server is not bound to an environment.")}}__name(resolveScope2,"resolveScope");async function runTool(host,name,tool,input){let resolution=resolveScope2(tool,input,host);if(!resolution.ok)return resolution.error;if(host.authorize)try{await host.authorize({tool:name,accessScope:tool.accessScope,operation:tool.operation,projectId:resolution.scope.projectId||void 0,env:resolution.scope.env||void 0})}catch(error){let code2=error&&typeof error=="object"&&typeof error.code=="string"?error.code:"authorization_denied";return toolError(code2,error instanceof Error?error.message:String(error))}if(!tool.buildRequest){let identity2=await host.identity();return toolResult(identity2)}let request=tool.buildRequest(input,resolution.scope),response;try{response=await host.dispatch(request)}catch(error){return toolError("dispatch_failed",error instanceof Error?error.message:String(error))}return mapResponse(response)}__name(runTool,"runTool");function createFimoMcpServer(host){let server=new McpServer({name:MCP_SERVER_NAME,version:MCP_SERVER_VERSION});for(let[name,definition]of Object.entries(mcpToolCatalog)){let tool=definition;server.registerTool(name,{description:tool.description,inputSchema:tool.inputSchema,annotations:tool.annotations},async input=>runTool(host,name,tool,input??{}))}return server}__name(createFimoMcpServer,"createFimoMcpServer");import process8 from"node:process";var ReadBuffer=class{static{__name(this,"ReadBuffer")}append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index2=this._buffer.indexOf(`
1346
+ ]`;continue}pattern+=source[i],source[i]==="\\"?isEscaped2=!0:inCharGroup&&source[i]==="]"?inCharGroup=!1:!inCharGroup&&source[i]==="["&&(inCharGroup=!0)}try{new RegExp(pattern)}catch{return console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),regex.source}return pattern}__name(stringifyRegExpWithFlags,"stringifyRegExpWithFlags");function parseRecordDef(def,refs){if(refs.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties};let schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3")return schema;if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.checks?.length){let{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else{if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{...schema,propertyNames:{enum:def.keyType._def.values}};if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.type._def.checks?.length){let{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}}return schema}__name(parseRecordDef,"parseRecordDef");function parseMapDef(def,refs){if(refs.mapStrategy==="record")return parseRecordDef(def,refs);let keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs),values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}__name(parseMapDef,"parseMapDef");function parseNativeEnumDef(def){let object4=def.values,actualValues=Object.keys(def.values).filter(key=>typeof object4[object4[key]]!="number").map(key=>object4[key]),parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}__name(parseNativeEnumDef,"parseNativeEnumDef");function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}__name(parseNeverDef,"parseNeverDef");function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}__name(parseNullDef,"parseNullDef");var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);let options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x=>x._def.typeName in primitiveMappings&&(!x._def.checks||!x._def.checks.length))){let types=options.reduce((types2,x)=>{let type=primitiveMappings[x._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x=>x._def.typeName==="ZodLiteral"&&!x.description)){let types=options.reduce((acc,x)=>{let type=typeof x._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x._def.value===null)return[...acc,"null"];default:return acc}},[]);if(types.length===options.length){let uniqueTypes=types.filter((x,i,a)=>a.indexOf(x)===i);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x)=>acc.includes(x._def.value)?acc:[...acc,x._def.value],[])}}}else if(options.every(x=>x._def.typeName==="ZodEnum"))return{type:"string",enum:options.reduce((acc,x)=>[...acc,...x._def.values.filter(x2=>!acc.includes(x2))],[])};return asAnyOf(def,refs)}__name(parseUnionDef,"parseUnionDef");var asAnyOf=__name((def,refs)=>{let anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i}`]})).filter(x=>!!x&&(!refs.strictUnions||typeof x=="object"&&Object.keys(x).length>0));return anyOf.length?{anyOf}:void 0},"asAnyOf");function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length))return refs.target==="openApi3"?{type:primitiveMappings[def.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[def.innerType._def.typeName],"null"]};if(refs.target==="openApi3"){let base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});return base2&&"$ref"in base2?{allOf:[base2],nullable:!0}:base2&&{...base2,nullable:!0}}let base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}__name(parseNullableDef,"parseNullableDef");function parseNumberDef(def,refs){let res={type:"number"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"int":res.type="integer",addErrorMessage(res,"type",check.message,refs);break;case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseNumberDef,"parseNumberDef");function parseObjectDef(def,refs){let forceOptionalIntoNullable=refs.target==="openAi",result={type:"object",properties:{}},required=[],shape=def.shape();for(let propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0)continue;let propOptional=safeIsOptional(propDef);propOptional&&forceOptionalIntoNullable&&(propDef._def.typeName==="ZodOptional"&&(propDef=propDef._def.innerType),propDef.isNullable()||(propDef=propDef.nullable()),propOptional=!1);let parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});parsedDef!==void 0&&(result.properties[propName]=parsedDef,propOptional||required.push(propName))}required.length&&(result.required=required);let additionalProperties=decideAdditionalProperties(def,refs);return additionalProperties!==void 0&&(result.additionalProperties=additionalProperties),result}__name(parseObjectDef,"parseObjectDef");function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever")return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]});switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}__name(decideAdditionalProperties,"decideAdditionalProperties");function safeIsOptional(schema){try{return schema.isOptional()}catch{return!0}}__name(safeIsOptional,"safeIsOptional");var parseOptionalDef=__name((def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString())return parseDef(def.innerType._def,refs);let innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)},"parseOptionalDef");var parsePipelineDef=__name((def,refs)=>{if(refs.pipeStrategy==="input")return parseDef(def.in._def,refs);if(refs.pipeStrategy==="output")return parseDef(def.out._def,refs);let a=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),b=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a?"1":"0"]});return{allOf:[a,b].filter(x=>x!==void 0)}},"parsePipelineDef");function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}__name(parsePromiseDef,"parsePromiseDef");function parseSetDef(def,refs){let schema={type:"array",uniqueItems:!0,items:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]})};return def.minSize&&setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs),def.maxSize&&setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs),schema}__name(parseSetDef,"parseSetDef");function parseTupleDef(def,refs){return def.rest?{type:"array",minItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}:{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[])}}__name(parseTupleDef,"parseTupleDef");function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}__name(parseUndefinedDef,"parseUndefinedDef");function parseUnknownDef(refs){return parseAnyDef(refs)}__name(parseUnknownDef,"parseUnknownDef");var parseReadonlyDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseReadonlyDef");var selectParser=__name((def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind3.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind3.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind3.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind3.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind3.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind3.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind3.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind3.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind3.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind3.ZodUnion:case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind3.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind3.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind3.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind3.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind3.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind3.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind3.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind3.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind3.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind3.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind3.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind3.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind3.ZodNaN:case ZodFirstPartyTypeKind3.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind3.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind3.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind3.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind3.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind3.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind3.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind3.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind3.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind3.ZodFunction:case ZodFirstPartyTypeKind3.ZodVoid:case ZodFirstPartyTypeKind3.ZodSymbol:return;default:return(_=>{})(typeName)}},"selectParser");function parseDef(def,refs,forceResolution=!1){let seenItem=refs.seen.get(def);if(refs.override){let overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride)return overrideResult}if(seenItem&&!forceResolution){let seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0)return seenSchema}let newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);let jsonSchemaOrGetter=selectParser(def,def.typeName,refs),jsonSchema=typeof jsonSchemaOrGetter=="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema&&addMeta(def,refs,jsonSchema),refs.postProcess){let postProcessResult=refs.postProcess(jsonSchema,def,refs);return newItem.jsonSchema=jsonSchema,postProcessResult}return newItem.jsonSchema=jsonSchema,jsonSchema}__name(parseDef,"parseDef");var get$ref=__name((item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":return item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)?(console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`),parseAnyDef(refs)):refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}},"get$ref"),addMeta=__name((def,refs,jsonSchema)=>(def.description&&(jsonSchema.description=def.description,refs.markdownDescription&&(jsonSchema.markdownDescription=def.description)),jsonSchema),"addMeta");var zodToJsonSchema=__name((schema,options)=>{let refs=getRefs(options),definitions=typeof options=="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name2,schema2])=>({...acc,[name2]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},!0)??parseAnyDef(refs)}),{}):void 0,name=typeof options=="string"?options:options?.nameStrategy==="title"?void 0:options?.name,main=parseDef(schema._def,name===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name]},!1)??parseAnyDef(refs),title=typeof options=="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;title!==void 0&&(main.title=title),refs.flags.hasReferencedOpenAiAnyType&&(definitions||(definitions={}),definitions[refs.openAiAnyTypeName]||(definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}));let combined=name===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};return refs.target==="jsonSchema7"?combined.$schema="http://json-schema.org/draft-07/schema#":(refs.target==="jsonSchema2019-09"||refs.target==="openAi")&&(combined.$schema="https://json-schema.org/draft/2019-09/schema#"),refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),combined},"zodToJsonSchema");function mapMiniTarget(t2){return!t2||t2==="jsonSchema7"||t2==="draft-7"?"draft-7":t2==="jsonSchema2019-09"||t2==="draft-2020-12"?"draft-2020-12":"draft-7"}__name(mapMiniTarget,"mapMiniTarget");function toJsonSchemaCompat(schema,opts){return isZ4Schema(schema)?z4mini2.toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"}):zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??!0,pipeStrategy:opts?.pipeStrategy??"input"})}__name(toJsonSchemaCompat,"toJsonSchemaCompat");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}__name(getMethodLiteral,"getMethodLiteral");function parseWithCompat(schema,data2){let result=safeParse3(schema,data2);if(!result.success)throw result.error;return result.data}__name(parseWithCompat,"parseWithCompat");var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{static{__name(this,"Protocol")}constructor(_options){this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=__name(async()=>{let taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage3=message,error=new McpError(errorMessage3.error.code,errorMessage3.error.message,errorMessage3.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()},"handleTaskResult");return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error=>this._onerror(new Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error=>this._onerror(new Error(`Failed to enqueue error response: ${error}`))):capturedTransport?.send(errorResponse).catch(error=>this._onerror(new Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:__name(async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},"sendNotification"),sendRequest:__name(async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},"sendRequest"),authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error=>this._onerror(new Error(`Failed to send response: ${error}`))).finally(()=>{this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve10=>setTimeout(resolve10,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve10,reject)=>{let earlyReject=__name(error=>{reject(error)},"earlyReject");if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=__name(reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>this._onerror(new Error(`Failed to send cancellation: ${error2}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)},"cancel");this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);parseResult.success?resolve10(parseResult.data):reject(parseResult.error)}catch(error){reject(error)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=__name(()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout})),"timeoutHandler");this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=__name(response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))},"responseResolver");this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve10,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve10,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:__name(async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},"createTask"),getTask:__name(async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},"getTask"),storeTaskResult:__name(async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},"storeTaskResult"),getTaskResult:__name(taskId=>taskStore.getTaskResult(taskId,sessionId),"getTaskResult"),updateTaskStatus:__name(async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},"updateTaskStatus"),listTasks:__name(cursor=>taskStore.listTasks(cursor,sessionId),"listTasks")}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}__name(isPlainObject2,"isPlainObject");function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}__name(mergeCapabilities,"mergeCapabilities");var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist4(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}__name(createDefaultAjvInstance,"createDefaultAjvInstance");var AjvJsonSchemaValidator=class{static{__name(this,"AjvJsonSchemaValidator")}constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{static{__name(this,"ExperimentalServerTasks")}constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode2=params.mode??"form";switch(mode2){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode2==="form"&&params.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}__name(assertToolsCallTaskCapability,"assertToolsCallTaskCapability");function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}__name(assertClientRequestTaskCapability,"assertClientRequestTaskCapability");var Server=class extends Protocol{static{__name(this,"Server")}constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue;if(isZ4Schema(methodSchema)){let v4Schema=methodSchema;methodValue=v4Schema._zod?.def?.value??v4Schema.value}else{let v3Schema=methodSchema;methodValue=v3Schema._def?.value??v3Schema.value}if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=__name(async(request,extra)=>{let validatedRequest=safeParse3(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage3=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage3}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage3=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage3}`)}return taskValidationResult.data}let validationResult=safeParse3(CallToolResultSchema,result);if(!validationResult.success){let errorMessage3=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage3}`)}return validationResult.data},"wrappedHandler");return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error instanceof Error?error.message:String(error)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema=="object"&&COMPLETABLE_SYMBOL in schema}__name(isCompletable,"isCompletable");function getCompleter(schema){return schema[COMPLETABLE_SYMBOL]?.complete}__name(getCompleter,"getCompleter");var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2.Completable="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=name.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c2=>`"${c2}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}__name(validateToolName,"validateToolName");function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}__name(issueToolNameWarning,"issueToolNameWarning");function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}__name(validateAndWarnToolName,"validateAndWarnToolName");var ExperimentalMcpServerTasks=class{static{__name(this,"ExperimentalMcpServerTasks")}constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name,config,handler){let execution={taskSupport:"required",...config.execution};if(execution.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(name,config.title,config.description,config.inputSchema,config.outputSchema,config.annotations,execution,config._meta,handler)}};import{ZodOptional}from"zod";var McpServer=class{static{__name(this,"McpServer")}constructor(serverInfo,options){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(serverInfo,options)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalMcpServerTasks(this)}),this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:(()=>{let obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){let obj=normalizeObjectSchema(tool.outputSchema);obj&&(toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"output"}))}return toolDefinition})})),this.server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{try{let tool=this._registeredTools[request.params.name];if(!tool)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);let isTaskRequest=!!request.params.task,taskSupport=tool.execution?.taskSupport,isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler)throw new McpError(ErrorCode.InternalError,`Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);if(taskSupport==="required"&&!isTaskRequest)throw new McpError(ErrorCode.MethodNotFound,`Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler)return await this.handleAutomaticTaskPolling(tool,request,extra);let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,extra);return isTaskRequest||await this.validateToolOutput(tool,result,request.params.name),result}catch(error){if(error instanceof McpError&&error.code===ErrorCode.UrlElicitationRequired)throw error;return this.createToolError(error instanceof Error?error.message:String(error))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage3){return{content:[{type:"text",text:errorMessage3}],isError:!0}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema)return;let schemaToParse=normalizeObjectSchema(tool.inputSchema)??tool.inputSchema,parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage3}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||!("content"in result)||result.isError)return;if(!result.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let outputObj=normalizeObjectSchema(tool.outputSchema),parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage3}`)}}async executeToolHandler(tool,args,extra){let handler=tool.handler;if("createTask"in handler){if(!extra.taskStore)throw new Error("No task store provided.");let taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request,extra){if(!extra.taskStore)throw new Error("No task store provided for task-capable tool.");let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),handler=tool.handler,taskExtra={...extra,taskStore:extra.taskStore},createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra)),taskId=createTaskResult.task.taskId,task=createTaskResult.task,pollInterval=task.pollInterval??5e3;for(;task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled";){await new Promise(resolve10=>setTimeout(resolve10,pollInterval));let updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask)throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`);task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=getObjectShape(prompt.argsSchema)?.[request.params.argument.name];if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(request,extra)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(extra);for(let resource of result.resources)templateResources.push({...template.metadata,...resource})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(request,extra)=>{let uri=new URL(request.params.uri),resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`);return resource.readCallback(uri,extra)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables)return template.readCallback(uri,variables,extra)}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(request,extra)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);if(prompt.argsSchema){let argsObj=normalizeObjectSchema(prompt.argsSchema),parseResult=await safeParseAsync2(argsObj,request.params.arguments);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage3=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request.params.name}: ${errorMessage3}`)}let args=parseResult.data,cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{let cb=prompt.callback;return await Promise.resolve(cb(extra))}}),this._promptHandlersInitialized=!0)}resource(name,uriOrTemplate,...rest){let metadata;typeof rest[0]=="object"&&(metadata=rest.shift());let readCallback=rest[0];if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}registerResource(name,uriOrTemplate,config,readCallback){if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,readCallback){let registeredResource={name,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResource.update({enabled:!1}),"disable"),enable:__name(()=>registeredResource.update({enabled:!0}),"enable"),remove:__name(()=>registeredResource.update({uri:null}),"remove"),update:__name(updates=>{typeof updates.uri<"u"&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),typeof updates.name<"u"&&(registeredResource.name=updates.name),typeof updates.title<"u"&&(registeredResource.title=updates.title),typeof updates.metadata<"u"&&(registeredResource.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResource.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()},"update")};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResourceTemplate.update({enabled:!1}),"disable"),enable:__name(()=>registeredResourceTemplate.update({enabled:!0}),"enable"),remove:__name(()=>registeredResourceTemplate.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),typeof updates.title<"u"&&(registeredResourceTemplate.title=updates.title),typeof updates.template<"u"&&(registeredResourceTemplate.resourceTemplate=updates.template),typeof updates.metadata<"u"&&(registeredResourceTemplate.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResourceTemplate.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()},"update")};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback){let registeredPrompt={title,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:!0,disable:__name(()=>registeredPrompt.update({enabled:!1}),"disable"),enable:__name(()=>registeredPrompt.update({enabled:!0}),"enable"),remove:__name(()=>registeredPrompt.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),typeof updates.title<"u"&&(registeredPrompt.title=updates.title),typeof updates.description<"u"&&(registeredPrompt.description=updates.description),typeof updates.argsSchema<"u"&&(registeredPrompt.argsSchema=objectFromShape(updates.argsSchema)),typeof updates.callback<"u"&&(registeredPrompt.callback=updates.callback),typeof updates.enabled<"u"&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()},"update")};return this._registeredPrompts[name]=registeredPrompt,argsSchema&&Object.values(argsSchema).some(field=>{let inner=field instanceof ZodOptional?field._def?.innerType:field;return isCompletable(inner)})&&this.setCompletionRequestHandler(),registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,execution,_meta,handler){validateAndWarnToolName(name);let registeredTool={title,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations:annotations2,execution,_meta,handler,enabled:!0,disable:__name(()=>registeredTool.update({enabled:!1}),"disable"),enable:__name(()=>registeredTool.update({enabled:!0}),"enable"),remove:__name(()=>registeredTool.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],updates.name&&(this._registeredTools[updates.name]=registeredTool)),typeof updates.title<"u"&&(registeredTool.title=updates.title),typeof updates.description<"u"&&(registeredTool.description=updates.description),typeof updates.paramsSchema<"u"&&(registeredTool.inputSchema=objectFromShape(updates.paramsSchema)),typeof updates.outputSchema<"u"&&(registeredTool.outputSchema=objectFromShape(updates.outputSchema)),typeof updates.callback<"u"&&(registeredTool.handler=updates.callback),typeof updates.annotations<"u"&&(registeredTool.annotations=updates.annotations),typeof updates._meta<"u"&&(registeredTool._meta=updates._meta),typeof updates.enabled<"u"&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()},"update")};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}tool(name,...rest){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let description,inputSchema,outputSchema,annotations2;if(typeof rest[0]=="string"&&(description=rest.shift()),rest.length>1){let firstArg=rest[0];isZodRawShapeCompat(firstArg)?(inputSchema=rest.shift(),rest.length>1&&typeof rest[0]=="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])&&(annotations2=rest.shift())):typeof firstArg=="object"&&firstArg!==null&&(annotations2=rest.shift())}let callback=rest[0];return this._createRegisteredTool(name,void 0,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},void 0,callback)}registerTool(name,config,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema,outputSchema,annotations:annotations2,_meta}=config;return this._createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},_meta,cb)}prompt(name,...rest){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let description;typeof rest[0]=="string"&&(description=rest.shift());let argsSchema;rest.length>1&&(argsSchema=rest.shift());let cb=rest[0],registeredPrompt=this._createRegisteredPrompt(name,void 0,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}registerPrompt(name,config,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema}=config,registeredPrompt=this._createRegisteredPrompt(name,title,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value=="object"&&"parse"in value&&typeof value.parse=="function"&&"safeParse"in value&&typeof value.safeParse=="function"}__name(isZodTypeLike,"isZodTypeLike");function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}__name(isZodSchemaInstance,"isZodSchemaInstance");function isZodRawShapeCompat(obj){return typeof obj!="object"||obj===null||isZodSchemaInstance(obj)?!1:Object.keys(obj).length===0?!0:Object.values(obj).some(isZodTypeLike)}__name(isZodRawShapeCompat,"isZodRawShapeCompat");function getZodSchemaObject(schema){if(schema)return isZodRawShapeCompat(schema)?objectFromShape(schema):schema}__name(getZodSchemaObject,"getZodSchemaObject");function promptArgumentsFromSchema(schema){let shape=getObjectShape(schema);return shape?Object.entries(shape).map(([name,field])=>{let description=getSchemaDescription(field),isOptional=isSchemaOptional(field);return{name,description,required:!isOptional}}):[]}__name(promptArgumentsFromSchema,"promptArgumentsFromSchema");function getMethodValue(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value=="string")return value;throw new Error("Schema method literal must be a string")}__name(getMethodValue,"getMethodValue");function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}__name(createCompletionResult,"createCompletionResult");var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var MCP_SERVER_NAME="fimo",MCP_SERVER_VERSION="0.2.0";function toolError(code2,message){return{content:[{type:"text",text:JSON.stringify({code:code2,message})}],isError:!0}}__name(toolError,"toolError");function toolResult(payload){return{content:[{type:"text",text:JSON.stringify(payload)}]}}__name(toolResult,"toolResult");async function responseBody(response){let text3=await response.text();if(!text3)return null;try{return JSON.parse(text3)}catch{return{message:text3}}}__name(responseBody,"responseBody");async function mapResponse(response){let body=await responseBody(response);if(!response.ok){let payload=body&&typeof body=="object"?body:null,code2=payload&&typeof payload.code=="string"?payload.code:`http_${response.status}`,message=payload&&typeof payload.message=="string"?payload.message:`Fimo API request failed with status ${response.status}.`;return toolError(code2,message)}return{content:[{type:"text",text:JSON.stringify(body)}]}}__name(mapResponse,"mapResponse");function resolveScope2(tool,input,host){if(tool.scope==="none")return{ok:!0,scope:{projectId:"",env:""}};let projectId=typeof input.projectId=="string"?input.projectId:host.defaults?.projectId;if(!projectId)return{ok:!1,error:toolError("missing_project","Pass projectId \u2014 this MCP server is not bound to a project.")};if(tool.scope==="project")return{ok:!0,scope:{projectId,env:""}};let env=typeof input.env=="string"?input.env:host.defaults?.env;return env?{ok:!0,scope:{projectId,env}}:{ok:!1,error:toolError("missing_env","Pass env (for example 'main') \u2014 this MCP server is not bound to an environment.")}}__name(resolveScope2,"resolveScope");async function runTool(host,name,tool,input){let resolution=resolveScope2(tool,input,host);if(!resolution.ok)return resolution.error;if(host.authorize)try{await host.authorize({tool:name,accessScope:tool.accessScope,operation:tool.operation,projectId:resolution.scope.projectId||void 0,env:resolution.scope.env||void 0})}catch(error){let code2=error&&typeof error=="object"&&typeof error.code=="string"?error.code:"authorization_denied";return toolError(code2,error instanceof Error?error.message:String(error))}if(!tool.buildRequest){let identity2=await host.identity();return toolResult(identity2)}let request=tool.buildRequest(input,resolution.scope),response;try{response=await host.dispatch(request)}catch(error){return toolError("dispatch_failed",error instanceof Error?error.message:String(error))}return mapResponse(response)}__name(runTool,"runTool");function createFimoMcpServer(host){let server=new McpServer({name:MCP_SERVER_NAME,version:MCP_SERVER_VERSION});for(let[name,definition]of Object.entries(mcpToolCatalog)){let tool=definition;server.registerTool(name,{description:tool.description,inputSchema:tool.inputSchema,annotations:tool.annotations},async input=>runTool(host,name,tool,input??{}))}return server}__name(createFimoMcpServer,"createFimoMcpServer");import process8 from"node:process";var ReadBuffer=class{static{__name(this,"ReadBuffer")}append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index2=this._buffer.indexOf(`
1347
1347
  `);if(index2===-1)return null;let line=this._buffer.toString("utf8",0,index2).replace(/\r$/,"");return this._buffer=this._buffer.subarray(index2+1),deserializeMessage(line)}clear(){this._buffer=void 0}};function deserializeMessage(line){return JSONRPCMessageSchema.parse(JSON.parse(line))}__name(deserializeMessage,"deserializeMessage");function serializeMessage(message){return JSON.stringify(message)+`
1348
1348
  `}__name(serializeMessage,"serializeMessage");var StdioServerTransport=class{static{__name(this,"StdioServerTransport")}constructor(_stdin=process8.stdin,_stdout=process8.stdout){this._stdin=_stdin,this._stdout=_stdout,this._readBuffer=new ReadBuffer,this._started=!1,this._ondata=chunk=>{this._readBuffer.append(chunk),this.processReadBuffer()},this._onerror=error=>{this.onerror?.(error)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error){this.onerror?.(error)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise(resolve10=>{let json=serializeMessage(message);this._stdout.write(json)?resolve10():this._stdout.once("drain",resolve10)})}};init_api();init_config();init_project_context();function createCliMcpHost(client,defaults={}){return{identity:__name(async()=>{let session=await client.getCurrentSession();if(!session)throw new Error("Not signed in. Run `fimo login` or set FIMO_API_TOKEN.");return{id:session.user.id,email:session.user.email??null,name:session.user.name??null}},"identity"),dispatch:__name(request=>client.fetchRaw(`/api${request.path}`,{method:request.method,body:request.body!==void 0?JSON.stringify(request.body):void 0}),"dispatch"),authorize:__name(async({operation,projectId,env})=>{if(operation)try{await requireOperation(operation,{projectId,env})}catch(error){throw error instanceof CapabilityDenied?Object.assign(error,{code:"capability_denied"}):error}},"authorize"),defaults}}__name(createCliMcpHost,"createCliMcpHost");async function resolveDefaults(cmd){try{let ctx=await getProjectContext({envOverride:envOverrideFromCommand(cmd)});return ctx.readOnly?{projectId:ctx.projectId}:{projectId:ctx.projectId,env:ctx.env}}catch(error){if(error instanceof NotInProjectError||error instanceof GitBranchUndetectedError)return{};throw error}}__name(resolveDefaults,"resolveDefaults");async function mcpCommand(_options,cmd){let client=new FimoApiClient(loadConfig()),defaults=await resolveDefaults(cmd),server=createFimoMcpServer(createCliMcpHost(client,defaults)),transport=new StdioServerTransport,closed=new Promise(resolve10=>{server.server.onclose=()=>resolve10()});await server.connect(transport),process.stderr.write(`fimo mcp: serving over stdio${defaults.projectId?` (project ${defaults.projectId}${defaults.env?`, env ${defaults.env}`:""})`:""}
1349
1349
  `),await closed}__name(mcpCommand,"mcpCommand");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,api}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await api.estimateGenerationTask(ctx.projectId,task.id,options),data2={...body,estimate};ui.result({command:commandName2,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,api,body})}__name(runTask,"runTask");function registerTaskCommand(parent2,task){parent2.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");init_dist5();init_dist();init_api();init_auth_errors();init_color();import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync10,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path39 from"node:path";function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromEnv} \u2192 ${result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
@@ -1379,9 +1379,19 @@ Delivery:
1379
1379
  Runs use at-least-once delivery. If a completion response is lost, the same run may execute again.
1380
1380
  Side-effecting commands should use FIMO_SCHEDULE_RUN_ID as their idempotency key.
1381
1381
 
1382
+ Limits:
1383
+ Schedule capacity, cadence, compute, and concurrency follow the organization's plan.
1384
+ Use \`fimo schedules list\` or \`show\` for the current policy and reset state.
1385
+
1382
1386
  Run \`fimo schedules <command> --help\` for command-specific help.
1383
- `);addScopeOptions2(schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the environment").option("--secret <key>","Expose a project secret to the command; repeat for multiple keys",collect)).action((name,opts)=>createCommand2(name,opts)),addScopeOptions2(schedules.command("list").description("List schedules for an environment")).action(opts=>listCommand3(opts)),addScopeOptions2(schedules.command("show <schedule>").description("Show a schedule configuration")).action((schedule,opts)=>showCommand(schedule,opts)),addScopeOptions2(schedules.command("update <schedule>").description("Update a schedule configuration").option("--name <name>","Change the schedule name").option("--cron <expr>","Change the cron expression").option("--do <command>","Change the command").option("--secret <key>","Replace exposed project secrets; repeat for multiple keys",collect).option("--clear-secrets","Remove all project secrets from the schedule")).action((schedule,opts)=>updateCommand(schedule,opts)),addScopeOptions2(schedules.command("run <schedule>").description("Run a schedule now").option("--no-wait","Return after the run is queued")).action((schedule,opts)=>runCommand2(schedule,opts)),addScopeOptions2(schedules.command("pause <schedule>").description("Pause future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!1,opts)),addScopeOptions2(schedules.command("resume <schedule>").description("Resume future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!0,opts));let runs=addScopeOptions2(schedules.command("runs [schedule]").description("List runs for a schedule").option("--limit <count>","Maximum runs per page (1-100)").option("--cursor <cursor>","Continue from an opaque cursor").option("--status <status>","Filter by queued, running, succeeded, failed, or skipped").option("--all","Fetch all pages"));runs.action((schedule,opts,command)=>{if(!schedule){command.help();return}return runsCommand(schedule,opts)}),addScopeOptions2(runs.command("show <runId>").description("Show run details and captured output")).action((runId,opts,command)=>runShowCommand(runId,{...command.parent?.opts(),...opts})),addScopeOptions2(schedules.command("delete <schedule>").description("Delete a schedule")).action((schedule,opts)=>deleteCommand(schedule,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope3(op,opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(error){if(!opts.project)throw error;env=DEFAULT_ENV}let projectId=opts.project??loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId;return await requireOperation(op,{projectId,env}),{projectId,api:baseApi.withEnv(env)}}__name(resolveScope3,"resolveScope");async function resolveScheduleId(api,projectId,reference){if(UUID_PATTERN.test(reference))return reference;let schedule=(await api.listSchedules(projectId)).find(candidate=>candidate.name===reference);if(!schedule)throw new ScheduleCommandError("SCHEDULE_NOT_FOUND",`Schedule '${reference}' was not found in this environment.`);return schedule.id}__name(resolveScheduleId,"resolveScheduleId");async function createCommand2(name,opts){let parsed=CreateProjectScheduleRequestSchema.safeParse({name,cron:opts.cron,command:opts.do,secretKeys:opts.secret??[]});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule.");let{projectId,api}=await resolveScope3("schedules.create",opts),schedule=await api.createSchedule(projectId,parsed.data);renderSchedule("schedules create",schedule)}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope3("schedules.list",opts);renderScheduleList("schedules list",await api.getSchedulesOverview(projectId))}__name(listCommand3,"listCommand");async function showCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.get",opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderScheduleDetail("schedules show",await api.getSchedule(projectId,scheduleId))}__name(showCommand,"showCommand");async function updateCommand(reference,opts){if(opts.secret!==void 0&&opts.clearSecrets)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED","Use either --secret or --clear-secrets, not both.");let request={...opts.name!==void 0?{name:opts.name}:{},...opts.cron!==void 0?{cron:opts.cron}:{},...opts.do!==void 0?{command:opts.do}:{},...opts.clearSecrets?{secretKeys:[]}:opts.secret!==void 0?{secretKeys:opts.secret}:{}},parsed=UpdateProjectScheduleRequestSchema.safeParse(request);if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule update.");let{projectId,api}=await resolveScope3("schedules.update",opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderSchedule("schedules update",await api.updateSchedule(projectId,scheduleId,parsed.data))}__name(updateCommand,"updateCommand");async function toggleCommand(reference,enabled,opts){let{projectId,api}=await resolveScope3(enabled?"schedules.resume":"schedules.pause",opts),scheduleId=await resolveScheduleId(api,projectId,reference),schedule=await api.setScheduleEnabled(projectId,scheduleId,enabled);renderSchedule(enabled?"schedules resume":"schedules pause",schedule)}__name(toggleCommand,"toggleCommand");async function runCommand2(reference,opts){let{projectId,api}=await resolveScope3("schedules.run",opts),scheduleId=await resolveScheduleId(api,projectId,reference),run;try{run=await api.runSchedule(projectId,scheduleId)}catch(error){if(error instanceof ApiRequestError&&error.status===409&&error.code==="run_in_progress"){let activeRunId=readActiveRunId(error.body);ui.error({command:"schedules run",code:"SCHEDULE_RUN_IN_PROGRESS",message:activeRunId?`Schedule already has an active run: ${activeRunId}`:"Schedule already has an active run.",hint:activeRunId?`Inspect it with: fimo schedules runs show ${activeRunId}`:void 0});return}throw error}if(opts.wait===!1){renderRun("schedules run",run);return}let progress=spinner(`Run ${run.id} is ${run.status}`),deadline=Date.now()+RUN_POLL_TIMEOUT_MS,detail=await api.getScheduleRun(projectId,run.id);for(;!TERMINAL_RUN_STATUSES.includes(detail.status)&&Date.now()<deadline;)progress.update(`Run ${run.id} is ${detail.status}`),await new Promise(resolve10=>setTimeout(resolve10,RUN_POLL_INTERVAL_MS)),detail=await api.getScheduleRun(projectId,run.id);if(progress.stop(),!TERMINAL_RUN_STATUSES.includes(detail.status))throw new ScheduleCommandError("SCHEDULE_RUN_TIMEOUT",`Run ${run.id} did not finish within ${RUN_POLL_TIMEOUT_MS/6e4} minutes.`);if(detail.status!=="succeeded"){let error=detail.error??"No error details were returned.";ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule run ${detail.id} finished with status ${detail.status}: ${error}`,hint:`Inspect run ${detail.id} (status: ${detail.status}, error: ${error}) with: fimo schedules runs show ${detail.id}`});return}renderRunDetail("schedules run",detail)}__name(runCommand2,"runCommand");async function runsCommand(reference,opts){let parsed=ProjectScheduleRunsQuerySchema.safeParse({limit:opts.limit,cursor:opts.cursor,status:opts.status});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid run query.");let{projectId,api}=await resolveScope3("schedules.runs.list",opts),scheduleId=await resolveScheduleId(api,projectId,reference),page=await api.listScheduleRuns(projectId,scheduleId,parsed.data);if(opts.all){let items=[...page.items];for(;page.nextCursor;)page=await api.listScheduleRuns(projectId,scheduleId,{limit:parsed.data.limit,cursor:page.nextCursor,status:parsed.data.status}),items.push(...page.items);page={...page,items,nextCursor:null}}renderRuns("schedules runs",page)}__name(runsCommand,"runsCommand");async function runShowCommand(runId,opts){let{projectId,api}=await resolveScope3("schedules.runs.get",opts);renderRunDetail("schedules runs show",await api.getScheduleRun(projectId,runId))}__name(runShowCommand,"runShowCommand");async function deleteCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.delete",opts),scheduleId=await resolveScheduleId(api,projectId,reference),result=await api.deleteSchedule(projectId,scheduleId);ui.result({command:"schedules delete",data:result,render:__name(()=>`Deleted schedule ${reference} (${scheduleId})`,"render")})}__name(deleteCommand,"deleteCommand");function renderSchedule(command,schedule){ui.result({command,data:schedule,render:__name(()=>renderFields({ID:schedule.id,Name:schedule.name,Environment:schedule.env,Cron:schedule.cron,Command:schedule.command,Enabled:schedule.enabled?"yes":"no",Secrets:schedule.secretKeys.join(", ")||"none"}),"render")})}__name(renderSchedule,"renderSchedule");function renderScheduleList(command,data2){ui.result({command,data:data2,render:__name(()=>renderTable(["ID","NAME","CRON","COMMAND","ENABLED","LAST STATUS"],data2.items.map(schedule=>[schedule.id,schedule.name,schedule.cron,schedule.command,schedule.enabled?"yes":"no",schedule.lastStatus??""])),"render")})}__name(renderScheduleList,"renderScheduleList");function renderScheduleDetail(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderFields({ID:data2.schedule.id,Name:data2.schedule.name,Environment:data2.schedule.env,Cron:data2.schedule.cron,Command:data2.schedule.command,Enabled:data2.schedule.enabled?"yes":"no",Secrets:data2.schedule.secretKeys.join(", ")||"none",Runs:data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`})}
1384
- `,"render")})}__name(renderScheduleDetail,"renderScheduleDetail");function renderRun(command,run){ui.result({command,data:run,render:__name(()=>renderFields({"Run ID":run.id,Schedule:run.scheduleName,Command:run.command,Status:run.status,Trigger:run.trigger,Queued:String(run.queuedAt)}),"render")})}__name(renderRun,"renderRun");function renderRuns(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderTable(["RUN ID","STATUS","TRIGGER","ACTOR","QUEUED","STARTED","FINISHED"],data2.items.map(run=>[run.id,run.status,run.trigger,run.triggeredBy?.name??"",String(run.queuedAt),run.startedAt?String(run.startedAt):"",run.finishedAt?String(run.finishedAt):""]))}
1387
+ `);addScopeOptions2(schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the environment").option("--secret <key>","Expose a project secret to the command; repeat for multiple keys",collect).option("--paused","Save the schedule paused; it never runs until resumed and does not use an active slot")).action((name,opts)=>createCommand2(name,opts)),addScopeOptions2(schedules.command("list").description("List schedules for an environment")).action(opts=>listCommand3(opts)),addScopeOptions2(schedules.command("show <schedule>").description("Show a schedule configuration")).action((schedule,opts)=>showCommand(schedule,opts)),addScopeOptions2(schedules.command("update <schedule>").description("Update a schedule configuration").option("--name <name>","Change the schedule name").option("--cron <expr>","Change the cron expression").option("--do <command>","Change the command").option("--secret <key>","Replace exposed project secrets; repeat for multiple keys",collect).option("--clear-secrets","Remove all project secrets from the schedule")).action((schedule,opts)=>updateCommand(schedule,opts)),addScopeOptions2(schedules.command("run <schedule>").description("Run a schedule now").option("--no-wait","Return after the run is queued")).action((schedule,opts)=>runCommand2(schedule,opts)),addScopeOptions2(schedules.command("pause <schedule>").description("Pause future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!1,opts)),addScopeOptions2(schedules.command("resume <schedule>").description("Resume future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!0,opts));let runs=addScopeOptions2(schedules.command("runs [schedule]").description("List runs for a schedule").option("--limit <count>","Maximum runs per page (1-100)").option("--cursor <cursor>","Continue from an opaque cursor").option("--status <status>","Filter by queued, running, succeeded, failed, or skipped").option("--all","Fetch all pages"));runs.action((schedule,opts,command)=>{if(!schedule){command.help();return}return runsCommand(schedule,opts)}),addScopeOptions2(runs.command("show <runId>").description("Show run details and captured output")).action((runId,opts,command)=>runShowCommand(runId,{...command.parent?.opts(),...opts})),addScopeOptions2(schedules.command("delete <schedule>").description("Delete a schedule")).action((schedule,opts)=>deleteCommand(schedule,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope3(op,opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(error){if(!opts.project)throw error;env=DEFAULT_ENV}let projectId=opts.project??loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId;return await requireOperation(op,{projectId,env}),{projectId,api:baseApi.withEnv(env)}}__name(resolveScope3,"resolveScope");async function resolveScheduleId(api,projectId,reference){if(UUID_PATTERN.test(reference))return reference;let schedule=(await api.listSchedules(projectId)).find(candidate=>candidate.name===reference);if(!schedule)throw new ScheduleCommandError("SCHEDULE_NOT_FOUND",`Schedule '${reference}' was not found in this environment.`);return schedule.id}__name(resolveScheduleId,"resolveScheduleId");async function createCommand2(name,opts){let parsed=CreateProjectScheduleRequestSchema.safeParse({name,cron:opts.cron,command:opts.do,secretKeys:opts.secret??[],...opts.paused?{enabled:!1}:{}});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule.");let{projectId,api}=await resolveScope3("schedules.create",opts),schedule;try{schedule=await api.createSchedule(projectId,parsed.data)}catch(error){if(renderSchedulePolicyRefusal("schedules create",error,"create"))return;throw error}renderSchedule("schedules create",schedule)}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope3("schedules.list",opts);renderScheduleList("schedules list",await api.getSchedulesOverview(projectId))}__name(listCommand3,"listCommand");async function showCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.get",opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderScheduleDetail("schedules show",await api.getSchedule(projectId,scheduleId))}__name(showCommand,"showCommand");async function updateCommand(reference,opts){if(opts.secret!==void 0&&opts.clearSecrets)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED","Use either --secret or --clear-secrets, not both.");let request={...opts.name!==void 0?{name:opts.name}:{},...opts.cron!==void 0?{cron:opts.cron}:{},...opts.do!==void 0?{command:opts.do}:{},...opts.clearSecrets?{secretKeys:[]}:opts.secret!==void 0?{secretKeys:opts.secret}:{}},parsed=UpdateProjectScheduleRequestSchema.safeParse(request);if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule update.");let{projectId,api}=await resolveScope3("schedules.update",opts),scheduleId=await resolveScheduleId(api,projectId,reference);try{renderSchedule("schedules update",await api.updateSchedule(projectId,scheduleId,parsed.data))}catch(error){if(renderSchedulePolicyRefusal("schedules update",error,"update"))return;throw error}}__name(updateCommand,"updateCommand");async function toggleCommand(reference,enabled,opts){let command=enabled?"schedules resume":"schedules pause",{projectId,api}=await resolveScope3(enabled?"schedules.resume":"schedules.pause",opts),scheduleId=await resolveScheduleId(api,projectId,reference),schedule;try{schedule=await api.setScheduleEnabled(projectId,scheduleId,enabled)}catch(error){if(renderSchedulePolicyRefusal(command,error,"resume"))return;throw error}renderSchedule(command,schedule)}__name(toggleCommand,"toggleCommand");async function runCommand2(reference,opts){let{projectId,api}=await resolveScope3("schedules.run",opts),scheduleId=await resolveScheduleId(api,projectId,reference),run;try{run=await api.runSchedule(projectId,scheduleId)}catch(error){if(renderSchedulePolicyRefusal("schedules run",error,"run"))return;if(error instanceof ApiRequestError&&error.status===409&&error.code==="run_in_progress"){let activeRunId=readActiveRunId(error.body);ui.error({command:"schedules run",code:"SCHEDULE_RUN_IN_PROGRESS",message:activeRunId?`Schedule already has an active run: ${activeRunId}`:"Schedule already has an active run.",hint:activeRunId?`Inspect it with: fimo schedules runs show ${activeRunId}`:void 0});return}throw error}if(opts.wait===!1){renderRun("schedules run",run);return}let progress=spinner(`Run ${run.id} is ${run.status}`),deadline=Date.now()+RUN_POLL_TIMEOUT_MS,detail=await api.getScheduleRun(projectId,run.id);for(;!TERMINAL_RUN_STATUSES.includes(detail.status)&&Date.now()<deadline;)progress.update(`Run ${run.id} is ${detail.status}`),await new Promise(resolve10=>setTimeout(resolve10,RUN_POLL_INTERVAL_MS)),detail=await api.getScheduleRun(projectId,run.id);if(progress.stop(),!TERMINAL_RUN_STATUSES.includes(detail.status))throw new ScheduleCommandError("SCHEDULE_RUN_TIMEOUT",`Run ${run.id} did not finish within ${RUN_POLL_TIMEOUT_MS/6e4} minutes.`);if(detail.status!=="succeeded"){let error=detail.error??"No error details were returned.";ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule run ${detail.id} finished with status ${detail.status}: ${error}`,hint:`Inspect run ${detail.id} (status: ${detail.status}, error: ${error}) with: fimo schedules runs show ${detail.id}`});return}renderRunDetail("schedules run",detail)}__name(runCommand2,"runCommand");async function runsCommand(reference,opts){let parsed=ProjectScheduleRunsQuerySchema.safeParse({limit:opts.limit,cursor:opts.cursor,status:opts.status});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid run query.");let{projectId,api}=await resolveScope3("schedules.runs.list",opts),scheduleId=await resolveScheduleId(api,projectId,reference),page=await api.listScheduleRuns(projectId,scheduleId,parsed.data);if(opts.all){let items=[...page.items];for(;page.nextCursor;)page=await api.listScheduleRuns(projectId,scheduleId,{limit:parsed.data.limit,cursor:page.nextCursor,status:parsed.data.status}),items.push(...page.items);page={...page,items,nextCursor:null}}renderRuns("schedules runs",page)}__name(runsCommand,"runsCommand");async function runShowCommand(runId,opts){let{projectId,api}=await resolveScope3("schedules.runs.get",opts);renderRunDetail("schedules runs show",await api.getScheduleRun(projectId,runId))}__name(runShowCommand,"runShowCommand");async function deleteCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.delete",opts),scheduleId=await resolveScheduleId(api,projectId,reference),result=await api.deleteSchedule(projectId,scheduleId);ui.result({command:"schedules delete",data:result,render:__name(()=>`Deleted schedule ${reference} (${scheduleId})`,"render")})}__name(deleteCommand,"deleteCommand");function renderSchedulePolicyRefusal(command,error,context){if(!(error instanceof ApiRequestError)||!error.code)return!1;let presentation={active_schedule_limit_reached:{code:"SCHEDULE_LIMIT_REACHED",hint:context==="create"?"Pause another schedule, or re-run with --paused to save this one as a draft. Upgrade your plan for more active schedules.":"Pause another schedule first, then resume this one. Upgrade your plan for more active schedules."},cadence_too_frequent:{code:"SCHEDULE_CADENCE_TOO_FREQUENT",hint:"Pick a less frequent --cron expression; `fimo schedules list` shows your plan cadence floor. Upgrade your plan if you need a more frequent schedule."},allowance_exhausted:{code:"SCHEDULE_COMPUTE_EXHAUSTED",hint:"Cron runs are skipped and manual runs are rejected until the cycle resets; `fimo schedules list` shows the reset time. Editing schedules still works. Upgrade your plan for more schedule compute."},concurrency_limited:{code:"SCHEDULE_CONCURRENCY_LIMITED",hint:"Wait for a running schedule in this organization to finish, then retry. Upgrade your plan for more concurrent runs."},invalid_cron:{code:"SCHEDULE_INVALID_CRON",hint:"Use standard five-field cron syntax: minute hour day-of-month month day-of-week (for example, `0 2 * * *`)."}}[error.code];if(!presentation)return!1;let serverMessage=error.body&&typeof error.body=="object"&&typeof error.body.message=="string"?error.body.message:error.detail;return ui.error({command,code:presentation.code,message:serverMessage,hint:presentation.hint}),!0}__name(renderSchedulePolicyRefusal,"renderSchedulePolicyRefusal");function formatPlanMinutes(minutes){return minutes%60===0&&minutes>=60?`${minutes/60} h`:`${minutes} min`}__name(formatPlanMinutes,"formatPlanMinutes");function formatPlanMs(ms){return formatPlanMinutes(Math.round(ms/6e4))}__name(formatPlanMs,"formatPlanMs");function planStateNote(plan){switch(plan.state){case"near_limit":return"Over 80% of the compute cycle is used.";case"exhausted":return`Compute is exhausted. Cron runs are skipped and manual runs are rejected until ${String(plan.compute.resetsAt)}. Editing schedules still works.`;case"over_policy":return`Some schedules exceed the current plan limits (${plan.overPolicyReasons.join(", ")}). They keep running; enabling more or making them more frequent is blocked.`;default:return null}}__name(planStateNote,"planStateNote");function planFields(plan){return{Plan:plan.code,"Active schedules":`${plan.activeSchedules.used} of ${plan.activeSchedules.limit}`,"Cadence floor":`every ${formatPlanMinutes(plan.minCadenceMinutes)} or less often`,"Max run time":formatPlanMs(plan.maxRunMs),"Concurrent runs":`${plan.concurrency.used} of ${plan.concurrency.limit}`,"Compute used":`${formatPlanMs(plan.compute.settledMs+plan.compute.reservedMs)} of ${formatPlanMs(plan.compute.includedMs)}${plan.compute.reservedMs>0?` (${formatPlanMs(plan.compute.reservedMs)} reserved)`:""}`,"Cycle resets":String(plan.compute.resetsAt)}}__name(planFields,"planFields");function renderSchedule(command,schedule){ui.result({command,data:schedule,render:__name(()=>renderFields({ID:schedule.id,Name:schedule.name,Environment:schedule.env,Cron:schedule.cron,Command:schedule.command,Enabled:schedule.enabled?"yes":"no",Secrets:schedule.secretKeys.join(", ")||"none"}),"render")})}__name(renderSchedule,"renderSchedule");function renderScheduleList(command,data2){ui.result({command,data:data2,render:__name(()=>{let table=renderTable(["ID","NAME","CRON","COMMAND","ENABLED","LAST STATUS","POLICY"],data2.items.map(schedule=>[schedule.id,schedule.name,schedule.cron,schedule.command,schedule.enabled?"yes":"no",schedule.lastStatus??"",schedule.overPolicyReasons?.join(", ")??""])),note=planStateNote(data2.plan);return`${table}
1388
+
1389
+ ${renderFields(planFields(data2.plan))}${note?`
1390
+
1391
+ ${note}`:""}`},"render")})}__name(renderScheduleList,"renderScheduleList");function renderScheduleDetail(command,data2){ui.result({command,data:data2,render:__name(()=>{let note=planStateNote(data2.plan),overPolicyReasons=data2.schedule.overPolicyReasons??[];return`${renderFields({ID:data2.schedule.id,Name:data2.schedule.name,Environment:data2.schedule.env,Cron:data2.schedule.cron,Command:data2.schedule.command,Enabled:data2.schedule.enabled?"yes":"no",Secrets:data2.schedule.secretKeys.join(", ")||"none",...overPolicyReasons.length>0?{"Policy reasons":overPolicyReasons.join(", ")}:{},Runs:data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,...planFields(data2.plan)})}${note?`
1392
+
1393
+ ${note}`:""}
1394
+ `},"render")})}__name(renderScheduleDetail,"renderScheduleDetail");function renderRun(command,run){ui.result({command,data:run,render:__name(()=>renderFields({"Run ID":run.id,Schedule:run.scheduleName,Command:run.command,Status:run.status,Trigger:run.trigger,Queued:String(run.queuedAt)}),"render")})}__name(renderRun,"renderRun");function renderRuns(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderTable(["RUN ID","STATUS","TRIGGER","ACTOR","QUEUED","STARTED","FINISHED"],data2.items.map(run=>[run.id,run.status,run.trigger,run.triggeredBy?.name??"",String(run.queuedAt),run.startedAt?String(run.startedAt):"",run.finishedAt?String(run.finishedAt):""]))}
1385
1395
 
1386
1396
  ${renderFields({"Run count":data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,"Next cursor":data2.nextCursor??"none"})}`,"render")})}__name(renderRuns,"renderRuns");function renderRunDetail(command,run){ui.result({command,data:run,render:__name(()=>{let fields=renderFields({"Run ID":run.id,"Schedule ID":run.scheduleId,Schedule:run.scheduleName,Command:run.command,Environment:run.env,Status:run.status,Trigger:run.trigger,Actor:run.triggeredBy?.name??"",Queued:String(run.queuedAt),Started:run.startedAt?String(run.startedAt):"",Finished:run.finishedAt?String(run.finishedAt):"","Exit code":run.exitCode??"","Error code":run.errorCode??"",Error:run.error??"","Output bytes":run.outputBytes,"Output truncated":run.outputTruncated?"yes":"no","Output expires":run.outputExpiresAt?String(run.outputExpiresAt):"","Metadata expires":run.metadataExpiresAt?String(run.metadataExpiresAt):"","Secret snapshot":run.secretSnapshot.state,Secrets:run.secretSnapshot.items.map(item=>`${item.key} (${item.resolution})`).join(", ")||"none"});return run.output?`${fields}
1387
1397
 
@@ -1412,7 +1422,7 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
1412
1422
  `);addScopeOptions3(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions3(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand4(opts,command)),addScopeOptions3(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect2).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <main|all>","Deliver events from main or all environments","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand3(name,opts,command)),addScopeOptions3(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect2).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <main|all>","Deliver events from main or all environments").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand2(webhookId,opts,command)),addScopeOptions3(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand2(webhookId,opts,command)),addScopeOptions3(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions3(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions3(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope4(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope4,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope4("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand4(opts,command){let{api,projectId}=await resolveScope4("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand4,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand3(name,opts,command){let{api,projectId}=await resolveScope4("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand3,"createCommand");async function updateCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&&current.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand2,"updateCommand");async function deleteCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand2,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit2(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path49=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path49,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path49}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function parseLimit2(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit2,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
1413
1423
  `)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&&sections.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&&sections.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
1414
1424
  `).map(line=>` ${line}`).join(`
1415
- `)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("inventory").description("Inspect source-backed migration evidence and write the deterministic inventory").argument("[project-root]","Source-backed project directory").option("-C, --cwd <dir>","Source-backed project directory").option("--json","Output the inventory as JSON").option("--prepare","Prepare the deterministic inventory plan").option("--area <area>","Run one planned inventory area").option("--reconcile","Reconcile existing inventory fragments").option("--sequential","Run planned areas sequentially").action(migrateInventoryCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the generated migration toward the source site").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print regular Fimo CLI commands for importing reviewed migration artifacts").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Show preview URLs + deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
1425
+ `)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("inventory").description("Inspect source-backed migration evidence and write the deterministic inventory").argument("[project-root]","Source-backed project directory").option("-C, --cwd <dir>","Source-backed project directory").option("--json","Output the inventory as JSON").option("--prepare","Prepare the deterministic inventory plan").option("--area <area>","Run one planned inventory area").option("--reconcile","Reconcile existing inventory fragments").option("--sequential","Run planned areas sequentially").action(migrateInventoryCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the generated migration toward the source site").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print regular Fimo CLI commands for importing reviewed migration artifacts").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Show preview URLs + deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
1416
1426
  Supported agents:
1417
1427
  Universal (always covered via AGENTS.md, no per-agent file needed):
1418
1428
  Codex, OpenCode, Aider, and other AGENTS.md-native tools