@tryarcanist/cli 0.1.510 → 0.1.512

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 (2) hide show
  1. package/dist/index.js +25 -25
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __arcanistCreateRequire } from "node:module";
3
3
  const require = __arcanistCreateRequire(import.meta.url);
4
- var Wy=Object.defineProperty;var Be=(e,t)=>{for(var r in t)Wy(e,r,{get:t[r],enumerable:!0})};import{Command as DA,Option as zA}from"commander";var Zp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Pn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],Ky=new Set(Pn),BA=new Set(Pn.filter(e=>e!=="completed")),VA=Pn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Bp(e,t){return Ky.has(e)}function Vp(e){let t=e.createHelp().visibleGlobalOptions(e).map(qp);return{...Gp(e),...t.length>0?{globalOptions:t}:{}}}function Gp(e){let t=Jy(e);return{path:Ea(e),description:e.description(),aliases:e.aliases(),arguments:e.registeredArguments.map(r=>({name:r.name(),description:r.description,required:r.required,variadic:r.variadic})),options:e.createHelp().visibleOptions(e).map(qp),...t?{notes:t}:{},subcommands:e.commands.map(Gp)}}function qp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Ea(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function Jy(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Fb,mkdirSync as Zb,writeFileSync as Bb}from"node:fs";import{basename as Vb,join as pm,resolve as Gb}from"node:path";var Yy="en-US";function Hp(e,t){let r=new Intl.DateTimeFormat(Yy,{timeZone:t,month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0,timeZoneName:"short"}).formatToParts(e),o=n=>r.find(i=>i.type===n)?.value??"";return`${o("month")} ${o("day")}, ${o("year")}, ${o("hour")}:${o("minute")} ${o("dayPeriod")} ${o("timeZoneName")}`}function xe(e,t=""){return(e instanceof Error?e.message:String(e))||t}var KA=Date.parse("2026-09-26T15:00:00Z"),JA=60*1e3,YA=5*6e4;var XA=6*36e5;var QA=2*6e4,eP=5*6e4,tP=20*6e4,nP=5*6e4,rP=10*1e3,iP=60*1e3,oP=5*6e4;var aP=48*36e5,sP=6*36e5,uP=7*864e5,cP=5*6e4;var lP=168*36e5,dP=168*36e5,pP=30*1e3,mP=90*1e3;var fP=6*36e5,gP=30*6e4,Xy=15*6e4,Qy=90*6e4,vP=15*6e4,hP=Xy+2*Qy,_P=2*6e4,yP=40*1e3,bP=14*864e5,wP=30*864e5;var $P=30*6e4;var xP=15*6e4;var SP=10*1e3,IP=15*1e3;var kP=60*6e4,EP=5*6e4,TP=2*6e4;var AP=3*6e4,PP=10*6e4,RP=10*6e4,CP=24*36e5,OP=24*36e5,NP=2*6e4;function Gr(e){return new Promise(t=>setTimeout(t,e))}var eb=new Set([408,429,500,502,503,504]);function Wp(e,t){let r=t.includeDefaults!==!1&&eb.has(e)||t.includeServerErrors===!0&&e>=500;return t.remove?.includes(e)?!1:r||t.add?.includes(e)===!0}var tb=/\/+$/;function Je(e){return e.replace(tb,"")}var Kp="Setup and reviews are paused for this workspace. Contact team@tryarcanist.com to resume them.";function Jp(e){if(!e||typeof e!="object")return null;let t=e,r=typeof t.code=="string"&&t.code?t.code:null,o=typeof t.message=="string"&&t.message?t.message:null;if(typeof t.error=="string"&&t.error)return{code:r??t.error,message:o??t.error,raw:t.error};if(t.error&&typeof t.error=="object"){let n=t.error,i=typeof n.code=="string"&&n.code?n.code:r,a=typeof n.message=="string"&&n.message?n.message:o;return i||a?{code:i,message:a,raw:t.error}:null}return r||o?{code:r,message:o,raw:e}:null}function Ta(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=t,o={...typeof r.repository=="string"?{repository:r.repository}:{},...typeof r.environmentsUrl=="string"?{environmentsUrl:r.environmentsUrl}:{},...typeof r.billingUrl=="string"?{billingUrl:r.billingUrl}:{}},n=Jp(t);return n?typeof n.raw=="string"&&n.raw?{...n.code?{serverCode:n.code}:{},rawError:n.raw,...n.message?{message:n.message}:{},...o}:n.message||n.code?{...n.message?{message:n.message}:{},...n.code?{serverCode:n.code,rawError:n.code}:{},...o}:null:null}catch{return null}}var nb=/^error: /,rb=/^\((.*)\)$/,vt=130,Aa=5,y=class extends Error{code;exitCode;hint;requestId;data;constructor(t,r,o={}){super(r),this.name="CliError",this.code=t,this.exitCode=o.exitCode??Yp(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},gt=class extends y{},ae=class extends y{status;body;constructor(t,r,o,n){let i=Xp(t),a=Ta(r);super(i,ob(t,r,a),{exitCode:ib(t),hint:ab(t,a,n),requestId:o,data:a?.serverCode||a?.repository||a?.environmentsUrl||a?.billingUrl?{...a.serverCode?{serverCode:a.serverCode}:{},...a.repository?{repository:a.repository}:{},...a.environmentsUrl?{environmentsUrl:a.environmentsUrl}:{},...a.billingUrl?{billingUrl:a.billingUrl}:{}}:void 0}),this.name="ApiError",this.status=t,this.body=r}};function Yp(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function Xp(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function ib(e){return Yp(Xp(e))}function ob(e,t,r=Ta(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function ab(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&t?.message===Kp)){if(e===403&&t?.serverCode==="github_not_connected")return"This user has not connected GitHub. Open `/auth/github/connect` on the Arcanist app and approve, then retry. `arcanist onboard <owner/repo>` prints that link.";if(e===403)return"This token is not allowed to do that. `arcanist auth whoami --json` shows its tokenScope and your businessRole: a change needs a write-scope token (mint one in Settings > CLI), and a workspace-wide change also needs the admin role.";if(e===404)return r==="repo"?"Check accessible repositories with `arcanist repos list`.":r==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&t?.repository){if(t.serverCode==="environment_required")return`Run \`arcanist environments prepare ${t.repository} --wait\`, then retry the review.`;if(t.serverCode==="environment_preparing"||t.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${t.repository} --wait\` for the latest setup state.`}if(e===409)return"Check the current resource state and retry the command when it is ready.";if(e>=500)return"Retry later or check the control-plane logs."}}var sb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function ub(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(nb,"").split(`
5
- `);return new y("user",t,{hint:r?r.replace(rb,"$1"):sb})}function Qp(e){if(e instanceof y)return e;if(e instanceof Error){let t=ub(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function qr(e){return JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{},...e.requestId?{requestId:e.requestId}:{},...e.data?{data:e.data}:{}}})}var em={name:"@tryarcanist/cli",version:"0.1.510",description:"Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",type:"module",bin:{arcanist:"dist/index.js"},engines:{node:">=22"},files:["dist/index.js"],scripts:{build:"tsup",typecheck:"node ../../node_modules/tsrs/bin/tsrs --noEmit",prepublishOnly:"npm --prefix ../.. run guard:cli-bundle"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/tryarcanist/arcanist.git",directory:"apps/cli"},homepage:"https://www.tryarcanist.com",license:"MIT",dependencies:{commander:"^12.1.0","eventsource-parser":"3.1.1","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var Ye=`${em.version}`;var lb=/^\d+$/,db=`arcanist-cli/${Ye}`,pb=3e4,mb=1e3,fb=6e5,Hr="ARCANIST_HTTP_TIMEOUT_MS";function gb(e=process.env){let t=e[Hr];if(!t)return pb;if(!lb.test(t))throw new y("user",`${Hr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<mb||r>fb)throw new y("user",`${Hr} must be between 1000 and 600000 milliseconds.`);return r}function Pa(e){return e instanceof DOMException&&e.name==="AbortError"}function vb(e){let t=e instanceof Error?e.cause:null;return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:null}function Ra(e){return new gt("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Hr} for slow links, or check the API connection.`})}function hb(e){let t=gb();if(!e)return{fetchInit:void 0,timeoutMs:t};let{timeoutMs:r,...o}=e;return r===void 0?{fetchInit:o,timeoutMs:t}:!Number.isFinite(r)||r<=0?{fetchInit:o,timeoutMs:1}:{fetchInit:o,timeoutMs:Math.max(1,Math.min(t,r))}}async function Ca(e,t,r,o){let{fetchInit:n,timeoutMs:i}=hb(r),a=new AbortController,s=setTimeout(()=>a.abort(),i);try{let u=new Headers(n?.headers);u.set("Content-Type","application/json"),u.set("User-Agent",db),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${Je(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw Pa(l)?Ra(i):new gt("server",`Network error: could not reach ${Je(e.apiUrl)} (${vb(l)??xe(l)}).`,{hint:"Check the network and `ARCANIST_API_URL` or `--api-url`, then retry."})});if(!c.ok){let l=await c.text().catch(d=>{if(Pa(d))throw Ra(i);return""});throw new ae(c.status,l,c.headers.get("x-request-id")??void 0,_b(t))}return await o(c)}catch(u){throw u instanceof y?u:Pa(u)?Ra(i):u instanceof TypeError?new gt("server",`The API response could not be read: ${xe(u)}`):new y("server",`The API response could not be read: ${xe(u)}`)}finally{clearTimeout(s)}}function _b(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function R(e,t,r){return Ca(e,t,r,o=>o.json())}async function tm(e,t,r){return Ca(e,t,r,o=>o.text())}async function nm(e,t,r){return Ca(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}function rm(e){return e instanceof gt||e instanceof ae&&Wp(e.status,{includeServerErrors:!0})}var yb=/:([A-Za-z]+)/g,M={getInferenceApiKeys:{method:"GET",pattern:"/api/inference/keys"},createInferenceApiKey:{method:"POST",pattern:"/api/inference/keys"},revokeInferenceApiKey:{method:"DELETE",pattern:"/api/inference/keys/:keyId"},getInferenceProviders:{method:"GET",pattern:"/api/inference/providers"},setInferenceKey:{method:"PUT",pattern:"/api/inference/providers/:provider/key"},removeInferenceKey:{method:"DELETE",pattern:"/api/inference/providers/:provider/key"},setInferenceFallback:{method:"PATCH",pattern:"/api/inference/providers/:provider"},getInferenceWorkflows:{method:"GET",pattern:"/api/inference/workflows"},getInferenceWorkflowUsage:{method:"GET",pattern:"/api/inference/workflows/usage"},getInferenceTraces:{method:"GET",pattern:"/api/inference/traces"},getInferenceTrace:{method:"GET",pattern:"/api/inference/traces/:traceId"},getInferenceTraceBody:{method:"GET",pattern:"/api/inference/traces/:traceId/calls/:callId"},getInferenceUsage:{method:"GET",pattern:"/api/inference/usage"},getCurrentUser:{method:"GET",pattern:"/api/auth/whoami"},exchangeCliLogin:{method:"POST",pattern:"/api/cli-login/exchange"},getGithubInstallation:{method:"GET",pattern:"/api/onboarding/github-installation"},answerOnboardingQuestion:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/question"},listRepositories:{method:"GET",pattern:"/api/repos"},listSessions:{method:"GET",pattern:"/api/sessions"},getSession:{method:"GET",pattern:"/api/sessions/:sessionId"},getSessionView:{method:"GET",pattern:"/api/sessions/:sessionId/view"},getSessionPrompts:{method:"GET",pattern:"/api/sessions/:sessionId/prompts"},getSessionEvents:{method:"GET",pattern:"/api/sessions/:sessionId/events"},getSessionEventHistory:{method:"GET",pattern:"/api/sessions/:sessionId/events/history"},exportSession:{method:"GET",pattern:"/api/sessions/:sessionId/export"},listSessionArtifacts:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/list"},viewSessionArtifact:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/:artifactId/view"},createReview:{method:"POST",pattern:"/api/pr-reviews"},getReviewRequest:{method:"GET",pattern:"/api/pr-reviews/requests/:requestId"},getReviewRequestStatuses:{method:"POST",pattern:"/api/pr-reviews/requests/status-batch"},createLocalReview:{method:"POST",pattern:"/api/local-reviews"},getLocalReview:{method:"GET",pattern:"/api/local-reviews/:requestId"},getRepositoryOnboarding:{method:"GET",pattern:"/api/settings/repositories/onboarding"},prepareRepository:{method:"POST",pattern:"/api/settings/repositories/onboarding"},retryRepositoryOnboarding:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/retry"},getSettingsBusinessReviewDefault:{method:"GET",pattern:"/api/settings/business/review-default"},putSettingsBusinessReviewDefault:{method:"PUT",pattern:"/api/settings/business/review-default"},listEnvironments:{method:"GET",pattern:"/api/environments"},getEnvironment:{method:"GET",pattern:"/api/environments/:id"},updateEnvironment:{method:"PUT",pattern:"/api/environments/:id"},getEnvironmentMockDependencies:{method:"GET",pattern:"/api/environments/:id/mock-dependencies"},updateEnvironmentMockDependency:{method:"PUT",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},deleteEnvironmentMockDependency:{method:"DELETE",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},createEnvironment:{method:"POST",pattern:"/api/environments"}};function P(e,t={}){return im(e,t)}function im(e,t){return e.replace(yb,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var cR=[{...M.getInferenceApiKeys,command:"inference keys list"},{...M.createInferenceApiKey,command:"inference keys create"},{...M.revokeInferenceApiKey,command:"inference keys revoke"},{...M.getInferenceProviders,command:"inference providers list"},{...M.setInferenceKey,command:"inference providers set-key"},{...M.removeInferenceKey,command:"inference providers remove-key"},{...M.setInferenceFallback,command:"inference providers fallback"},{...M.getInferenceUsage,command:"inference usage"},{...M.getCurrentUser,command:"auth whoami"},{...M.exchangeCliLogin,command:"auth login",public:!0},{...M.getGithubInstallation,command:"onboard"},{...M.getSettingsBusinessReviewDefault,command:"onboard"},{...M.putSettingsBusinessReviewDefault,command:"onboard --automatic-review"},{...M.answerOnboardingQuestion,command:"environments answer"},{...M.listRepositories,command:"repos list"},{...M.listSessions,command:"sessions list"},{...M.getSession,command:"sessions get"},{...M.getSessionView,command:"sessions view"},{...M.getSessionPrompts,command:"sessions events --follow"},{...M.getSessionEvents,command:"sessions events --follow"},{...M.getSessionEventHistory,command:"sessions events"},{...M.exportSession,command:"sessions transcript"},{...M.listSessionArtifacts,command:"sessions artifacts"},{...M.viewSessionArtifact,command:"sessions artifacts get"},{...M.createReview,command:"review <pr-url>"},{...M.getReviewRequest,command:"review <pr-url>"},{...M.getReviewRequest,command:"reviews get"},{...M.getReviewRequestStatuses,command:"reviews get"},{...M.createLocalReview,command:"review"},{...M.getLocalReview,command:"review --request"},{...M.getRepositoryOnboarding,command:"environments status"},{...M.prepareRepository,command:"environments prepare"},{...M.retryRepositoryOnboarding,command:"environments retry"},{...M.listEnvironments,command:"environments export"},{...M.getEnvironment,command:"environments export"},{...M.listEnvironments,command:"environments import"},{...M.getEnvironment,command:"environments import"},{...M.updateEnvironment,command:"environments import"},{...M.createEnvironment,command:"environments import --create"}];import{createHash as am}from"node:crypto";import{existsSync as Rn,mkdirSync as Sb,readFileSync as Oa,statSync as Ib}from"node:fs";import{homedir as kb}from"node:os";import{dirname as sm,join as _t,resolve as Eb}from"node:path";import{randomUUID as bb}from"node:crypto";import{renameSync as wb,rmSync as $b,writeFileSync as xb}from"node:fs";function ht(e,t){let r=`${e}.${bb()}.tmp`;try{xb(r,JSON.stringify(t,null,2)+`
6
- `,{mode:384,flag:"wx"}),wb(r,e)}finally{$b(r,{force:!0})}}var Tb=/\r?\n/,Ab=/^\[|\]$/g,um=_t(kb(),".arcanist"),cm=_t(um,"config.json"),Xe=".arcanist-cli.json",Pb="https://app.tryarcanist.com";function Na(){try{return JSON.parse(Oa(cm,"utf-8"))}catch{return null}}function Cn(e={}){let t=Rb(e);if(t)return om(t);let r=Da(),o=za(e,r!==null),n=Na(),i=o?.apiUrl??r?.apiUrl??n?.apiUrl,a=r&&n?.apiUrl===r.apiUrl&&n.token&&n.supersededProjectTokenHash===am("sha256").update(r.token).digest("hex")?n.token:r?.token,s=o?.token??a??n?.token;if(!i||!s)return null;let u=om({apiUrl:i,token:s});return r&&!o&&!e.json&&process.stderr.write(`using ${Xe} -> ${u.apiUrl}
4
+ var Wy=Object.defineProperty;var Be=(e,t)=>{for(var r in t)Wy(e,r,{get:t[r],enumerable:!0})};import{Command as zA,Option as UA}from"commander";var Zp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Pn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],Ky=new Set(Pn),VA=new Set(Pn.filter(e=>e!=="completed")),GA=Pn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Bp(e,t){return Ky.has(e)}function Vp(e){let t=e.createHelp().visibleGlobalOptions(e).map(qp);return{...Gp(e),...t.length>0?{globalOptions:t}:{}}}function Gp(e){let t=Jy(e);return{path:Ea(e),description:e.description(),aliases:e.aliases(),arguments:e.registeredArguments.map(r=>({name:r.name(),description:r.description,required:r.required,variadic:r.variadic})),options:e.createHelp().visibleOptions(e).map(qp),...t?{notes:t}:{},subcommands:e.commands.map(Gp)}}function qp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Ea(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function Jy(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Fb,mkdirSync as Zb,writeFileSync as Bb}from"node:fs";import{basename as Vb,join as pm,resolve as Gb}from"node:path";var Yy="en-US";function Hp(e,t){let r=new Intl.DateTimeFormat(Yy,{timeZone:t,month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0,timeZoneName:"short"}).formatToParts(e),o=n=>r.find(i=>i.type===n)?.value??"";return`${o("month")} ${o("day")}, ${o("year")}, ${o("hour")}:${o("minute")} ${o("dayPeriod")} ${o("timeZoneName")}`}function xe(e,t=""){return(e instanceof Error?e.message:String(e))||t}var JA=Date.parse("2026-09-26T15:00:00Z"),YA=60*1e3,XA=5*6e4;var QA=6*36e5;var eP=2*6e4,tP=5*6e4,nP=20*6e4,rP=5*6e4,iP=10*1e3,oP=60*1e3,aP=5*6e4;var sP=48*36e5,uP=6*36e5,cP=7*864e5,lP=5*6e4;var dP=168*36e5,pP=168*36e5,mP=30*1e3,fP=90*1e3;var gP=6*36e5,vP=30*6e4,Xy=15*6e4,Qy=90*6e4,hP=15*6e4,_P=Xy+2*Qy,yP=2*6e4,bP=40*1e3,wP=14*864e5,$P=30*864e5;var xP=30*6e4;var SP=15*6e4;var IP=10*1e3,kP=15*1e3;var EP=60*6e4,TP=5*6e4,AP=2*6e4;var PP=3*6e4,RP=10*6e4,CP=10*6e4,OP=24*36e5,NP=24*36e5,DP=2*6e4;function Gr(e){return new Promise(t=>setTimeout(t,e))}var eb=new Set([408,429,500,502,503,504]);function Wp(e,t){let r=t.includeDefaults!==!1&&eb.has(e)||t.includeServerErrors===!0&&e>=500;return t.remove?.includes(e)?!1:r||t.add?.includes(e)===!0}var tb=/\/+$/;function Je(e){return e.replace(tb,"")}var Kp="Setup and reviews are paused for this workspace. Contact team@tryarcanist.com to resume them.";function Jp(e){if(!e||typeof e!="object")return null;let t=e,r=typeof t.code=="string"&&t.code?t.code:null,o=typeof t.message=="string"&&t.message?t.message:null;if(typeof t.error=="string"&&t.error)return{code:r??t.error,message:o??t.error,raw:t.error};if(t.error&&typeof t.error=="object"){let n=t.error,i=typeof n.code=="string"&&n.code?n.code:r,a=typeof n.message=="string"&&n.message?n.message:o;return i||a?{code:i,message:a,raw:t.error}:null}return r||o?{code:r,message:o,raw:e}:null}function Ta(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=t,o={...typeof r.repository=="string"?{repository:r.repository}:{},...typeof r.environmentsUrl=="string"?{environmentsUrl:r.environmentsUrl}:{},...typeof r.billingUrl=="string"?{billingUrl:r.billingUrl}:{}},n=Jp(t);return n?typeof n.raw=="string"&&n.raw?{...n.code?{serverCode:n.code}:{},rawError:n.raw,...n.message?{message:n.message}:{},...o}:n.message||n.code?{...n.message?{message:n.message}:{},...n.code?{serverCode:n.code,rawError:n.code}:{},...o}:null:null}catch{return null}}var nb=/^error: /,rb=/^\((.*)\)$/,vt=130,Aa=5,y=class extends Error{code;exitCode;hint;requestId;data;constructor(t,r,o={}){super(r),this.name="CliError",this.code=t,this.exitCode=o.exitCode??Yp(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},gt=class extends y{},ae=class extends y{status;body;constructor(t,r,o,n){let i=Xp(t),a=Ta(r);super(i,ob(t,r,a),{exitCode:ib(t),hint:ab(t,a,n),requestId:o,data:a?.serverCode||a?.repository||a?.environmentsUrl||a?.billingUrl?{...a.serverCode?{serverCode:a.serverCode}:{},...a.repository?{repository:a.repository}:{},...a.environmentsUrl?{environmentsUrl:a.environmentsUrl}:{},...a.billingUrl?{billingUrl:a.billingUrl}:{}}:void 0}),this.name="ApiError",this.status=t,this.body=r}};function Yp(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function Xp(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function ib(e){return Yp(Xp(e))}function ob(e,t,r=Ta(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function ab(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&t?.message===Kp)){if(e===403&&t?.serverCode==="github_not_connected")return"This user has not connected GitHub. Open `/auth/github/connect` on the Arcanist app and approve, then retry. `arcanist onboard <owner/repo>` prints that link.";if(e===403)return"This token is not allowed to do that. `arcanist auth whoami --json` shows its tokenScope and your businessRole: a change needs a write-scope token (mint one in Settings > CLI), and a workspace-wide change also needs the admin role.";if(e===404)return r==="repo"?"Check accessible repositories with `arcanist repos list`.":r==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&t?.repository){if(t.serverCode==="environment_required")return`Run \`arcanist environments prepare ${t.repository} --wait\`, then retry the review.`;if(t.serverCode==="environment_preparing"||t.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${t.repository} --wait\` for the latest setup state.`}if(e===409)return"Check the current resource state and retry the command when it is ready.";if(e>=500)return"Retry later or check the control-plane logs."}}var sb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function ub(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(nb,"").split(`
5
+ `);return new y("user",t,{hint:r?r.replace(rb,"$1"):sb})}function Qp(e){if(e instanceof y)return e;if(e instanceof Error){let t=ub(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function qr(e){return JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{},...e.requestId?{requestId:e.requestId}:{},...e.data?{data:e.data}:{}}})}var em={name:"@tryarcanist/cli",version:"0.1.512",description:"Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",type:"module",bin:{arcanist:"dist/index.js"},engines:{node:">=22"},files:["dist/index.js"],scripts:{build:"tsup",typecheck:"node ../../node_modules/tsrs/bin/tsrs --noEmit",prepublishOnly:"npm --prefix ../.. run guard:cli-bundle"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/tryarcanist/arcanist.git",directory:"apps/cli"},homepage:"https://www.tryarcanist.com",license:"MIT",dependencies:{commander:"^12.1.0","eventsource-parser":"3.1.1","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var Ye=`${em.version}`;var lb=/^\d+$/,db=`arcanist-cli/${Ye}`,pb=3e4,mb=1e3,fb=6e5,Hr="ARCANIST_HTTP_TIMEOUT_MS";function gb(e=process.env){let t=e[Hr];if(!t)return pb;if(!lb.test(t))throw new y("user",`${Hr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<mb||r>fb)throw new y("user",`${Hr} must be between 1000 and 600000 milliseconds.`);return r}function Pa(e){return e instanceof DOMException&&e.name==="AbortError"}function vb(e){let t=e instanceof Error?e.cause:null;return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:null}function Ra(e){return new gt("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Hr} for slow links, or check the API connection.`})}function hb(e){let t=gb();if(!e)return{fetchInit:void 0,timeoutMs:t};let{timeoutMs:r,...o}=e;return r===void 0?{fetchInit:o,timeoutMs:t}:!Number.isFinite(r)||r<=0?{fetchInit:o,timeoutMs:1}:{fetchInit:o,timeoutMs:Math.max(1,Math.min(t,r))}}async function Ca(e,t,r,o){let{fetchInit:n,timeoutMs:i}=hb(r),a=new AbortController,s=setTimeout(()=>a.abort(),i);try{let u=new Headers(n?.headers);u.set("Content-Type","application/json"),u.set("User-Agent",db),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${Je(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw Pa(l)?Ra(i):new gt("server",`Network error: could not reach ${Je(e.apiUrl)} (${vb(l)??xe(l)}).`,{hint:"Check the network and `ARCANIST_API_URL` or `--api-url`, then retry."})});if(!c.ok){let l=await c.text().catch(d=>{if(Pa(d))throw Ra(i);return""});throw new ae(c.status,l,c.headers.get("x-request-id")??void 0,_b(t))}return await o(c)}catch(u){throw u instanceof y?u:Pa(u)?Ra(i):u instanceof TypeError?new gt("server",`The API response could not be read: ${xe(u)}`):new y("server",`The API response could not be read: ${xe(u)}`)}finally{clearTimeout(s)}}function _b(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function R(e,t,r){return Ca(e,t,r,o=>o.json())}async function tm(e,t,r){return Ca(e,t,r,o=>o.text())}async function nm(e,t,r){return Ca(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}function rm(e){return e instanceof gt||e instanceof ae&&Wp(e.status,{includeServerErrors:!0})}var yb=/:([A-Za-z]+)/g,M={getInferenceApiKeys:{method:"GET",pattern:"/api/inference/keys"},createInferenceApiKey:{method:"POST",pattern:"/api/inference/keys"},revokeInferenceApiKey:{method:"DELETE",pattern:"/api/inference/keys/:keyId"},getInferenceProviders:{method:"GET",pattern:"/api/inference/providers"},setInferenceKey:{method:"PUT",pattern:"/api/inference/providers/:provider/key"},removeInferenceKey:{method:"DELETE",pattern:"/api/inference/providers/:provider/key"},setInferenceFallback:{method:"PATCH",pattern:"/api/inference/providers/:provider"},getInferenceWorkflows:{method:"GET",pattern:"/api/inference/workflows"},getInferenceWorkflowUsage:{method:"GET",pattern:"/api/inference/workflows/usage"},getInferenceTraces:{method:"GET",pattern:"/api/inference/traces"},getInferenceTrace:{method:"GET",pattern:"/api/inference/traces/:traceId"},getInferenceTraceBody:{method:"GET",pattern:"/api/inference/traces/:traceId/calls/:callId"},getInferenceUsage:{method:"GET",pattern:"/api/inference/usage"},getCurrentUser:{method:"GET",pattern:"/api/auth/whoami"},exchangeCliLogin:{method:"POST",pattern:"/api/cli-login/exchange"},getGithubInstallation:{method:"GET",pattern:"/api/onboarding/github-installation"},answerOnboardingQuestion:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/question"},listRepositories:{method:"GET",pattern:"/api/repos"},listSessions:{method:"GET",pattern:"/api/sessions"},getSession:{method:"GET",pattern:"/api/sessions/:sessionId"},getSessionView:{method:"GET",pattern:"/api/sessions/:sessionId/view"},getSessionPrompts:{method:"GET",pattern:"/api/sessions/:sessionId/prompts"},getSessionEvents:{method:"GET",pattern:"/api/sessions/:sessionId/events"},getSessionEventHistory:{method:"GET",pattern:"/api/sessions/:sessionId/events/history"},exportSession:{method:"GET",pattern:"/api/sessions/:sessionId/export"},listSessionArtifacts:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/list"},viewSessionArtifact:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/:artifactId/view"},createReview:{method:"POST",pattern:"/api/pr-reviews"},getReviewRequest:{method:"GET",pattern:"/api/pr-reviews/requests/:requestId"},getReviewRequestStatuses:{method:"POST",pattern:"/api/pr-reviews/requests/status-batch"},createLocalReview:{method:"POST",pattern:"/api/local-reviews"},getLocalReview:{method:"GET",pattern:"/api/local-reviews/:requestId"},getRepositoryOnboarding:{method:"GET",pattern:"/api/settings/repositories/onboarding"},prepareRepository:{method:"POST",pattern:"/api/settings/repositories/onboarding"},retryRepositoryOnboarding:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/retry"},getSettingsBusinessReviewDefault:{method:"GET",pattern:"/api/settings/business/review-default"},putSettingsBusinessReviewDefault:{method:"PUT",pattern:"/api/settings/business/review-default"},listEnvironments:{method:"GET",pattern:"/api/environments"},getEnvironment:{method:"GET",pattern:"/api/environments/:id"},updateEnvironment:{method:"PUT",pattern:"/api/environments/:id"},getEnvironmentMockDependencies:{method:"GET",pattern:"/api/environments/:id/mock-dependencies"},updateEnvironmentMockDependency:{method:"PUT",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},deleteEnvironmentMockDependency:{method:"DELETE",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},createEnvironment:{method:"POST",pattern:"/api/environments"}};function P(e,t={}){return im(e,t)}function im(e,t){return e.replace(yb,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var lR=[{...M.getInferenceApiKeys,command:"inference keys list"},{...M.createInferenceApiKey,command:"inference keys create"},{...M.revokeInferenceApiKey,command:"inference keys revoke"},{...M.getInferenceProviders,command:"inference providers list"},{...M.setInferenceKey,command:"inference providers set-key"},{...M.removeInferenceKey,command:"inference providers remove-key"},{...M.setInferenceFallback,command:"inference providers fallback"},{...M.getInferenceUsage,command:"inference usage"},{...M.getCurrentUser,command:"auth whoami"},{...M.exchangeCliLogin,command:"auth login",public:!0},{...M.getGithubInstallation,command:"onboard"},{...M.getSettingsBusinessReviewDefault,command:"onboard"},{...M.putSettingsBusinessReviewDefault,command:"onboard --automatic-review"},{...M.answerOnboardingQuestion,command:"environments answer"},{...M.listRepositories,command:"repos list"},{...M.listSessions,command:"sessions list"},{...M.getSession,command:"sessions get"},{...M.getSessionView,command:"sessions view"},{...M.getSessionPrompts,command:"sessions events --follow"},{...M.getSessionEvents,command:"sessions events --follow"},{...M.getSessionEventHistory,command:"sessions events"},{...M.exportSession,command:"sessions transcript"},{...M.listSessionArtifacts,command:"sessions artifacts"},{...M.viewSessionArtifact,command:"sessions artifacts get"},{...M.createReview,command:"review <pr-url>"},{...M.getReviewRequest,command:"review <pr-url>"},{...M.getReviewRequest,command:"reviews get"},{...M.getReviewRequestStatuses,command:"reviews get"},{...M.createLocalReview,command:"review"},{...M.getLocalReview,command:"review --request"},{...M.getRepositoryOnboarding,command:"environments status"},{...M.prepareRepository,command:"environments prepare"},{...M.retryRepositoryOnboarding,command:"environments retry"},{...M.listEnvironments,command:"environments export"},{...M.getEnvironment,command:"environments export"},{...M.listEnvironments,command:"environments import"},{...M.getEnvironment,command:"environments import"},{...M.updateEnvironment,command:"environments import"},{...M.createEnvironment,command:"environments import --create"}];import{createHash as am}from"node:crypto";import{existsSync as Rn,mkdirSync as Sb,readFileSync as Oa,statSync as Ib}from"node:fs";import{homedir as kb}from"node:os";import{dirname as sm,join as _t,resolve as Eb}from"node:path";import{randomUUID as bb}from"node:crypto";import{renameSync as wb,rmSync as $b,writeFileSync as xb}from"node:fs";function ht(e,t){let r=`${e}.${bb()}.tmp`;try{xb(r,JSON.stringify(t,null,2)+`
6
+ `,{mode:384,flag:"wx"}),wb(r,e)}finally{$b(r,{force:!0})}}var Tb=/\r?\n/,Ab=/^\[|\]$/g,um=_t(kb(),".arcanist"),cm=_t(um,"config.json"),Xe=".arcanist-cli.json",Pb="https://app.tryarcanist.com";function Na(){try{return JSON.parse(Oa(cm,"utf-8"))}catch{return null}}function Cn(e){let t=Rb(e);if(t)return om(t);let r=Da(),o=za(e,r!==null),n=Na(),i=o?.apiUrl??r?.apiUrl??n?.apiUrl,a=r&&n?.apiUrl===r.apiUrl&&n.token&&n.supersededProjectTokenHash===am("sha256").update(r.token).digest("hex")?n.token:r?.token,s=o?.token??a??n?.token;if(!i||!s)return null;let u=om({apiUrl:i,token:s});return r&&!o&&!e.json&&process.stderr.write(`using ${Xe} -> ${u.apiUrl}
7
7
  `),u}function Wr(e,t){let r=Jr(e.apiUrl);if(r)throw new y("user",r);Sb(um,{recursive:!0,mode:448});let o=Je(e.apiUrl),n=Na(),i=t?am("sha256").update(t).digest("hex"):n?.apiUrl===o?n.supersededProjectTokenHash:void 0,a={...e,apiUrl:o,...i?{supersededProjectTokenHash:i}:{}};ht(cm,a)}function he(e){let t=Cn(e);if(!t)throw new y("auth","Not logged in.",{hint:"Run `arcanist auth login` or set `ARCANIST_TOKEN`."});return t}function Kr(e){let t=e??process.env.ARCANIST_API_URL??Na()?.apiUrl??Pb,r=Jr(t);if(r)throw new y("user",r);return Je(t)}function Da(e=process.cwd()){let t=Cb(e);if(!t)return null;let r=e;for(;;){let o=_t(r,Xe);if(Rn(o))return Db(o);if(r===t)return null;let n=sm(r);if(n===r)return null;r=n}}function Jr(e){let t;try{t=new URL(e)}catch{return"Invalid URL format"}return t.username||t.password?"API URL must not include embedded credentials. Use --token or ARCANIST_TOKEN to authenticate.":t.protocol!=="https:"&&!lm(t)?"API URL must use HTTPS for non-local hosts":null}function za(e,t){let r=e.apiUrl??process.env.ARCANIST_API_URL,o=e.token??process.env.ARCANIST_TOKEN;if(!t)return!r&&!o?null:{apiUrl:r,token:o};if(r&&!o||!r&&o)throw new y("user",`${Xe} is active; set both ARCANIST_API_URL and ARCANIST_TOKEN, pass both --api-url and --token, or set neither.`);return!r||!o?null:{apiUrl:r,token:o}}function Rb(e){let t=e.apiUrl??process.env.ARCANIST_API_URL,r=e.token??process.env.ARCANIST_TOKEN;return!t||!r?null:{apiUrl:t,token:r}}function om(e){let t=Jr(e.apiUrl);if(t)throw new y("user",t);return{apiUrl:Je(e.apiUrl),token:e.token}}function Cb(e){let t=e;for(;;){if(Ob(t))return t;let r=sm(t);if(r===t)return null;t=r}}function Ob(e){let t=_t(e,".git");if(!Rn(t))return!1;try{let r=Ib(t);if(r.isDirectory())return Rn(_t(t,"HEAD"))&&Rn(_t(t,"config"));if(!r.isFile())return!1;let o=Nb(t);return o?Rn(_t(Eb(e,o),"HEAD")):!1}catch{return!1}}function Nb(e){let t=Oa(e,"utf-8").split(Tb).find(o=>o.startsWith("gitdir:"));return t&&t.slice(7).trim()||null}function Db(e){let t;try{t=JSON.parse(Oa(e,"utf-8"))}catch{throw new y("user",`${Xe} is not valid JSON.`)}if(!t||typeof t!="object")throw new y("user",`${Xe} must contain both apiUrl and token.`);let r=t;if(typeof r.apiUrl!="string"||typeof r.token!="string"||!r.apiUrl||!r.token)throw new y("user",`${Xe} must contain both apiUrl and token.`);let o;try{o=new URL(r.apiUrl)}catch{throw new y("user",`${Xe} apiUrl must be a valid URL.`)}if(!lm(o))throw new y("user",`${Xe} apiUrl must be a loopback host.`);let n=Jr(r.apiUrl);if(n)throw new y("user",n);return{apiUrl:Je(r.apiUrl),token:r.token}}function lm(e){let t=e.hostname.replace(Ab,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function ee(e,t={}){let o={...e?.optsWithGlobals?.(),...t};return{...o,noColor:o.noColor===!0||o.color===!1}}function Se(e,t={}){return ee(e,t).json===!0}function Ve(e){process.stdout.write(`${JSON.stringify(e)}
8
- `)}function D(e,t,r,o){if(Se(e,t)){Ve(r);return}o(r)}function Y(e,t={}){let r=ee(e,t);return{runtime:r,config:he(r)}}async function zb(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString()}async function jt(){return(await zb()).trim()}function dm(e){(e.noColor===!0||!process.stdout.isTTY)&&(process.env.NO_COLOR="1")}var Ub=/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,Lb=/\u001b\[[0-?]*[ -\/]*[@-~]/g,jb=/[\u0000-\u001f\u007f]/g,Mb=/\r?\n/;function F(e){return e.replace(Ub,"").replace(Lb,"").replace(jb,"")}function Oe(e){return e.split(Mb).map(F).join(`
8
+ `)}function D(e,t,r,o){if(Se(e,t)){Ve(r);return}o(r)}function Y(e,t){let r=ee(e,t);return{runtime:r,config:he(r)}}async function zb(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString()}async function jt(){return(await zb()).trim()}function dm(e){(e.noColor===!0||!process.stdout.isTTY)&&(process.env.NO_COLOR="1")}var Ub=/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,Lb=/\u001b\[[0-?]*[ -\/]*[@-~]/g,jb=/[\u0000-\u001f\u007f]/g,Mb=/\r?\n/;function F(e){return e.replace(Ub,"").replace(Lb,"").replace(jb,"")}function Oe(e){return e.split(Mb).map(F).join(`
9
9
  `)}async function mm(e,t){return(await R(e,P("/api/sessions/:sessionId/artifacts/list",{sessionId:t}))).artifacts??[]}function fm(e){let t=e.metadata?.filename,r=t?F(Vb(t)):"";return r&&r!=="."&&r!==".."?r:`${F(e.type)}-${e.artifactId}`}async function gm(e,t,r,o,n){let i=fm(r),s=n.has(i)||Fb(pm(o,i))?`${r.artifactId}-${i}`:i;n.add(s);let u=await nm(e,`${P("/api/sessions/:sessionId/artifacts/:artifactId/view",{sessionId:t,artifactId:r.artifactId})}?filename=${encodeURIComponent(i)}`),c=pm(o,s);return Bb(c,u),c}function vm(e){let t=Gb(e??process.cwd());return Zb(t,{recursive:!0}),t}async function hm(e,t,r){let o=ee(r,t),n=he(o),i=await mm(n,e);if(t.all){await qb(n,e,i,t,r);return}D(r,t,{artifacts:i},a=>{if(a.artifacts.length===0){console.log(`No artifacts for session ${e}.`);return}console.log(["ARTIFACT ID","KIND","LABEL","FILENAME","BYTES","CREATED AT"].join(" "));for(let s of a.artifacts)console.log([s.artifactId,F(s.type),F(s.metadata?.label??"-"),fm(s),s.metadata?.bytes??"-",Hp(s.createdAt)].join(" "))})}async function qb(e,t,r,o,n){if(r.length===0){D(n,o,{downloaded:[]},()=>{console.log(`No artifacts for session ${t}.`)});return}let i=vm(o.output),a=new Set,s=[];for(let u of r){let c=await gm(e,t,u,i,a);s.push({artifactId:u.artifactId,path:c})}D(n,o,{downloaded:s},u=>{for(let c of u.downloaded)console.log(c.path)})}async function _m(e,t,r,o){let n=ee(o,r),i=he(n),s=(await mm(i,e)).find(l=>l.artifactId===t);if(!s)throw new y("user",`Artifact ${t} not found in session ${e}.`,{hint:`Run \`arcanist sessions artifacts ${e}\` to list the artifact IDs for this session.`});let u=vm(r.output),c=await gm(i,e,s,u,new Set);D(o,r,{artifactId:t,path:c},l=>{console.log(l.path)})}async function ym(e,t){let{config:r}=Y(t,e),o=await R(r,P("/api/auth/whoami"));D(t,e,o,n=>{console.log(`User: ${String(n.email??n.userId??"unknown")}`),n.tokenScope&&console.log(`Token scope: ${String(n.tokenScope)}`)})}import{readFile as dk,writeFile as pk}from"node:fs/promises";var f={};Be(f,{$brand:()=>Ja,$input:()=>$c,$output:()=>wc,INVALID:()=>fe,NEVER:()=>Ka,TimePrecision:()=>Nc,ZodAny:()=>wd,ZodArray:()=>Id,ZodBase64:()=>Ho,ZodBase64URL:()=>Wo,ZodBigInt:()=>Sn,ZodBigIntFormat:()=>Yo,ZodBoolean:()=>xn,ZodCIDRv4:()=>Go,ZodCIDRv6:()=>qo,ZodCUID:()=>Lo,ZodCUID2:()=>jo,ZodCatch:()=>qd,ZodCodec:()=>Er,ZodCompileAsyncError:()=>De,ZodCompileUnsupportedError:()=>Z,ZodCreditCard:()=>md,ZodCustom:()=>Tr,ZodCustomStringFormat:()=>Dt,ZodDate:()=>wr,ZodDefault:()=>Md,ZodDiscriminatedUnion:()=>Ed,ZodE164:()=>Ko,ZodEmail:()=>No,ZodEmoji:()=>zo,ZodEnum:()=>bn,ZodError:()=>dI,ZodExactOptional:()=>ta,ZodFile:()=>zd,ZodFirstPartyTypeKind:()=>ap,ZodFunction:()=>np,ZodGUID:()=>Do,ZodIBAN:()=>fd,ZodIPv4:()=>Bo,ZodIPv6:()=>Vo,ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,ZodInstanceOf:()=>op,ZodIntersection:()=>Td,ZodIssueCode:()=>fI,ZodJWT:()=>Jo,ZodKSUID:()=>Zo,ZodLazy:()=>Qd,ZodLiteral:()=>Dd,ZodMAC:()=>pd,ZodMap:()=>Od,ZodNaN:()=>Wd,ZodNanoID:()=>Uo,ZodNever:()=>xd,ZodNonOptional:()=>na,ZodNull:()=>yd,ZodNullable:()=>jd,ZodNumber:()=>$n,ZodNumberFormat:()=>zt,ZodObject:()=>xr,ZodOptional:()=>Ir,ZodPipe:()=>kr,ZodPrefault:()=>Zd,ZodPreprocess:()=>Kd,ZodPromise:()=>tp,ZodReadonly:()=>Jd,ZodRealError:()=>$e,ZodRecord:()=>yn,ZodSet:()=>Nd,ZodString:()=>wn,ZodStringFormat:()=>K,ZodSuccess:()=>Gd,ZodSymbol:()=>hd,ZodTemplateLiteral:()=>Xd,ZodTransform:()=>Ud,ZodTuple:()=>Pd,ZodType:()=>L,ZodULID:()=>Mo,ZodURL:()=>br,ZodUUID:()=>Fe,ZodUndefined:()=>_d,ZodUnion:()=>Sr,ZodUnknown:()=>$d,ZodVoid:()=>Sd,ZodXID:()=>Fo,ZodXor:()=>kd,_ZodString:()=>Oo,_default:()=>Fd,_function:()=>eh,any:()=>Rv,array:()=>$r,base64:()=>dv,base64url:()=>pv,bigint:()=>kv,boolean:()=>vd,catch:()=>Hd,check:()=>th,cidrv4:()=>cv,cidrv6:()=>lv,clone:()=>q,codec:()=>Jv,coerce:()=>up,compile:()=>kc,config:()=>te,core:()=>Ke,creditCard:()=>fv,cuid:()=>tv,cuid2:()=>nv,currencyCode:()=>bv,custom:()=>nh,date:()=>Ov,decode:()=>od,decodeAsync:()=>sd,deepPartial:()=>gh,describe:()=>rh,discriminatedUnion:()=>jv,e164:()=>mv,email:()=>Gg,emoji:()=>Qg,encode:()=>id,encodeAsync:()=>ad,endsWith:()=>un,enum:()=>Qo,exactOptional:()=>Ld,file:()=>qv,flattenError:()=>Bn,float32:()=>$v,float64:()=>xv,formatError:()=>Vn,fromJSONSchema:()=>mh,function:()=>eh,getDiscriminatedOption:()=>Ku,getErrorMap:()=>vI,globalRegistry:()=>ue,gt:()=>je,gte:()=>ke,guid:()=>qg,hash:()=>wv,hex:()=>yv,hostname:()=>_v,httpUrl:()=>Xg,iban:()=>gv,includes:()=>an,input:()=>hh,instanceof:()=>oh,int:()=>Ro,int32:()=>Sv,int64:()=>Ev,intersection:()=>Ad,invertCodec:()=>Yv,ipv4:()=>av,ipv6:()=>uv,iso:()=>Ar,json:()=>sh,jwt:()=>vv,keyof:()=>Nv,ksuid:()=>ov,lazy:()=>ep,length:()=>Pt,literal:()=>Gv,locales:()=>lr,looseObject:()=>Uv,looseRecord:()=>Fv,lowercase:()=>rn,lt:()=>Le,lte:()=>Ie,mac:()=>sv,map:()=>Zv,maxLength:()=>At,maxSize:()=>it,memoizer:()=>ur,meta:()=>ih,mime:()=>ln,minLength:()=>We,minSize:()=>Me,multipleOf:()=>rt,nan:()=>Kv,nanoid:()=>ev,nativeEnum:()=>Vv,negative:()=>bo,never:()=>Xo,nonnegative:()=>$o,nonoptional:()=>Vd,nonpositive:()=>wo,normalize:()=>dn,null:()=>bd,nullable:()=>yr,nullish:()=>Hv,number:()=>gd,object:()=>Dv,optional:()=>Ot,output:()=>_h,overwrite:()=>ze,parse:()=>ed,parseAsync:()=>td,partialRecord:()=>Mv,pipe:()=>Co,positive:()=>yo,prefault:()=>Bd,preprocess:()=>uh,prettifyError:()=>ts,promise:()=>Qv,properties:()=>cn,property:()=>xo,readonly:()=>Yd,record:()=>Cd,refine:()=>rp,regex:()=>nn,regexes:()=>Re,registry:()=>Hi,safeDecode:()=>cd,safeDecodeAsync:()=>dd,safeEncode:()=>ud,safeEncodeAsync:()=>ld,safeParse:()=>nd,safeParseAsync:()=>rd,set:()=>Bv,setErrorMap:()=>gI,size:()=>Tt,slugify:()=>gn,startsWith:()=>sn,strictObject:()=>zv,string:()=>_r,stringFormat:()=>hv,stringbool:()=>ah,success:()=>Wv,superRefine:()=>ip,symbol:()=>Av,templateLiteral:()=>Xv,toJSONSchema:()=>Eo,toLowerCase:()=>mn,toUpperCase:()=>fn,toZod:()=>On,transform:()=>ea,treeifyError:()=>es,trim:()=>pn,tuple:()=>Rd,uint32:()=>Iv,uint64:()=>Tv,ulid:()=>rv,undefined:()=>Pv,union:()=>In,unknown:()=>Ct,uppercase:()=>on,url:()=>Yg,util:()=>b,uuid:()=>Hg,uuidv4:()=>Wg,uuidv6:()=>Kg,uuidv7:()=>Jg,validate:()=>Gn,validateAsync:()=>qn,void:()=>Cv,withParser:()=>Wi,xid:()=>iv,xor:()=>Lv});var Ke={};Be(Ke,{$ZodAny:()=>Mu,$ZodArray:()=>qu,$ZodAsyncError:()=>be,$ZodBase64:()=>Tu,$ZodBase64URL:()=>Au,$ZodBigInt:()=>Oi,$ZodBigIntFormat:()=>zu,$ZodBoolean:()=>nr,$ZodCIDRv4:()=>ku,$ZodCIDRv6:()=>Eu,$ZodCUID:()=>fu,$ZodCUID2:()=>gu,$ZodCatch:()=>dc,$ZodCheck:()=>J,$ZodCheckBigIntFormat:()=>Fs,$ZodCheckEndsWith:()=>Qs,$ZodCheckGreaterThan:()=>hi,$ZodCheckIncludes:()=>Ys,$ZodCheckLengthEquals:()=>Hs,$ZodCheckLessThan:()=>vi,$ZodCheckLowerCase:()=>Ks,$ZodCheckMaxLength:()=>Gs,$ZodCheckMaxSize:()=>Zs,$ZodCheckMimeType:()=>nu,$ZodCheckMinLength:()=>qs,$ZodCheckMinSize:()=>Bs,$ZodCheckMultipleOf:()=>js,$ZodCheckNumberFormat:()=>Ms,$ZodCheckOverwrite:()=>ru,$ZodCheckProperties:()=>tu,$ZodCheckProperty:()=>eu,$ZodCheckRegex:()=>Ws,$ZodCheckSizeEquals:()=>Vs,$ZodCheckStartsWith:()=>Xs,$ZodCheckStringFormat:()=>Yt,$ZodCheckUpperCase:()=>Js,$ZodCodec:()=>ir,$ZodCreditCard:()=>Ru,$ZodCustom:()=>_c,$ZodCustomStringFormat:()=>Nu,$ZodCyclicError:()=>Mi,$ZodDate:()=>Vu,$ZodDefault:()=>sc,$ZodDiscriminatedUnion:()=>Ju,$ZodE164:()=>Pu,$ZodEmail:()=>uu,$ZodEmoji:()=>pu,$ZodEncodeError:()=>tt,$ZodEnum:()=>tc,$ZodError:()=>Qa,$ZodExactOptional:()=>oc,$ZodFile:()=>rc,$ZodFunction:()=>vc,$ZodGUID:()=>au,$ZodIBAN:()=>Cu,$ZodIPv4:()=>xu,$ZodIPv6:()=>Su,$ZodISODate:()=>bu,$ZodISODateTime:()=>yu,$ZodISODuration:()=>$u,$ZodISOTime:()=>wu,$ZodIntersection:()=>Yu,$ZodJWT:()=>Ou,$ZodKSUID:()=>_u,$ZodLazy:()=>or,$ZodLiteral:()=>nc,$ZodMAC:()=>Iu,$ZodMap:()=>Qu,$ZodNaN:()=>pc,$ZodNanoID:()=>mu,$ZodNever:()=>Zu,$ZodNonOptional:()=>cc,$ZodNull:()=>ju,$ZodNullable:()=>ac,$ZodNumber:()=>Ci,$ZodNumberFormat:()=>Du,$ZodObject:()=>ef,$ZodObjectJIT:()=>Hu,$ZodOptional:()=>Di,$ZodPipe:()=>zi,$ZodPrefault:()=>uc,$ZodPreprocess:()=>mc,$ZodPromise:()=>hc,$ZodReadonly:()=>fc,$ZodRealError:()=>we,$ZodRecord:()=>Xu,$ZodRegistry:()=>qi,$ZodSet:()=>ec,$ZodString:()=>St,$ZodStringFormat:()=>H,$ZodSuccess:()=>lc,$ZodSymbol:()=>Uu,$ZodTemplateLiteral:()=>gc,$ZodTransform:()=>ic,$ZodTuple:()=>Ni,$ZodType:()=>U,$ZodULID:()=>vu,$ZodURL:()=>du,$ZodUUID:()=>su,$ZodUndefined:()=>Lu,$ZodUnion:()=>rr,$ZodUnknown:()=>Fu,$ZodVoid:()=>Bu,$ZodXID:()=>hu,$ZodXor:()=>Wu,$brand:()=>Ja,$constructor:()=>g,$input:()=>$c,$output:()=>wc,Doc:()=>xt,INVALID:()=>fe,JSONSchema:()=>Zg,JSONSchemaGenerator:()=>To,NEVER:()=>Ka,TimePrecision:()=>Nc,URL_BAD_FORMAT:()=>cu,URL_UNPARSEABLE:()=>Yn,ZodCompileAsyncError:()=>De,ZodCompileUnsupportedError:()=>Z,_any:()=>Yc,_array:()=>il,_base64:()=>go,_base64url:()=>vo,_bigint:()=>Vc,_boolean:()=>Zc,_catch:()=>QS,_check:()=>kg,_cidrv4:()=>mo,_cidrv6:()=>fo,_coercedBigint:()=>Gc,_coercedBoolean:()=>Bc,_coercedDate:()=>nl,_coercedNumber:()=>zc,_coercedString:()=>Pc,_creditCard:()=>Cc,_cuid:()=>oo,_cuid2:()=>ao,_custom:()=>al,_date:()=>tl,_decode:()=>oi,_decodeAsync:()=>si,_default:()=>JS,_discriminatedUnion:()=>LS,_e164:()=>ho,_email:()=>Yi,_emoji:()=>ro,_encode:()=>ii,_encodeAsync:()=>ai,_endsWith:()=>un,_enum:()=>VS,_file:()=>ol,_float32:()=>Lc,_float64:()=>jc,_gt:()=>je,_gte:()=>ke,_guid:()=>Xi,_iban:()=>Oc,_includes:()=>an,_int:()=>Uc,_int32:()=>Mc,_int64:()=>qc,_intersection:()=>jS,_ipv4:()=>lo,_ipv6:()=>po,_isoDate:()=>mr,_isoDateTime:()=>pr,_isoDuration:()=>gr,_isoTime:()=>fr,_jwt:()=>_o,_ksuid:()=>co,_lazy:()=>rI,_length:()=>Pt,_literal:()=>qS,_lowercase:()=>rn,_lt:()=>Le,_lte:()=>Ie,_mac:()=>Rc,_map:()=>ZS,_max:()=>Ie,_maxLength:()=>At,_maxSize:()=>it,_mime:()=>ln,_min:()=>ke,_minLength:()=>We,_minSize:()=>Me,_multipleOf:()=>rt,_nan:()=>rl,_nanoid:()=>io,_nativeEnum:()=>GS,_negative:()=>bo,_never:()=>Qc,_nonnegative:()=>$o,_nonoptional:()=>YS,_nonpositive:()=>wo,_normalize:()=>dn,_null:()=>Jc,_nullable:()=>KS,_number:()=>Dc,_optional:()=>WS,_overwrite:()=>ze,_parse:()=>Ht,_parseAsync:()=>Wt,_pipe:()=>eI,_positive:()=>yo,_promise:()=>iI,_properties:()=>cn,_property:()=>xo,_readonly:()=>tI,_record:()=>FS,_refine:()=>sl,_regex:()=>nn,_safeDecode:()=>ci,_safeDecodeAsync:()=>di,_safeEncode:()=>ui,_safeEncodeAsync:()=>li,_safeParse:()=>Kt,_safeParseAsync:()=>Jt,_set:()=>BS,_size:()=>Tt,_slugify:()=>gn,_startsWith:()=>sn,_string:()=>Ac,_stringFormat:()=>Rt,_stringbool:()=>dl,_success:()=>XS,_superRefine:()=>ul,_symbol:()=>Wc,_templateLiteral:()=>nI,_toLowerCase:()=>mn,_toUpperCase:()=>fn,_transform:()=>HS,_trim:()=>pn,_tuple:()=>MS,_uint32:()=>Fc,_uint64:()=>Hc,_ulid:()=>so,_undefined:()=>Kc,_union:()=>zS,_unknown:()=>Xc,_uppercase:()=>on,_url:()=>dr,_uuid:()=>Qi,_uuidv4:()=>eo,_uuidv6:()=>to,_uuidv7:()=>no,_void:()=>el,_xid:()=>uo,_xor:()=>US,base64Charset:()=>Ei,base64urlCharset:()=>tr,canParseURL:()=>lu,clone:()=>q,compile:()=>kc,compileFn:()=>Ki,config:()=>te,createStandardJSONSchemaMethod:()=>vn,createToJSONSchemaMethod:()=>ml,decode:()=>Uw,decodeAsync:()=>jw,describe:()=>cl,encode:()=>zw,encodeAsync:()=>Lw,extractDefs:()=>at,finalize:()=>st,flattenError:()=>Bn,formatError:()=>Vn,getDiscriminatedOption:()=>Ku,globalConfig:()=>oe,globalRegistry:()=>ue,handleUnrepresentable:()=>re,initializeContext:()=>ot,isBackEdge:()=>Zi,isRecursiveSchema:()=>Fi,isValidBase64:()=>er,isValidBase64URL:()=>Ti,isValidCIDRv6:()=>ki,isValidCreditCard:()=>Ai,isValidIBAN:()=>Pi,isValidIPv6:()=>Qn,isValidJWT:()=>Ri,locales:()=>lr,memoizer:()=>ur,mergeValues:()=>Xt,meta:()=>ll,parse:()=>ni,parseAsync:()=>ri,parseURLObject:()=>Ym,prettifyError:()=>ts,process:()=>W,processSchema:()=>W,regexes:()=>Re,registry:()=>Hi,safeDecode:()=>Fw,safeDecodeAsync:()=>Bw,safeEncode:()=>Mw,safeEncodeAsync:()=>Zw,safeParse:()=>Rw,safeParseAsync:()=>Cw,standardProps:()=>$i,stripTabAndNewline:()=>Xn,toDotPath:()=>Pm,toJSONSchema:()=>Eo,toZod:()=>On,treeifyError:()=>es,urlHostnameOk:()=>Si,urlProtocolOk:()=>Ii,util:()=>b,validate:()=>Gn,validateAsync:()=>qn,validateURL:()=>xi,version:()=>iu,withParser:()=>Wi});var b={};Be(b,{BIGINT_FORMAT_RANGES:()=>Ln,CONSTANT_CATCH:()=>ei,Class:()=>ja,NUMBER_FORMAT_RANGES:()=>Un,aborted:()=>me,allowsEval:()=>Za,assert:()=>Yb,assertEqual:()=>Hb,assertIs:()=>Kb,assertNever:()=>Jb,assertNotEqual:()=>Wb,assignProp:()=>se,attachSchema:()=>jn,base64ToUint8Array:()=>Sm,base64urlToUint8Array:()=>vw,cached:()=>Bt,captureStackTrace:()=>Xr,cleanEnum:()=>gw,cleanRegex:()=>qe,clone:()=>q,cloneDef:()=>ew,codePointLength:()=>wt,constantCatch:()=>Ha,createTransparentProxy:()=>aw,defineLazy:()=>Ma,defineLazyInternal:()=>j,derived:()=>bw,esc:()=>pe,escapeRegex:()=>Pe,explicitlyAborted:()=>Ga,extend:()=>cw,finalizeIssue:()=>ye,floatSafeRemainder:()=>Nn,getElementAtPath:()=>tw,getEnumValues:()=>Ft,getLengthableOrigin:()=>Fn,getParsedType:()=>ow,getSizableOrigin:()=>Mn,hexToUint8Array:()=>_w,hide:()=>Zn,installLazyProp:()=>Sw,isObject:()=>bt,isPlainObject:()=>Ae,issue:()=>qt,joinValues:()=>h,jsonStringifyReplacer:()=>Zt,members:()=>qa,merge:()=>dw,mergeDefs:()=>Ne,normalizeParams:()=>I,nullish:()=>Yr,numKeys:()=>iw,objectClone:()=>Xb,omit:()=>uw,optionalKeys:()=>Va,own:()=>et,parsedType:()=>$,partial:()=>pw,pick:()=>sw,prefixIssues:()=>_e,primitiveTypes:()=>Ba,promiseAllObject:()=>nw,propertyKeyTypes:()=>zn,randomString:()=>rw,rawShape:()=>Vt,required:()=>mw,safeExtend:()=>lw,shallowClone:()=>Dn,sizeCaps:()=>Gt,slugify:()=>Fa,stringifyPrimitive:()=>w,toZod:()=>On,uint8ArrayToBase64:()=>Im,uint8ArrayToBase64url:()=>hw,uint8ArrayToHex:()=>yw,unwrapMessage:()=>Mt});function Hb(e){return e}function Wb(e){return e}function On(){return e=>e}function Kb(e){}function Jb(e){throw new Error("Unexpected value in exhaustive check")}function Yb(e){}function Ft(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function h(e,t="|"){return e.map(r=>w(r)).join(t)}function Zt(e,t){return typeof t=="bigint"?t.toString():t}var La=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function Bt(e){return new La(e)}function Yr(e){return e==null}function qe(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Nn(e,t){let r=e/t,o=Math.round(r),n=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var bm=Symbol("evaluating");function Ma(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==bm)return o===void 0&&(o=bm,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Xb(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function se(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Vt(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Ge(e){return Vt(e._zod.def)??e._zod.def.shape}function wm(e,t,r){Object.defineProperty(e,t,{get(){let o=r();return se(this,t,o),o},enumerable:!0,configurable:!0})}function $m(e,t,r){t in e?se(e,t,r):e[t]=r}function yt(e,t,r,o){let n=Ge(t);for(let i of r){let a=Object.getOwnPropertyDescriptor(n,i);a.enumerable&&(a.get?wm(e,i,()=>{let s=t._zod.def.shape[i];return o?o(s,i):s}):$m(e,i,o?o(a.value,i):a.value))}}function Qb(e,t){for(let r of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,r);o.enumerable&&(o.get?wm(e,r,()=>t[r]):$m(e,r,o.value))}}function Ne(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function ew(e){return Ne(e._zod.def)}function tw(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function nw(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function rw(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function pe(e){return JSON.stringify(e)}function Fa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Xr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Za=Bt(()=>{if(oe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ae(e){if(bt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(bt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Dn(e){return Ae(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function iw(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ow=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},zn=new Set(["string","number","symbol"]),Ba=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Pe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function I(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function aw(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function w(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Va(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Un={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ln={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return yt(i,e,Qr(e,t)),q(e,Ne(r,{shape:i,checks:[]}))}function Qr(e,t){let r=Ge(e),o=[];for(let n of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,n)?.enumerable)throw new Error(`Unrecognized key: "${String(n)}"`);t[n]&&o.push(n)}return o}function uw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(Qr(e,t)),a={};return yt(a,e,Reflect.ownKeys(Ge(e)).filter(s=>!i.has(s))),q(e,Ne(r,{shape:a,checks:[]}))}function cw(e,t){if(!Ae(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let n=Ge(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return q(e,Ne(e._zod.def,{shape:xm(e,t)}))}function xm(e,t){let r={};return yt(r,e,Reflect.ownKeys(Ge(e))),Qb(r,t),r}function lw(e,t){if(!Ae(t))throw new Error("Invalid input to safeExtend: expected a plain object");return q(e,Ne(e._zod.def,{shape:xm(e,t)}))}function dw(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};yt(r,e,Reflect.ownKeys(Ge(e))),yt(r,t,Reflect.ownKeys(Ge(t)));let o=Ne(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return q(e,o)}function pw(e,t,r,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let s=r?new Set(Qr(t,r)):void 0,u={};return yt(u,t,Reflect.ownKeys(Ge(t)),e&&((c,l)=>s&&!s.has(l)?c:new e({type:"optional",innerType:c}))),q(t,Ne(t._zod.def,{shape:u,checks:[]}))}function mw(e,t,r){let o=r?new Set(Qr(t,r)):void 0,n={};return yt(n,t,Reflect.ownKeys(Ge(t)),(i,a)=>o&&!o.has(a)?i:new e({type:"nonoptional",innerType:i})),q(t,Ne(t._zod.def,{shape:n}))}function me(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ga(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function _e(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function Mt(e){return typeof e=="string"?e:e?.message}function Gt(e){let t=[];for(let r of e??[]){let o=r._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;let n=o.maximum??o.length??o.size;n>=0&&t.push([n,r])}return t}function jn(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function ye(e,t,r){var o;let n=e.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:Mt(e.inst?._zod.def?.error?.(e))??Mt(i?.(e))??Mt(t?.error?.(e))??Mt(r.customError?.(e))??Mt(r.localeError?.(e))??"Invalid input",s={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(s[u]=e[u]);return s.path??(s.path=[]),s.message=a,t?.reportInput&&(s.input=e.input),s}function Mn(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var fw=/[\uD800-\uDBFF]/;function wt(e){let t=e.length;if(!fw.test(e))return t;let r=t;for(let o=0;o<t-1;o++)(e.charCodeAt(o)&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320&&(r--,o++);return r}function Fn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function $(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function qt(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function gw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Sm(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Im(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function vw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Sm(t+r)}function hw(e){return Im(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function _w(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function yw(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var ja=class{constructor(...t){}};function qa(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):ww(e,r,o.value)}}function et(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function Zn(e,t,r){return et(e,t,r,!1)}function bw(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return et(this,r,o(this))},set(n){et(this,r,n)}})}return t}function ww(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:et(this,t,r.bind(this))},set(o){et(this,t,o)}})}function $w(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Ua,Qe=!1,xw={configurable:!0,get(){Qe=!0}};function j(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&Ua!==e._zod){Ua=void 0;return}Ua=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,xw);let n=Qe;Qe=!1;try{let i=r(this);return Qe?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),Qe=Qe||n,i}catch(i){throw delete this[t],Qe=Qe||n,i}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function Sw(e,t,r,o){let n=$w(e,t);n&&Object.defineProperty(n,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var ei="~constantCatch";function Ha(e){let t=()=>e;return t[ei]=!0,t}var km,Ka=Object.freeze({status:"aborted"}),Wa={value:void 0,enumerable:!1},Em="captureStackTrace"in Error?Error:null;function Iw(e){let t=Em;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Em=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function g(e,t,r,o){let n={};function i(m){this.def=m,this.constr=d,this.traits=new Set}i.prototype=n;let a=r,s=a&&new WeakSet;function u(m,p){if(m._zod){if(m._zod.traits.has(e))return}else{Wa.value=new i(p);try{Object.defineProperty(m,"_zod",Wa)}finally{Wa.value=void 0}}if(m._zod.traits.add(e),t(m,p),s){let _=Object.getPrototypeOf(m),x=m._zod.constr.prototype,E=_;for(;E&&E!==x;)E=Object.getPrototypeOf(E);let k=E??_;s.has(k)||(s.add(k),qa(k,a))}let v=d.prototype;for(let _ in v)Object.prototype.hasOwnProperty.call(v,_)&&(_ in m||(m[_]=v[_].bind(m)))}let c=o?.Parent??Object;class l extends c{}Object.defineProperty(l,"name",{value:e});function d(m){let p=o?.Parent?Iw(l):this;u(p,m);let v=p._zod.deferred;if(v){for(let x of v)x();p._zod.deferred=void 0}let _=globalThis.__zod_globalConfig?.postProcessor;return _&&_(p),p}return Object.defineProperty(d,"init",{value:u}),Object.defineProperty(d,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Ja=Symbol("zod_brand"),be=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},tt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(km=globalThis).__zod_globalConfig??(km.__zod_globalConfig={});var oe=globalThis.__zod_globalConfig;function te(e){return e&&Object.assign(oe,e),oe}function kw(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Zt,2)),e.message}function Ew(e){this._zod.message=e}var Tw={get:kw,set:Ew,enumerable:!0,configurable:!0},Xa={value:void 0,enumerable:!1},Tm=new WeakSet([Object.prototype,Error.prototype]),Am=(e,t)=>{e.name="$ZodError",Xa.value=t,Object.defineProperty(e,"issues",Xa),Xa.value=void 0,Object.defineProperty(e,"message",Tw);let r=Object.getPrototypeOf(e);Tm.has(r)||(Tm.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},Qa=g("$ZodError",Am),we=g("$ZodError",Am,void 0,{Parent:Error});function Aw(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function Bn(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?Aw(r,n.path[0],()=>[]).push(t(n)):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Vn(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>o({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)r._errors.push(t(a));else{let u=r,c=0;for(;c<s.length;){let l=s[c],d=c===s.length-1;if(l==="_errors"){d&&u._errors.push(t(a)),c++;continue}Object.prototype.hasOwnProperty.call(u,l)||Object.defineProperty(u,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let m=u[l];d&&m._errors.push(t(a)),u=m,c++}}}};return o(e),r}function es(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a;for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(u=>o({issues:u},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let u=[...i,...s.path];if(u.length===0){r.errors.push(t(s));continue}let c=r,l=0;for(;l<u.length;){let d=u[l],m=l===u.length-1;typeof d=="string"?(c.properties??(c.properties={}),Object.prototype.hasOwnProperty.call(c.properties,d)||Object.defineProperty(c.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),c=c.properties[d]):(c.items??(c.items=[]),(a=c.items)[d]??(a[d]={errors:[]}),c=c.items[d]),m&&c.errors.push(t(s)),l++}}};return o(e),r}function Pm(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function ts(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Pm(o.path)}`);return t.join(`
10
10
  `)}function ti(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Ht=e=>{let t=(r,o,n,i)=>{let a=n?{...n,async:!1}:{async:!1},s=r._zod.run({value:o,issues:[]},a);if(s instanceof Promise)throw new be;if(s.issues.length){let u=new(i?.Err??e)(s.issues.map(c=>ye(c,a,te())));throw Xr(u,i?.callee??t),u}return s.value};return t},ni=Ht(we),Wt=e=>{let t=async(r,o,n,i)=>{let a=n?{...n,async:!0}:{async:!0},s=r._zod.run({value:o,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let u=new(i?.Err??e)(s.issues.map(c=>ye(c,a,te())));throw Xr(u,i?.callee??t),u}return s.value};return t},ri=Wt(we),Kt=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new be;return i.issues.length?Rm(e,i.issues,n):{success:!0,data:i.value}},Rw=Kt(we);function Rm(e,t,r){let o;return{success:!1,get error(){return o||(o=new e(t.map(n=>ye(n,r,te()))),t=void 0,r=void 0),o},set error(n){o=n,t=void 0,r=void 0}}}var Jt=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?Rm(e,i.issues,n):{success:!0,data:i.value}},Cw=Jt(we),Ow=Symbol.for("zod.compile.invalid"),Nw=Symbol.for("zod.compile.fallback"),Gn=((e,t,r)=>{let o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==Ow)return!0;if(o.definite===!0&&r===void 0)return!1}return Dw(e,t,r)});function Dw(e,t,r){let o=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},n=e._zod.bag.fallbackRun,i;if(n?(o[Nw]=!0,i=n({value:t,issues:[]},o)):i=e._zod.run({value:t,issues:[]},o),i instanceof Promise)throw new be;return i.issues.length===0}var qn=async(e,t,r)=>{let o=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},n=e._zod.run({value:t,issues:[]},o);return n instanceof Promise&&(n=await n),n.issues.length===0},ii=e=>{let t=Ht(e),r=(o,n,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(o,n,s,ti(r,a))};return r},zw=ii(we),oi=e=>{let t=Ht(e),r=(o,n,i,a)=>t(o,n,i,ti(r,a));return r},Uw=oi(we),ai=e=>{let t=Wt(e),r=async(o,n,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(o,n,s,ti(r,a))};return r},Lw=ai(we),si=e=>{let t=Wt(e),r=async(o,n,i,a)=>await t(o,n,i,ti(r,a));return r},jw=si(we),ui=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Kt(e)(t,r,n)},Mw=ui(we),ci=e=>(t,r,o)=>Kt(e)(t,r,o),Fw=ci(we),li=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Jt(e)(t,r,n)},Zw=li(we),di=e=>async(t,r,o)=>Jt(e)(t,r,o),Bw=di(we);var Re={};Be(Re,{anyString:()=>Ts,base64:()=>ys,base64url:()=>bs,bigint:()=>Ps,boolean:()=>Rs,browserEmail:()=>Yw,cidrv4:()=>hs,cidrv6:()=>_s,creditCard:()=>pi,cuid:()=>rs,cuid2:()=>is,currencyCode:()=>Ss,date:()=>Is,datetime:()=>Es,domain:()=>$s,duration:()=>ls,e164:()=>xs,email:()=>ps,emoji:()=>ms,extendedDuration:()=>Vw,guid:()=>ds,hex:()=>zs,hostname:()=>ws,html5Email:()=>Ww,httpProtocol:()=>Hn,iban:()=>mi,idnEmail:()=>Jw,integer:()=>Wn,ipv4:()=>fs,ipv6:()=>gs,ksuid:()=>ss,lowercase:()=>Ns,mac:()=>vs,md5_base64:()=>t$,md5_base64url:()=>n$,md5_hex:()=>e$,nanoid:()=>us,nanoidOfLength:()=>cs,null:()=>Cs,number:()=>He,rfc5322Email:()=>Kw,sha1_base64:()=>i$,sha1_base64url:()=>o$,sha1_hex:()=>r$,sha256_base64:()=>s$,sha256_base64url:()=>u$,sha256_hex:()=>a$,sha384_base64:()=>l$,sha384_base64url:()=>d$,sha384_hex:()=>c$,sha512_base64:()=>m$,sha512_base64url:()=>f$,sha512_hex:()=>p$,string:()=>As,time:()=>ks,ulid:()=>os,undefined:()=>Os,unicodeEmail:()=>Cm,uppercase:()=>Ds,uuid:()=>$t,uuid4:()=>Gw,uuid6:()=>qw,uuid7:()=>Hw,xid:()=>as});var rs=/^[cC][0-9a-z]{6,}$/,is=/^[0-9a-z]+$/,os=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,as=/^[0-9a-vA-V]{20}$/,ss=/^[A-Za-z0-9]{27}$/,us=/^[a-zA-Z0-9_-]{21}$/;function cs(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var ls=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ds=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,$t=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Gw=$t(4),qw=$t(6),Hw=$t(7),ps=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ww=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Kw=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Cm=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Jw=Cm,Yw=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Xw="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function ms(){return new RegExp(Xw,"u")}var fs=/^(?:(?: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])$/,gs=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,vs=e=>{let t=Pe(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},hs=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,_s=/^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ys=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bs=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,ws=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,$s=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,Hn=/^https?$/,xs=/^\+[1-9]\d{6,14}$/,pi=/^\d(?:[ -]?\d){11,18}$/,Ss=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,mi=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,Om="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Qw(e){return new RegExp(`^${e}$`)}var Is=Qw(Om);function ns(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ks(e){return new RegExp(`^${ns(e)}$`)}function Es(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${ns({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,o=e.local?`${r}|${ns({precision:e.precision})}`:r;return new RegExp(`^${Om}T(?:${o})$`)}var Ts=/^[\s\S]{0,}$/,As=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ps=/^-?\d+n?$/,Wn=/^-?\d+$/,He=/^-?\d+(?:\.\d+)?$/,Rs=/^(?:true|false)$/i,Cs=/^null$/i;var Os=/^undefined$/i;var Ns=/^[^A-Z]*$/,Ds=/^[^a-z]*$/,zs=/^[0-9a-fA-F]*$/;function Kn(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Jn(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var e$=/^[0-9a-fA-F]{32}$/,t$=Kn(22,"=="),n$=Jn(22),r$=/^[0-9a-fA-F]{40}$/,i$=Kn(27,"="),o$=Jn(27),a$=/^[0-9a-fA-F]{64}$/,s$=Kn(43,"="),u$=Jn(43),c$=/^[0-9a-fA-F]{96}$/,l$=Kn(64,""),d$=Jn(64),p$=/^[0-9a-fA-F]{128}$/,m$=Kn(86,"=="),f$=Jn(86);var J=g("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Us=e=>{let t=e.value;return!Yr(t)&&t.size!==void 0},Ls=e=>{let t=e.value;return!Yr(t)&&t.length!==void 0},fi={number:"number",bigint:"bigint",object:"date"},vi=g("$ZodCheckLessThan",(e,t)=>{J.init(e,t);let r=fi[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:fi[typeof o.value]??r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),hi=g("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);let r=fi[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:fi[typeof o.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),js=g("$ZodCheckMultipleOf",(e,t)=>{J.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):Nn(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ms=g("$ZodCheckNumberFormat",(e,t)=>{J.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Un[t.format];e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}s<n&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Fs=g("$ZodCheckBigIntFormat",(e,t)=>{J.init(e,t);let[r,o]=Ln[t.format];e._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Zs=g("$ZodCheckMaxSize",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Us),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:Mn(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Bs=g("$ZodCheckMinSize",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Us),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:Mn(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Vs=g("$ZodCheckSizeEquals",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Us),e._zod.check=o=>{let n=o.value,i=n.size;if(i===t.size)return;let a=i>t.size;o.issues.push({origin:Mn(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Gs=g("$ZodCheckMaxLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Ls),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>t.maximum?wt(n):i)<=t.maximum)return;let s=Fn(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),qs=g("$ZodCheckMinLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Ls),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>=t.minimum&&i<t.minimum*2?wt(n):i)>=t.minimum)return;let s=Fn(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Hs=g("$ZodCheckLengthEquals",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=Ls),e._zod.check=o=>{let n=o.value,i=n.length,a=typeof n=="string"&&i>=t.length&&i<=t.length*2?wt(n):i;if(a===t.length)return;let s=Fn(n),u=a>t.length;o.issues.push({origin:s,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Yt=g("$ZodCheckStringFormat",(e,t)=>{var r,o;J.init(e,t),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Ws=g("$ZodCheckRegex",(e,t)=>{Yt.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ks=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ns),Yt.init(e,t)}),Js=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ds),Yt.init(e,t)}),Ys=g("$ZodCheckIncludes",(e,t)=>{J.init(e,t);let r=Pe(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r);t.pattern=o,e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Xs=g("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);let r=new RegExp(`^${Pe(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Qs=g("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);let r=new RegExp(`.*${Pe(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function gi(e,t,r){e.issues.length&&t.issues.push(..._e(r,e.issues))}var eu=g("$ZodCheckProperty",(e,t)=>{J.init(e,t),e._zod.check=r=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>gi(n,r,t.property));gi(o,r,t.property)}}),tu=g("$ZodCheckProperties",(e,t)=>{J.init(e,t),Zn(e,Symbol.iterator,function*(){yield e});let r;e._zod.check=o=>{if(o.value==null){o.issues.push({expected:"object",code:"invalid_type",input:o.value,inst:e});return}r??(r=Reflect.ownKeys(t.shape).map(a=>[a,t.shape[a]]));let n=o.value,i;for(let[a,s]of r){let u=s._zod.run({value:n[a],issues:[]},{});u instanceof Promise?(i??(i=[]),i.push(u.then(c=>gi(c,o,a)))):gi(u,o,a)}if(i)return Promise.all(i).then(()=>{})}}),nu=g("$ZodCheckMimeType",(e,t)=>{J.init(e,t);let r=new Set(t.mime);e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),ru=g("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var xt=class{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
11
11
  `).filter(a=>a),n=Math.min(...o.map(a=>a.length-a.trimStart().length)),i=o.map(a=>a.slice(n)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
@@ -67,9 +67,9 @@ ${u}`:u:"",l=Function,d=`return (input) => {
67
67
  ${u}
68
68
  }`,m;try{m=new l(...a,d)(...s)}catch(p){throw new Z(`this schema (generated code failed to evaluate: ${p.message})`)}return t?.debug&&(m.code=c),m.definite=o.definite,m}function N(e,t){for(let[o,n]of e.constants)if(n===t)return o;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function kt(e,t){return e.definite=!1,N(e,t)}function C(e){return`v${e.varCounter++}`}function jx(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return fe;let o=r;return o.issues.length===0?o.value:fe}function le(e,t,r,o,n=!0){let i=e.content.length,a=t.constants.size,s=t.constantCounter,u=t.varCounter;try{return X(e,t,r,o,n)}catch(c){if(!(c instanceof Z)||!c.islandable)throw c;if(e.content.length=i,t.constants.size>a){let l=Array.from(t.constants.keys()).slice(a);for(let d of l)t.constants.delete(d)}return t.constantCounter=s,t.varCounter=u,Mx(e,t,r,o)}}function Mx(e,t,r,o){t.definite=!1;let n=N(t,r),i=N(t,jx),a=C(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var Fx=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Zx(e,t,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let a of n){let s=a._zod.def;if(s.when&&!Fx.has(s.check))throw new Z('check with a custom "when" condition');switch(s.check){case"greater_than":Bx(e,t,s,i);break;case"less_than":Vx(e,t,s,i);break;case"multiple_of":Gx(e,t,s,i);break;case"number_format":Sg(e,s,i);break;case"min_length":{let u=nt(s.minimum,"min_length"),c=xc(e,t,i,`${i}.length >= ${u} && ${i}.length < ${s.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{let u=nt(s.maximum,"max_length"),c=xc(e,t,i,`${i}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{let u=nt(s.length,"length_equals"),c=xc(e,t,i,`${i}.length >= ${u} && ${i}.length <= ${s.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${nt(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${nt(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${nt(s.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Ig(e,t,s,i);break;case"custom":i=Yx(e,t,a,i);break;case"bigint_format":qx(e,s,i);break;case"mime_type":Hx(e,t,s,i);break;case"property":Kx(e,t,s,i);break;case"properties":Wx(e,t,s,i);break;case"overwrite":{let u=C(t);Jx(e,t,a,i,u),i=u;break}default:throw new Z(`check type ${s.check}`)}}return i}function xc(e,t,r,o){let n=N(t,wt),i=C(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function nt(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Z(`${t} bound of type ${typeof e}`);return`${e}`}function xg(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Z("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Z("comparison check with Invalid Date bound");return N(e,t)}throw new Z(`comparison check bound of type ${typeof t}`)}function Bx(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${xg(t,r.value)}) return INVALID;`)}function Vx(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${xg(t,r.value)}) return INVALID;`)}function Gx(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Z("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=N(t,Nn);e.write(`if (${n}(${o}, ${nt(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Sg(e,t,r){let o=t.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Z(`number format ${o}`)}}function qx(e,t,r){let o=t.format;if(o)switch(o){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Z(`bigint format ${o}`)}}function Hx(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=N(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Wx(e,t,r,o){if(r.when)throw new Z('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let a=typeof i=="symbol"?N(t,i):pe(i),s=C(t);e.write(`const ${s} = ${o}[${a}];`),le(e,t,n[i],s,!1)}}function Kx(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;X(e,t,r.schema,n)}function Jx(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new Z("overwrite check without a transform function");if(Et(i))throw new De("z.compile: async overwrite transforms are not supported");let a=N(t,i);e.write(`const ${n} = ${a}(${o});`)}function Sc(){throw new be}function Ec(e){this.issues.push(e)}function Yx(e,t,r,o){let n=r._zod.def;if(n.fn){if(Et(n.fn))throw new De("z.compile: async .refine() predicates are not supported");let i=kt(t,n.fn),a=N(t,Sc),s=C(t);return e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`),o}if(r._zod.check){if(Et(r._zod.check))throw new De("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,s=kt(t,c=>{let l={value:c,issues:[],addIssue:Ec};return i(l)instanceof Promise&&Sc(),l.issues.length===0?l.value:fe}),u=C(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new Z("custom check without a predicate or check function")}var Xx=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Ig(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let c=N(t,er);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="base64url"){let c=N(t,Ti);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="jwt"){let c=N(t,Ri),l=N(t,r.alg??null);return e.write(`if (!${c}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let c=N(t,Qn);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="cidrv6"){let c=N(t,ki);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="credit_card"){let c=N(t,Ai);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="iban"){let c=N(t,Pi);return e.write(`if (!${c}(${o})) return INVALID;`),o}let a=r;if(i==="url"||i==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let c=N(t,xi),l=N(t,r),d=C(t),m=C(t);if(e.write(`const ${d} = ${o}.trim();`),e.write(`const ${m} = ${c}(${d}, ${l});`),e.write(`if (typeof ${m} === "number") return INVALID;`),a.hostname!==void 0){let _=N(t,Si);e.write(`if (!${_}(${m}, ${l}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let _=N(t,Ii);e.write(`if (!${_}(${m}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=C(t),v=a.normalize?`${m}.href`:`${N(t,Xn)}(${d})`;return e.write(`const ${p} = ${v};`),p}let s=r.fn;if(s){if(Et(s))throw new Z(`async string format ${i}`);let c=N(t,s);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(Xx.has(i)&&r.pattern){let c=N(t,r.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${o})) return INVALID;`),o}let u=r.format;switch(u){case"regex":throw new Z("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${pe(r.includes)})) return INVALID;`);break;case"starts_with":{let c=r.prefix;e.write(`if (${o}.slice(0, ${c.length}) !== ${pe(c)}) return INVALID;`);break}case"ends_with":{let c=r.suffix;e.write(`if (${o}.slice(-${c.length}) !== ${pe(c)}) return INVALID;`);break}default:throw new Z(`string format ${u}`)}return o}function X(e,t,r,o,n=!0){let i=r._zod.def,a=i.type;if(i.coerce)throw new Z(`coercion (z.coerce.${a}())`);let s=n||!!i.checks?.length,u;switch(a){case"string":u=Qx(e,t,r,o,s);break;case"number":u=eS(e,r,o);break;case"boolean":u=tS(e,o);break;case"bigint":u=nS(e,r,o);break;case"symbol":u=rS(e,o);break;case"undefined":u=iS(e,o);break;case"null":u=oS(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=aS(e,o);break;case"nan":u=sS(e,o);break;case"date":u=uS(e,o);break;case"object":u=cS(e,t,r,o,s);break;case"optional":u=lS(e,t,r,o,s);break;case"nullable":u=mS(e,t,r,o,s);break;case"array":u=fS(e,t,r,o,s);break;case"literal":u=gS(e,t,r,o);break;case"enum":u=vS(e,t,r,o);break;case"readonly":{let c=bg(e,t,r,o),l=C(t);e.write(`const ${l} = Object.freeze(${c});`),u=l;break}case"success":bg(e,t,r,o),u="true";break;case"default":case"prefault":u=hS(e,t,r,o);break;case"nonoptional":u=_S(e,t,r,o);break;case"tuple":u=yS(e,t,r,o);break;case"union":u=bS(e,t,r,o);break;case"intersection":u=xS(e,t,r,o);break;case"record":u=SS(e,t,r,o);break;case"map":u=kS(e,t,r,o);break;case"set":u=ES(e,t,r,o);break;case"file":u=TS(e,o);break;case"template_literal":u=AS(e,t,r,o);break;case"lazy":u=PS(e,t,r,o);break;case"pipe":u=RS(e,t,r,o);break;case"custom":u=CS(e,t,r,o);break;case"transform":u=DS(e,t,r,o);break;case"catch":u=NS(e,t,r,o);break;default:throw new Z(`schema type ${a}`)}return u===null?null:Zx(e,t,r,u)}function Qx(e,t,r,o,n=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:Ig(e,t,i,o,n)}function eS(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=t._zod.def;return o.check==="number_format"&&o.format&&Sg(e,{format:o.format},r),r}function tS(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function nS(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=t._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function rS(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function iS(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function oS(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function aS(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function sS(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function uS(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function cS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let a=i.shape,s=Object.keys(a),u=Object.getOwnPropertySymbols(a),c=u.length?[...s,...u]:s,l=k=>typeof k=="symbol"?N(t,k):pe(k),d=k=>typeof k=="symbol"?`[${l(k)}]`:pe(k),m=a;if(s.includes("__proto__"))throw new Z('object shape key "__proto__"');let p=new Map;for(let k of c){let A=m[k],S=l(k),O=C(t);if(e.write(`const ${O} = ${o}[${S}];`),A._zod.optin!==void 0){let z=C(t);e.write(`let ${z} = (() => {`),e.indented(G=>{let ne=le(G,t,A,O);G.write(`return ${ne};`)}),e.write("})();"),A._zod.optout==="optional"?(e.write(`if (${z} === INVALID) {`),e.indented(G=>{G.write(`if (${S} in ${o}) return INVALID;`),G.write(`${z} = undefined;`)}),e.write("}")):e.write(`if (${z} === INVALID) return INVALID;`),p.set(k,z)}else{pS(A)&&e.write(`if (!(${S} in ${o})) return INVALID;`);let z=le(e,t,A,O,n);z!==null&&p.set(k,z)}}let v=i.catchall,_="none";if(v){let k=v._zod.def.type;if(k==="never"){let A=s.map(S=>`k !== ${pe(S)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(S=>{S.write(`if (${A}) return INVALID;`)}),e.write("}")}else(k==="unknown"||k==="any")&&!v._zod.def.checks?.length?_="passthrough":_="schema"}let x=C(t),E=c.some(k=>yg(m[k])||Ic(m[k]));if(!n){if(_==="schema"){let k=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`);let S=C(t);A.write(`const ${S} = ${o}[k];`),le(A,t,v,S,!1)}),e.write("}")}return null}if(E){e.write(`const ${x} = {};`);for(let k of c){let A=l(k),S=p.get(k);Ic(m[k])?e.write(`if (${A} in ${o}) ${x}[${A}] = ${S};`):yg(m[k])?e.write(`if (${S} !== undefined || ${A} in ${o}) ${x}[${A}] = ${S};`):e.write(`${x}[${A}] = ${S};`)}}else{let k=c.map(A=>`${d(A)}: ${p.get(A)}`).join(", ");e.write(`const ${x} = { ${k} };`)}if(_!=="none"){let k=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{if(A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`),_==="passthrough")A.write(`${x}[k] = ${o}[k];`);else{let S=C(t);A.write(`const ${S} = ${o}[k];`);let O=le(A,t,v,S);A.write(`${x}[k] = ${O};`)}}),e.write("}")}return x}function lS(e,t,r,o,n=!0){let i=r._zod.def;if(dS(r))return X(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let s=C(t),u=C(t);return e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(l=>{let d=X(l,t,i.innerType,o);l.write(`return ${d};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${s} = ${u};`)}),e.write("} else {"),e.indented(c=>{let l=X(c,t,i.innerType,o);c.write(`${s} = ${l};`)}),e.write("}"),s}let a=n?C(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(s=>{let u=X(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function dS(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function pS(e){return e._zod.optin===void 0&&It(e)}function It(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?It(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?It(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(It):!0;case"intersection":return!t.left||!t.right?!0:It(t.left)&&It(t.right);case"pipe":return t.in?It(t.in):!0;default:return!0}}function Ic(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function yg(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&tn(e)}function tn(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?tn(t.innerType):!0;case"union":return t.options?t.options.some(tn):!0;case"intersection":return!t.left||!t.right||tn(t.left)||tn(t.right);case"pipe":return t.out?tn(t.out):!0;default:return!0}}function mS(e,t,r,o,n=!0){let i=r._zod.def,a=n?C(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(s=>{let u=X(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function Tc(e,t,r){for(let[o,n]of Gt(t._zod.def.checks))e.write(`if (${r} > ${nt(o,n._zod.def.check)}) return INVALID;`)}function fS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),Tc(e,r,`${o}.length`);let a=n?C(t):null,s=C(t),u=C(t);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${s} = 0; ${s} < ${o}.length; ${s}++) {`),e.indented(c=>{c.write(`const ${u} = ${o}[${s}];`);let l=le(c,t,i.element,u,n);a&&l!==null&&c.write(`${a}[${s}] = ${l};`)}),e.write("}"),a}function gS(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}let a=i[0];if(typeof a=="number"&&Number.isNaN(a)){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${pe(a)}) return INVALID;`);else if(typeof a=="number"||typeof a=="boolean")e.write(`if (${o} !== ${a}) return INVALID;`);else if(a===null)e.write(`if (${o} !== null) return INVALID;`);else if(a===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof a=="bigint")e.write(`if (${o} !== ${a}n) return INVALID;`);else throw new Z(`literal type ${typeof a}`);return o}function vS(e,t,r,o){let n=r._zod.values;if(!n)throw new Z("enum schema without enumerated values");let i=N(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function bg(e,t,r,o){let n=r._zod.def;return X(e,t,n.innerType,o)}function hS(e,t,r,o){let n=r._zod.def,a=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!a)return X(e,t,n.innerType,o);let u=N(t,a),c=C(t);return e.write(`let ${c} = ${o};`),e.write(`if (${o} === undefined) ${c} = ${u}();`),X(e,t,n.innerType,c)}let s=C(t);if(a){let u=N(t,a),c=N(t,Dn);e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`${s} = ${c}(${u}());`)}),e.write("} else {"),e.indented(l=>{let d=X(l,t,n.innerType,o);l.write(`${s} = ${d} === undefined ? ${c}(${u}()) : ${d};`)}),e.write("}")}else e.write(`let ${s};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let c=X(u,t,n.innerType,o);u.write(`${s} = ${c};`)}),e.write("}");return s}function _S(e,t,r,o){let n=r._zod.def,i=X(e,t,n.innerType,o),a=C(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function yS(e,t,r,o){let n=r._zod.def,i=n.items,a=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let s=wg(i,"optin"),u=wg(i,"optout");a?e.write(`if (${o}.length < ${s}) return INVALID;`):e.write(`if (${o}.length < ${s} || ${o}.length > ${i.length}) return INVALID;`);let c=C(t);e.write(`const ${c} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=u)e.write(`if (${c}.length === ${l}) {`),e.indented(m=>{m.write(`if (${l} < ${o}.length) {`),m.indented(p=>{let v=C(t);p.write(`const ${v} = ${o}[${l}];`);let _=le(p,t,d,v);p.write(`${c}[${l}] = ${_};`)}),m.write("} else {"),m.indented(p=>{if(Ic(d)){p.write(`${c}.length = ${l};`);return}let v=C(t),_=C(t);p.write(`const ${v} = undefined;`),p.write(`const ${_} = (() => {`),p.indented(x=>{let E=le(x,t,d,v);x.write(`return ${E};`)}),p.write("})();"),p.write(`if (${_} === INVALID || ${_} === undefined) ${c}.length = ${l};`),p.write(`else ${c}[${l}] = ${_};`)}),m.write("}")}),e.write("}");else{let m=C(t);e.write(`const ${m} = ${o}[${l}];`);let p=le(e,t,d,m);e.write(`${c}[${l}] = ${p};`)}}if(a){let l=C(t),d=C(t);e.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),e.indented(m=>{m.write(`const ${d} = ${o}[${l}];`);let p=le(m,t,a,d);m.write(`${c}[${l}] = ${p};`)}),e.write("}")}return c}function wg(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function bS(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return wS(e,t,n,o);if(n.inclusive===!1)throw new Z("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return X(e,t,i[0],o);if(i.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(i.flatMap(l=>l._zod.def.values)),c=N(t,u);return e.write(`if (!${c}.has(${o})) return INVALID;`),o}let s=C(t);e.write(`let ${s};`);for(let u=0;u<i.length;u++){let c=i[u];u===0?e.write(`${s} = (() => {`):e.write(`if (${s} === INVALID) ${s} = (() => {`),e.indented(l=>{let d=X(l,t,c,o);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function wS(e,t,r,o){if(r.unionFallback)throw new Z("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=C(t),i=C(t);e.write(`const ${n} = ${o}?.[${pe(r.discriminator)}];`),e.write(`let ${i};`);let a=!0,s=new Set;for(let u of r.options){let c=u._zod.propValues?.[r.discriminator];if(!c||c.size===0)throw new Z("discriminated union option without static discriminator values");for(let m of c){if(s.has(m))throw new Z(`duplicate discriminator value ${String(m)}`);s.add(m)}let l=Array.from(c,m=>$S(t,n,m)),d=a?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(m=>{let p=X(m,t,u,o);m.write(`${i} = ${p};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function $S(e,t,r){if(typeof r=="string")return`${t} === ${pe(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let o=N(e,r);return`${t} === ${o}`}throw new Z(`literal discriminator value ${String(r)}`)}function xS(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=le(e,t,n.left,o),a=le(e,t,n.right,o),s=N(t,Xt),u=C(t);return e.write(`const ${u} = ${s}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function SS(e,t,r,o){let n=r._zod.def,i=N(t,Ae);e.write(`if (!${i}(${o})) return INVALID;`);let a=C(t),s=C(t),u=C(t);e.write(`const ${a} = {};`);let c=n,l=c.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let _ of l){if(!(typeof _=="string"||typeof _=="number"||typeof _=="symbol"))throw new Z(`record key value ${String(_)}`);let x=typeof _=="number"?_.toString():_;if(x==="__proto__")throw new Z('record key "__proto__"');p.push(x);let E=N(t,_),k=X(e,t,n.keyType,E),A=C(t);e.write(`const ${A} = ${o}[${IS(t,x)}];`);let S=le(e,t,n.valueType,A);e.write(`${a}[${k}] = ${S};`)}let v=N(t,new Set(p));return e.write(`for (const ${s} in ${o}) {`),e.indented(_=>{_.write(`if (${v}.has(${s})) continue;`),c.mode==="loose"?_.write(`if (${s} !== "__proto__") ${a}[${s}] = ${o}[${s}];`):_.write("return INVALID;")}),e.write("}"),a}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",v=Ki(n.keyType);v.definite===!1&&(t.definite=!1);let _=N(t,v),x=N(t,He),E=C(t);return $g(e,t,o,s,k=>{k.write(`let ${E} = ${_}(${s});`),k.write(`if (${E} === INVALID && typeof ${s} === "string" && ${x}.test(${s})) ${E} = ${_}(Number(${s}));`),p?k.write(`if (${E} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):k.write(`if (${E} === INVALID) return INVALID;`),k.write(`if (${E} === "__proto__") continue;`);let A=C(t);k.write(`const ${A} = ${o}[${s}];`);let S=le(k,t,n.valueType,A);k.write(`${a}[${E}] = ${S};`)}),a}return $g(e,t,o,s,p=>{p.write(`const ${u} = ${o}[${s}];`);let v=le(p,t,n.valueType,u);p.write(`${a}[${s}] = ${v};`)},"return INVALID;"),a}function $g(e,t,r,o,n,i){let a=N(t,Object.prototype.propertyIsEnumerable),s=C(t),u=C(t),c=C(t);e.write(`const ${s} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${u} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${o} = ${u}[${c}];`),l.write(`if (${o} === "__proto__" || !${a}.call(${r}, ${o})) continue;`),n(l)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${s}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${o} = ${s}[${c}];`),l.write(`if (!${a}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),e.write("}")}function IS(e,t){return typeof t=="string"?pe(t):N(e,t)}function kS(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Tc(e,r,`${o}.size`);let i=C(t),a=C(t),s=C(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${s}] of ${o}) {`),e.indented(u=>{let c=X(u,t,n.keyType,a),l=X(u,t,n.valueType,s);u.write(`${i}.set(${c}, ${l});`)}),e.write("}"),i}function ES(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Tc(e,r,`${o}.size`);let i=C(t),a=C(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(s=>{let u=X(s,t,n.valueType,a);s.write(`${i}.add(${u});`)}),e.write("}"),i}function TS(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function AS(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=N(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function PS(e,t,r,o){let n=r._zod.def,i=kt(t,n.getter),a=N(t,{parser:null});e.write(`if (!${a}.parser) {`),e.indented(u=>{u.write(`const inner = ${i}();`),u.write(`${a}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let s=C(t);return e.write(`const ${s} = ${a}.parser(${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function RS(e,t,r,o){let n=r._zod.def,i=X(e,t,n.in,o);if(n.transform){if(Et(n.transform))throw new De("z.compile: async transforms in pipes are not supported");let a=n.transform,u=kt(t,l=>{let d={value:l,issues:[],addIssue:Ec},m=a(l,d);return m instanceof Promise?fe:d.issues.length===0?m:fe}),c=C(t);return e.write(`const ${c} = ${u}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),X(e,t,n.out,c)}else return X(e,t,n.out,i)}function Et(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function CS(e,t,r,o){let n=r._zod.def;if(n.fn){if(Et(n.fn))throw new De("z.compile: async custom predicates are not supported");let i=kt(t,n.fn),a=N(t,Sc),s=C(t);e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`)}else throw new Z("custom schema without a predicate function");return o}function OS(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return fe;let n=o;return n.issues.length===0?n.value:t()}function NS(e,t,r,o){let n=r._zod.def;if(!n.catchValue[ei])throw new Z("catch with a callback (only a constant catch value compiles)",!1);let i=C(t);e.write(`let ${i} = (() => {`),e.indented(c=>{let l=le(c,t,n.innerType,o);c.write(`return ${l};`)}),e.write("})();");let a=N(t,n.innerType),s=kt(t,n.catchValue),u=N(t,OS);return e.write(`if (${i} === INVALID) {`),e.indented(c=>{c.write(`${i} = ${u}(${a}, ${s}, ${o});`),c.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function DS(e,t,r,o){let n=r._zod.def;if(n.transform){if(Et(n.transform))throw new De("z.compile: async transforms are not supported");let i=n.transform,s=kt(t,c=>{let l={value:c,issues:[],addIssue:Ec},d=i(c,l);return d instanceof Promise?fe:l.issues.length===0?d:fe}),u=C(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function Ji(e){return e.checks&&(e.checks=[...e.checks]),e}function Ac(e,t){return new e(Ji({type:"string",...I(t)}))}function Pc(e,t){return new e(Ji({type:"string",coerce:!0,...I(t)}))}function Yi(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...I(t)})}function Xi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...I(t)})}function Qi(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...I(t)})}function eo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(t)})}function to(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(t)})}function no(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(t)})}function dr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...I(t)})}function ro(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...I(t)})}function io(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(t)})}function oo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...I(t)})}function ao(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(t)})}function so(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...I(t)})}function uo(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...I(t)})}function co(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(t)})}function lo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(t)})}function po(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(t)})}function Rc(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...I(t)})}function mo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(t)})}function fo(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(t)})}function go(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...I(t)})}function vo(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...I(t)})}function ho(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...I(t)})}function Cc(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...I(t)})}function Oc(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...I(t)})}function _o(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...I(t)})}var Nc={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function pr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(t)})}function mr(e,t){return new e({type:"string",format:"date",check:"string_format",...I(t)})}function fr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...I(t)})}function gr(e,t){return new e({type:"string",format:"duration",check:"string_format",...I(t)})}function Dc(e,t){return new e(Ji({type:"number",checks:[],...I(t)}))}function zc(e,t){return new e(Ji({type:"number",coerce:!0,checks:[],...I(t)}))}function Uc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...I(t)})}function Lc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...I(t)})}function jc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...I(t)})}function Mc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...I(t)})}function Fc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...I(t)})}function Zc(e,t){return new e({type:"boolean",...I(t)})}function Bc(e,t){return new e({type:"boolean",coerce:!0,...I(t)})}function Vc(e,t){return new e({type:"bigint",...I(t)})}function Gc(e,t){return new e({type:"bigint",coerce:!0,...I(t)})}function qc(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...I(t)})}function Hc(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...I(t)})}function Wc(e,t){return new e({type:"symbol",...I(t)})}function Kc(e,t){return new e({type:"undefined",...I(t)})}function Jc(e,t){return new e({type:"null",...I(t)})}function Yc(e){return new e({type:"any"})}function Xc(e){return new e({type:"unknown"})}function Qc(e,t){return new e({type:"never",...I(t)})}function el(e,t){return new e({type:"void",...I(t)})}function tl(e,t){return new e({type:"date",...I(t)})}function nl(e,t){return new e({type:"date",coerce:!0,...I(t)})}function rl(e,t){return new e({type:"nan",...I(t)})}function Le(e,t){return new vi({check:"less_than",...I(t),value:e,inclusive:!1})}function Ie(e,t){return new vi({check:"less_than",...I(t),value:e,inclusive:!0})}function je(e,t){return new hi({check:"greater_than",...I(t),value:e,inclusive:!1})}function ke(e,t){return new hi({check:"greater_than",...I(t),value:e,inclusive:!0})}function yo(e){return je(0,e)}function bo(e){return Le(0,e)}function wo(e){return Ie(0,e)}function $o(e){return ke(0,e)}function rt(e,t){return new js({check:"multiple_of",...I(t),value:e})}function it(e,t){return new Zs({check:"max_size",...I(t),maximum:e})}function Me(e,t){return new Bs({check:"min_size",...I(t),minimum:e})}function Tt(e,t){return new Vs({check:"size_equals",...I(t),size:e})}function At(e,t){return new Gs({check:"max_length",...I(t),maximum:e})}function We(e,t){return new qs({check:"min_length",...I(t),minimum:e})}function Pt(e,t){return new Hs({check:"length_equals",...I(t),length:e})}function nn(e,t){return new Ws({check:"string_format",format:"regex",...I(t),pattern:e})}function rn(e){return new Ks({check:"string_format",format:"lowercase",...I(e)})}function on(e){return new Js({check:"string_format",format:"uppercase",...I(e)})}function an(e,t){return new Ys({check:"string_format",format:"includes",...I(t),includes:e})}function sn(e,t){return new Xs({check:"string_format",format:"starts_with",...I(t),prefix:e})}function un(e,t){return new Qs({check:"string_format",format:"ends_with",...I(t),suffix:e})}function xo(e,t,r){return new eu({check:"property",property:e,schema:t,...I(r)})}function cn(e,t){return new tu({check:"properties",shape:e,...I(t)})}function ln(e,t){return new nu({check:"mime_type",mime:e,...I(t)})}function ze(e){return new ru({check:"overwrite",tx:e})}function dn(e){return ze(t=>t.normalize(e))}function pn(){return ze(e=>e.trim())}function mn(){return ze(e=>e.toLowerCase())}function fn(){return ze(e=>e.toUpperCase())}function gn(){return ze(e=>Fa(e))}function il(e,t,r){return new e({type:"array",element:t,...I(r)})}function zS(e,t,r){return new e({type:"union",options:t,...I(r)})}function US(e,t,r){return new e({type:"union",options:t,inclusive:!1,...I(r)})}function LS(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...I(o)})}function jS(e,t,r){return new e({type:"intersection",left:t,right:r})}function MS(e,t,r,o){let n=r instanceof U,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...I(i)})}function FS(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...I(o)})}function ZS(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...I(o)})}function BS(e,t,r){return new e({type:"set",valueType:t,...I(r)})}function VS(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...I(r)})}function GS(e,t,r){return new e({type:"enum",entries:t,...I(r)})}function qS(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...I(r)})}function ol(e,t){return new e({type:"file",...I(t)})}function HS(e,t){return new e({type:"transform",transform:t})}function WS(e,t){return new e({type:"optional",innerType:t})}function KS(e,t){return new e({type:"nullable",innerType:t})}function JS(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Dn(r)}})}function YS(e,t,r){return new e({type:"nonoptional",innerType:t,...I(r)})}function XS(e,t){return new e({type:"success",innerType:t})}function QS(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:Ha(r)})}function eI(e,t,r){return new e({type:"pipe",in:t,out:r})}function tI(e,t){return new e({type:"readonly",innerType:t})}function nI(e,t,r){return new e({type:"template_literal",parts:t,...I(r)})}function rI(e,t){return new e({type:"lazy",getter:t})}function iI(e,t){return new e({type:"promise",innerType:t})}function al(e,t,r){let o=I(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function sl(e,t,r){return new e({type:"custom",check:"custom",fn:t,...I(r)})}function ul(e,t){let r=kg(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(qt(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(qt(i))}},e(o.value,o)),t);return r}function kg(e,t){let r=new J({check:"custom",...I(t)});return r._zod.check=e,r}function cl(e){let t=new J({check:"describe"});return t._zod.onattach=[r=>{let o=ue.get(r)??{};ue.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function ll(e){let t=new J({check:"meta"});return t._zod.onattach=[r=>{let o=ue.get(r)??{};ue.add(r,{...o,...e})}],t._zod.check=()=>{},t}function dl(e,t){let r=I(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(o),a=new Set(n),s=e.Codec??ir,u=e.Boolean??nr,c=e.String??St,l=new c({type:"string",error:r.error}),d=new u({type:"boolean",error:r.error}),m=new s({type:"pipe",in:l,out:d,transform:((p,v)=>{let _=p;return r.case!=="sensitive"&&(_=_.toLowerCase()),i.has(_)?!0:a.has(_)?!1:(v.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:v.value,inst:m,continue:!1}),{})}),reverseTransform:((p,v)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=o,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function Rt(e,t,r,o={}){let n=I(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function vr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&se(e,o,r[o]);return e}function ot(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ue,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function re(e,t,r,o,n){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:n}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function W(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,l);else{let m=a.schema,p=t.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(e,t,m,l)}let d=e._zod.parent;d&&(a.ref||(a.ref=d),W(d,t,l),t.seen.get(d).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&vr(a.schema,u),t.io==="input"&&ge(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Eg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function at(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let u=o.get(s);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(s,a[0])}}let n=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(a[0])?.id,m=e.external.uri??(v=>v);if(d)return{ref:m(d)};let p=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=p,{defId:p,ref:`${m("__shared")}#/${s}/${Eg(p)}`}}let u="#",c=`${u}/${s}/`;if(a[1]===r&&!a[1].schema.id)return{ref:u};let l=a[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+Eg(l)}},i=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:u,defId:c}=n(a);s.def={...s.schema},c&&(s.defId=c);let l=s.schema;for(let d in l)delete l[d];l.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
69
69
 
70
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let c=e.external.registry.get(a[0])?.id;if(t!==a[0]&&c){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Pg(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Pg(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Rg=new Set(["type","properties","required","additionalProperties"]),Tg=["oneOf","anyOf"];function Ag(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function pl(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Rg.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let s=[];for(let c of t){let l=c.properties?.[a]??Ag(c);l!=null&&(s.some(d=>JSON.stringify(d)===JSON.stringify(l))||s.push(l))}let u=s.length===1?s[0]:pl(s)??{allOf:s};se(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let s=Ag(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function oI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Rg)if(n in e)return;let r=t.filter(n=>Tg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=pl(t);else{let n=r[0],i=Tg.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>pl([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,vr(e,o))}function st(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){o(d);let p=e.seen.get(d),v=p.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(v)):vr(c,v),vr(c,l),s._zod.parent===d)for(let x in c)x==="$ref"||x==="allOf"||x in l||delete c[x];if(v.$ref&&p.def)for(let x in c)x==="$ref"||x==="allOf"||x in p.def&&JSON.stringify(c[x])===JSON.stringify(p.def[x])&&delete c[x]}let m=s._zod.parent;if(m&&m!==d){o(m);let p=e.seen.get(m);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let v in c)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(c[v])===JSON.stringify(p.def[v])&&delete c[v]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Pg(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let l=c?.allOf;if(!Array.isArray(l))continue;let d=s.get(l);d?d.push(c):s.set(l,[c])}for(let u of e.intersections)for(let c of s.get(u)??[])oI(c)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}vr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,se(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:vn(t,"input",e.processors),output:vn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ge(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ge(o.element,r);if(o.type==="set")return ge(o.valueType,r);if(o.type==="lazy")return ge(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return ge(o.innerType,r);if(o.type==="intersection")return ge(o.left,r)||ge(o.right,r);if(o.type==="record"||o.type==="map")return ge(o.keyType,r)||ge(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ge(o.in,r)||ge(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ge(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ge(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ge(n,r))return!0;return!!(o.rest&&ge(o.rest,r))}return!1}var ml=(e,t={})=>r=>{let o=ot({...r,processors:t});return W(e,o),at(o,e),st(o,e)},vn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=ot({...n??{},target:i,io:t,processors:r});return W(e,a),at(a,e),st(a,e)};var hn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},_n=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Cg=(e,t)=>{hn(e,"minimum",t),_n(e,"maximum",t)},zg=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Ug=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Lg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},jg=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Og=(e,t)=>hn(e,"minimum",t.minimum),Ng=(e,t)=>_n(e,"maximum",t.maximum),Dg=e=>(t,r)=>{jg(t,r.format);let[o,n]=e[r.format];hn(t,"minimum",o),_n(t,"maximum",n)},aI={greater_than:(e,t)=>hn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>_n(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>zg(e,t.value),number_format:Dg(Un),bigint_format:Dg(Ln),min_length:Og,max_length:Ng,length_equals:(e,t)=>Cg(e,t.length),min_size:Og,max_size:Ng,size_equals:(e,t)=>Cg(e,t.size),string_format:(e,t)=>{jg(e,t.format),t.pattern&&Ug(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Lg(e,t.mime)};function ie(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)aI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&hn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&hn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&_n(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&_n(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&zg(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Lg(t,n.mime);for(let i of n.patterns??[])Ug(t,i);return t}var sI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uI=new Map([[Ei,ys],[tr,bs]]),Mg=e=>uI.get(e)??e,vl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:c,laxFormat:l}=ie(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=sI[s]??s,n.format===""&&delete n.format,(s==="time"||l)&&delete n.format),c&&(n.contentEncoding=c),u&&u.size>0){let d=[...u].map(Mg);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},hl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:c,isInt:l}=ie(e);n.type=l?"integer":"number";let d=typeof c=="number"&&c>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(n.minimum=c,n.exclusiveMinimum=!0):n.exclusiveMinimum=c:typeof i=="number"&&(n.minimum=i),m?p?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let E of s)Number.isFinite(E)&&E!==0?v.add(Math.abs(E)):re(e,t,n,o,`A multipleOf divisor of ${E} cannot be represented in JSON Schema`);let[_,...x]=v;_!==void 0&&(n.multipleOf=_),x.length&&(n.allOf=[...n.allOf??[],...x.map(E=>({multipleOf:E}))])}},_l=(e,t,r,o)=>{r.type="boolean"},yl=(e,t,r,o)=>{re(e,t,r,o,"BigInt cannot be represented in JSON Schema")},bl=(e,t,r,o)=>{re(e,t,r,o,"Symbols cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},$l=(e,t,r,o)=>{re(e,t,r,o,"Undefined cannot be represented in JSON Schema")},xl=(e,t,r,o)=>{re(e,t,r,o,"Void cannot be represented in JSON Schema")},Sl=(e,t,r,o)=>{r.not={}},Il=(e,t,r,o)=>{},kl=(e,t,r,o)=>{},El=(e,t,r,o)=>{re(e,t,r,o,"Date cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{let n=e._zod.def,i=Ft(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Al=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(re(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(re(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Pl=(e,t,r,o)=>{re(e,t,r,o,"NaN cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Cl=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ie(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},Ol=(e,t,r,o)=>{r.type="boolean"},Nl=(e,t,r,o)=>{re(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{re(e,t,r,o,"Function types cannot be represented in JSON Schema")},zl=(e,t,r,o)=>{re(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Ul=(e,t,r,o)=>{re(e,t,r,o,"Map cannot be represented in JSON Schema")},Ll=(e,t,r,o)=>{re(e,t,r,o,"Set cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ie(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=W(i.element,t,{...o,path:[...o.path,"items"]})};function hr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?hr(t.out):t.type==="catch"?hr(t.innerType):e._zod.optin}var Ml=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&re(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let c in a)se(n.properties,c,W(a[c],t,{...o,path:[...o.path,"properties",c]}));let u=[];for(let c of Object.keys(a)){let l=i.shape[c];(t.io==="input"?hr(l)===void 0:l._zod.optout===void 0)&&u.push(c)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=W(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Io=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>W(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Fl=(e,t,r,o)=>{let n=e._zod.def,i=W(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=W(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},Zl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((_,x)=>W(_,t,{...o,path:[...o.path,a,x]})),c=i.rest?W(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let _=i.items[l-1];if(!(t.io==="input"?hr(_)!==void 0:_._zod.optout==="optional"))break;l--}let d=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:c&&(n.items=c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:u},c&&n.items.anyOf.push(c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):(n.items=u,m?n.additionalItems=!1:c&&(n.additionalItems=c),l>0&&(n.minItems=l),m&&(n.maxItems=d));let{minimum:p,maximum:v}=ie(e);typeof p=="number"&&(n.minItems=p),typeof v=="number"&&(n.maxItems=v)};function fl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let v=e.get(t)?.def;if(!v)return t;let _=fl(e,v,r);return _===v?t:_}for(let v of["anyOf","oneOf"]){let _=t[v];if(!Array.isArray(_))continue;let x=_.map(E=>fl(e,E,r));x.some((E,k)=>E!==_[k])&&(t={...t,[v]:x})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(v=>v==="number"||v==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(v=>typeof v=="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:l,format:d,id:m,...p}=t;return p.enum?p.enum=p.enum.map(v=>typeof v=="number"?String(v):v):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?He:Wn).source)),p}var gl=new WeakMap;function cI(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of gl.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=fl(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var Bl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ie(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let l=W(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of s)se(n.patternProperties,Mg(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=W(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let l=gl.get(t);l||(l=[],gl.set(t,l),t.deferred.push(()=>cI(t))),l.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=t.io==="input"&&hr(i.valueType)!==void 0;if(u&&!i.partial&&!c){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},Vl=(e,t,r,o)=>{let n=e._zod.def,i=W(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Gl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ql=Symbol();function Fg(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(re(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),ql):JSON.parse(a)}var Hl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Fg(n.defaultValue,e,t,r,o);a!==ql&&(r.default=a)},Wl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Fg(n.defaultValue,e,t,r,o);a!==ql&&(r._prefault=a)},Kl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{re(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Jl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;W(a,t,o);let s=t.seen.get(e);s.ref=a},Yl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Xl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ko=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ql=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},So={string:vl,number:hl,boolean:_l,bigint:yl,symbol:bl,null:wl,undefined:$l,void:xl,never:Sl,any:Il,unknown:kl,date:El,enum:Tl,literal:Al,nan:Pl,template_literal:Rl,file:Cl,success:Ol,custom:Nl,function:Dl,transform:zl,map:Ul,set:Ll,array:jl,object:Ml,union:Io,intersection:Fl,tuple:Zl,record:Bl,nullable:Vl,nonoptional:Gl,default:Hl,prefault:Wl,catch:Kl,pipe:Jl,readonly:Yl,promise:Xl,optional:ko,lazy:Ql};function Eo(e,t){if("_idmap"in e){let o=e,n=ot({...t,processors:So}),i={};for(let u of o._idmap.entries()){let[c,l]=u;W(l,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[c,l]=u;at(n,l),se(a,c,st(n,l))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=ot({...t,processors:So});return W(e,r),at(r,e),st(r,e)}var To=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ot({processors:So,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return W(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,at(this.ctx,t);let o=st(this.ctx,t),{"~standard":n,...i}=o;return i}};var Zg={};var kn={};Be(kn,{ZodAny:()=>wd,ZodArray:()=>Id,ZodBase64:()=>Ho,ZodBase64URL:()=>Wo,ZodBigInt:()=>Sn,ZodBigIntFormat:()=>Yo,ZodBoolean:()=>xn,ZodCIDRv4:()=>Go,ZodCIDRv6:()=>qo,ZodCUID:()=>Lo,ZodCUID2:()=>jo,ZodCatch:()=>qd,ZodCodec:()=>Er,ZodCreditCard:()=>md,ZodCustom:()=>Tr,ZodCustomStringFormat:()=>Dt,ZodDate:()=>wr,ZodDefault:()=>Md,ZodDiscriminatedUnion:()=>Ed,ZodE164:()=>Ko,ZodEmail:()=>No,ZodEmoji:()=>zo,ZodEnum:()=>bn,ZodExactOptional:()=>ta,ZodFile:()=>zd,ZodFunction:()=>np,ZodGUID:()=>Do,ZodIBAN:()=>fd,ZodIPv4:()=>Bo,ZodIPv6:()=>Vo,ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,ZodInstanceOf:()=>op,ZodIntersection:()=>Td,ZodJWT:()=>Jo,ZodKSUID:()=>Zo,ZodLazy:()=>Qd,ZodLiteral:()=>Dd,ZodMAC:()=>pd,ZodMap:()=>Od,ZodNaN:()=>Wd,ZodNanoID:()=>Uo,ZodNever:()=>xd,ZodNonOptional:()=>na,ZodNull:()=>yd,ZodNullable:()=>jd,ZodNumber:()=>$n,ZodNumberFormat:()=>zt,ZodObject:()=>xr,ZodOptional:()=>Ir,ZodPipe:()=>kr,ZodPrefault:()=>Zd,ZodPreprocess:()=>Kd,ZodPromise:()=>tp,ZodReadonly:()=>Jd,ZodRecord:()=>yn,ZodSet:()=>Nd,ZodString:()=>wn,ZodStringFormat:()=>K,ZodSuccess:()=>Gd,ZodSymbol:()=>hd,ZodTemplateLiteral:()=>Xd,ZodTransform:()=>Ud,ZodTuple:()=>Pd,ZodType:()=>L,ZodULID:()=>Mo,ZodURL:()=>br,ZodUUID:()=>Fe,ZodUndefined:()=>_d,ZodUnion:()=>Sr,ZodUnknown:()=>$d,ZodVoid:()=>Sd,ZodXID:()=>Fo,ZodXor:()=>kd,_ZodString:()=>Oo,_default:()=>Fd,_function:()=>eh,any:()=>Rv,array:()=>$r,base64:()=>dv,base64url:()=>pv,bigint:()=>kv,boolean:()=>vd,catch:()=>Hd,check:()=>th,cidrv4:()=>cv,cidrv6:()=>lv,codec:()=>Jv,creditCard:()=>fv,cuid:()=>tv,cuid2:()=>nv,currencyCode:()=>bv,custom:()=>nh,date:()=>Ov,describe:()=>rh,discriminatedUnion:()=>jv,e164:()=>mv,email:()=>Gg,emoji:()=>Qg,enum:()=>Qo,exactOptional:()=>Ld,file:()=>qv,float32:()=>$v,float64:()=>xv,function:()=>eh,guid:()=>qg,hash:()=>wv,hex:()=>yv,hostname:()=>_v,httpUrl:()=>Xg,iban:()=>gv,instanceof:()=>oh,int:()=>Ro,int32:()=>Sv,int64:()=>Ev,intersection:()=>Ad,invertCodec:()=>Yv,ipv4:()=>av,ipv6:()=>uv,json:()=>sh,jwt:()=>vv,keyof:()=>Nv,ksuid:()=>ov,lazy:()=>ep,literal:()=>Gv,looseObject:()=>Uv,looseRecord:()=>Fv,mac:()=>sv,map:()=>Zv,meta:()=>ih,nan:()=>Kv,nanoid:()=>ev,nativeEnum:()=>Vv,never:()=>Xo,nonoptional:()=>Vd,null:()=>bd,nullable:()=>yr,nullish:()=>Hv,number:()=>gd,object:()=>Dv,optional:()=>Ot,partialRecord:()=>Mv,pipe:()=>Co,prefault:()=>Bd,preprocess:()=>uh,promise:()=>Qv,readonly:()=>Yd,record:()=>Cd,refine:()=>rp,set:()=>Bv,strictObject:()=>zv,string:()=>_r,stringFormat:()=>hv,stringbool:()=>ah,success:()=>Wv,superRefine:()=>ip,symbol:()=>Av,templateLiteral:()=>Xv,transform:()=>ea,tuple:()=>Rd,uint32:()=>Iv,uint64:()=>Tv,ulid:()=>rv,undefined:()=>Pv,union:()=>In,unknown:()=>Ct,url:()=>Yg,uuid:()=>Hg,uuidv4:()=>Wg,uuidv6:()=>Kg,uuidv7:()=>Jg,void:()=>Cv,xid:()=>iv,xor:()=>Lv});var Ao={};Be(Ao,{endsWith:()=>un,gt:()=>je,gte:()=>ke,includes:()=>an,length:()=>Pt,lowercase:()=>rn,lt:()=>Le,lte:()=>Ie,maxLength:()=>At,maxSize:()=>it,mime:()=>ln,minLength:()=>We,minSize:()=>Me,multipleOf:()=>rt,negative:()=>bo,nonnegative:()=>$o,nonpositive:()=>wo,normalize:()=>dn,overwrite:()=>ze,positive:()=>yo,properties:()=>cn,property:()=>xo,regex:()=>nn,size:()=>Tt,slugify:()=>gn,startsWith:()=>sn,toLowerCase:()=>mn,toUpperCase:()=>fn,trim:()=>pn,uppercase:()=>on});var Bg=new WeakSet([Object.prototype,Error.prototype]);function Po(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Vg=(e,t)=>{Qa.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Bg.has(r)||(Bg.add(r),Po(r,"format",o=>n=>Vn(o,n)),Po(r,"flatten",o=>n=>Bn(o,n)),Po(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Zt,2)}),Po(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Zt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},dI=g("ZodError",Vg),$e=g("ZodError",Vg,void 0,{Parent:Error});var ed=Ht($e),td=Wt($e),nd=Kt($e),rd=Jt($e),id=ii($e),od=oi($e),ad=ai($e),sd=si($e),ud=ui($e),cd=ci($e),ld=li($e),dd=di($e);function mI(){oe.localeError||te(Bi())}function Nt(){oe.memoizer||te({memoizer:ur()})}var L=g("ZodType",(e,t)=>(mI(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return q(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rp(e,t))},superRefine(e,t){return this.check(ip(e,t))},overwrite(e){return this.check(ze(e))},optional(){return Ot(this)},exactOptional(){return Ld(this)},nullable(){return yr(this)},nullish(){return Ot(yr(this))},nonoptional(e){return Vd(this,e)},array(){return $r(this)},or(e){return In([this,e])},and(e){return Ad(this,e)},transform(e){return Co(this,ea(e))},default(e){return Fd(this,e)},prefault(e){return Bd(this,e)},catch(e){return Hd(this,e)},pipe(e){return Co(this,e)},readonly(){return Yd(this)},describe(e){let t=this.clone();return ue.add(t,{description:e}),t},meta(...e){if(e.length===0)return ue.get(this);let t=this.clone();return ue.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return b.hide(this,"~standard",{...$i(this),jsonSchema:{input:vn(this,"input"),output:vn(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return ed(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await td(this,t,r,{callee:e})},safeParse(e,t){return nd(this,e,t)},async safeParseAsync(e,t){return rd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return Gn(this,e,t)},validateAsync(e,t){return qn(this,e,t)},encode:function e(t,r){return id(this,t,r,{callee:e})},decode:function e(t,r){return od(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ad(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await sd(this,t,r,{callee:e})},safeEncode(e,t){return ud(this,e,t)},safeDecode(e,t){return cd(this,e,t)},async safeEncodeAsync(e,t){return ld(this,e,t)},async safeDecodeAsync(e,t){return dd(this,e,t)},toJSONSchema(e){return ml(this,{})(e)},get description(){return ue.get(this)?.description},get _def(){return this._zod.def}}),Oo=g("_ZodString",(e,t)=>{St.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)},b.derived({format:e=>ie(e).format??null,minLength:e=>ie(e).minimum??null,maxLength:e=>ie(e).maximum??null},{regex(...e){return this.check(nn(...e))},includes(...e){return this.check(an(...e))},startsWith(...e){return this.check(sn(...e))},endsWith(...e){return this.check(un(...e))},min(...e){return this.check(We(...e))},max(...e){return this.check(At(...e))},length(...e){return this.check(Pt(...e))},nonempty(...e){return this.check(We(1,...e))},lowercase(e){return this.check(rn(e))},uppercase(e){return this.check(on(e))},trim(){return this.check(pn())},normalize(...e){return this.check(dn(...e))},toLowerCase(){return this.check(mn())},toUpperCase(){return this.check(fn())},slugify(){return this.check(gn())}})),wn=g("ZodString",(e,t)=>{St.init(e,t),Oo.init(e,t)},{email(e){return this.check(Yi(No,e))},url(e){return this.check(dr(br,e))},jwt(e){return this.check(_o(Jo,e))},emoji(e){return this.check(ro(zo,e))},guid(e){return this.check(Xi(Do,e))},uuid(e){return this.check(Qi(Fe,e))},uuidv4(e){return this.check(eo(Fe,e))},uuidv6(e){return this.check(to(Fe,e))},uuidv7(e){return this.check(no(Fe,e))},nanoid(e){return this.check(io(Uo,e))},cuid(e){return this.check(oo(Lo,e))},cuid2(e){return this.check(ao(jo,e))},ulid(e){return this.check(so(Mo,e))},base64(e){return this.check(go(Ho,e))},base64url(e){return this.check(vo(Wo,e))},xid(e){return this.check(uo(Fo,e))},ksuid(e){return this.check(co(Zo,e))},ipv4(e){return this.check(lo(Bo,e))},ipv6(e){return this.check(po(Vo,e))},cidrv4(e){return this.check(mo(Go,e))},cidrv6(e){return this.check(fo(qo,e))},e164(e){return this.check(ho(Ko,e))},datetime(e){return this.check(pr(ut,e))},date(e){return this.check(mr(ct,e))},time(e){return this.check(fr(lt,e))},duration(e){return this.check(gr(dt,e))}});function _r(e){return Ac(wn,e)}var K=g("ZodStringFormat",(e,t)=>{H.init(e,t),Oo.init(e,t)}),ut=g("ZodISODateTime",(e,t)=>{yu.init(e,t),K.init(e,t)}),ct=g("ZodISODate",(e,t)=>{bu.init(e,t),K.init(e,t)}),lt=g("ZodISOTime",(e,t)=>{wu.init(e,t),K.init(e,t)}),dt=g("ZodISODuration",(e,t)=>{$u.init(e,t),K.init(e,t)}),No=g("ZodEmail",(e,t)=>{uu.init(e,t),K.init(e,t)});function Gg(e){return Yi(No,e)}var Do=g("ZodGUID",(e,t)=>{au.init(e,t),K.init(e,t)});function qg(e){return Xi(Do,e)}var Fe=g("ZodUUID",(e,t)=>{su.init(e,t),K.init(e,t)});function Hg(e){return Qi(Fe,e)}function Wg(e){return eo(Fe,e)}function Kg(e){return to(Fe,e)}function Jg(e){return no(Fe,e)}var br=g("ZodURL",(e,t)=>{du.init(e,t),K.init(e,t)});function Yg(e){return dr(br,e)}function Xg(e){return dr(br,{protocol:Hn,hostname:$s,...b.normalizeParams(e)})}var zo=g("ZodEmoji",(e,t)=>{pu.init(e,t),K.init(e,t)});function Qg(e){return ro(zo,e)}var Uo=g("ZodNanoID",(e,t)=>{mu.init(e,t),K.init(e,t)});function ev(e){return io(Uo,e)}var Lo=g("ZodCUID",(e,t)=>{fu.init(e,t),K.init(e,t)});function tv(e){return oo(Lo,e)}var jo=g("ZodCUID2",(e,t)=>{gu.init(e,t),K.init(e,t)});function nv(e){return ao(jo,e)}var Mo=g("ZodULID",(e,t)=>{vu.init(e,t),K.init(e,t)});function rv(e){return so(Mo,e)}var Fo=g("ZodXID",(e,t)=>{hu.init(e,t),K.init(e,t)});function iv(e){return uo(Fo,e)}var Zo=g("ZodKSUID",(e,t)=>{_u.init(e,t),K.init(e,t)});function ov(e){return co(Zo,e)}var Bo=g("ZodIPv4",(e,t)=>{xu.init(e,t),K.init(e,t)});function av(e){return lo(Bo,e)}var pd=g("ZodMAC",(e,t)=>{Iu.init(e,t),K.init(e,t)});function sv(e){return Rc(pd,e)}var Vo=g("ZodIPv6",(e,t)=>{Su.init(e,t),K.init(e,t)});function uv(e){return po(Vo,e)}var Go=g("ZodCIDRv4",(e,t)=>{ku.init(e,t),K.init(e,t)});function cv(e){return mo(Go,e)}var qo=g("ZodCIDRv6",(e,t)=>{Eu.init(e,t),K.init(e,t)});function lv(e){return fo(qo,e)}var Ho=g("ZodBase64",(e,t)=>{Tu.init(e,t),K.init(e,t)});function dv(e){return go(Ho,e)}var Wo=g("ZodBase64URL",(e,t)=>{Au.init(e,t),K.init(e,t)});function pv(e){return vo(Wo,e)}var Ko=g("ZodE164",(e,t)=>{Pu.init(e,t),K.init(e,t)});function mv(e){return ho(Ko,e)}var md=g("ZodCreditCard",(e,t)=>{Ru.init(e,t),K.init(e,t)});function fv(e){return Cc(md,e)}var fd=g("ZodIBAN",(e,t)=>{Cu.init(e,t),K.init(e,t)});function gv(e){return Oc(fd,e)}var Jo=g("ZodJWT",(e,t)=>{Ou.init(e,t),K.init(e,t)});function vv(e){return _o(Jo,e)}var Dt=g("ZodCustomStringFormat",(e,t)=>{Nu.init(e,t),K.init(e,t)});function hv(e,t,r={}){return Rt(Dt,e,t,r)}function _v(e){return Rt(Dt,"hostname",ws,e)}function yv(e){return Rt(Dt,"hex",zs,e)}function bv(e){return Rt(Dt,"currency_code",Ss,e)}function wv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Re[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Rt(Dt,o,n,t)}var $n=g("ZodNumber",(e,t)=>{Ci.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hl(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ie(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ie(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ie(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ie(e).format??null},{gt(e,t){return this.check(je(e,t))},gte(e,t){return this.check(ke(e,t))},min(e,t){return this.check(ke(e,t))},lt(e,t){return this.check(Le(e,t))},lte(e,t){return this.check(Ie(e,t))},max(e,t){return this.check(Ie(e,t))},int(e){return this.check(Ro(e))},safe(e){return this.check(Ro(e))},positive(e){return this.check(je(0,e))},nonnegative(e){return this.check(ke(0,e))},negative(e){return this.check(Le(0,e))},nonpositive(e){return this.check(Ie(0,e))},multipleOf(e,t){return this.check(rt(e,t))},step(e,t){return this.check(rt(e,t))},finite(){return this}}));function gd(e){return Dc($n,e)}var zt=g("ZodNumberFormat",(e,t)=>{Du.init(e,t),$n.init(e,t)});function Ro(e){return Uc(zt,e)}function $v(e){return Lc(zt,e)}function xv(e){return jc(zt,e)}function Sv(e){return Mc(zt,e)}function Iv(e){return Fc(zt,e)}var xn=g("ZodBoolean",(e,t)=>{nr.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_l(e,r,o,n)});function vd(e){return Zc(xn,e)}var Sn=g("ZodBigInt",(e,t)=>{Oi.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yl(e,r,o,n)},b.derived({minValue:e=>ie(e).minimum??null,maxValue:e=>ie(e).maximum??null,format:e=>ie(e).format??null},{gte(e,t){return this.check(ke(e,t))},min(e,t){return this.check(ke(e,t))},gt(e,t){return this.check(je(e,t))},lt(e,t){return this.check(Le(e,t))},lte(e,t){return this.check(Ie(e,t))},max(e,t){return this.check(Ie(e,t))},positive(e){return this.check(je(BigInt(0),e))},negative(e){return this.check(Le(BigInt(0),e))},nonpositive(e){return this.check(Ie(BigInt(0),e))},nonnegative(e){return this.check(ke(BigInt(0),e))},multipleOf(e,t){return this.check(rt(e,t))}}));function kv(e){return Vc(Sn,e)}var Yo=g("ZodBigIntFormat",(e,t)=>{zu.init(e,t),Sn.init(e,t)});function Ev(e){return qc(Yo,e)}function Tv(e){return Hc(Yo,e)}var hd=g("ZodSymbol",(e,t)=>{Uu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bl(e,r,o,n)});function Av(e){return Wc(hd,e)}var _d=g("ZodUndefined",(e,t)=>{Lu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n)});function Pv(e){return Kc(_d,e)}var yd=g("ZodNull",(e,t)=>{ju.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function bd(e){return Jc(yd,e)}var wd=g("ZodAny",(e,t)=>{Mu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function Rv(){return Yc(wd)}var $d=g("ZodUnknown",(e,t)=>{Fu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)});function Ct(){return Xc($d)}var xd=g("ZodNever",(e,t)=>{Zu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sl(e,r,o,n)});function Xo(e){return Qc(xd,e)}var Sd=g("ZodVoid",(e,t)=>{Bu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Cv(e){return el(Sd,e)}var wr=g("ZodDate",(e,t)=>{Vu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.min=(r,o)=>e.check(ke(r,o)),e.max=(r,o)=>e.check(Ie(r,o))},b.derived({minDate:e=>{let{minimum:t}=ie(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ie(e);return t?new Date(t):null}},{}));function Ov(e){return tl(wr,e)}var Id=g("ZodArray",(e,t)=>{Nt(),qu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.element=t.element},{min(e,t){return this.check(We(e,t))},nonempty(e){return this.check(We(1,e))},max(e,t){return this.check(At(e,t))},length(e,t){return this.check(Pt(e,t))},unwrap(){return this.element}});function $r(e,t){return il(Id,e,t)}function Nv(e){let t=e._zod.def.shape;return Qo(Object.keys(t))}var xr=g("ZodObject",(e,t)=>{Nt(),Hu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Qo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ct()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ct()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Xo()}))},strip(){return this.clone(b.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return b.extend(this,e)},safeExtend(e){return b.safeExtend(this,e)},merge(e){return b.merge(this,e)},pick(e){return b.pick(this,e)},omit(e){return b.omit(this,e)},partial(...e){return b.partial(Ir,this,e[0])},exactPartial(...e){return b.partial(ta,this,e[0],"exactPartial")},required(...e){return b.required(na,this,e[0])}});function Dv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new xr(r)}function zv(e,t){return new xr({type:"object",shape:e,catchall:Xo(),...b.normalizeParams(t)})}function Uv(e,t){return new xr({type:"object",shape:e,catchall:Ct(),...b.normalizeParams(t)})}var Sr=g("ZodUnion",(e,t)=>{rr.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Io(e,r,o,n),e.options=t.options});function In(e,t){return new Sr({type:"union",options:e,...b.normalizeParams(t)})}var kd=g("ZodXor",(e,t)=>{Sr.init(e,t),Wu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Io(e,r,o,n),e.options=t.options});function Lv(e,t){return new kd({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var Ed=g("ZodDiscriminatedUnion",(e,t)=>{Sr.init(e,t),Ju.init(e,t)});function jv(e,t,r){return new Ed({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var Td=g("ZodIntersection",(e,t)=>{Yu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function Ad(e,t){return new Td({type:"intersection",left:e,right:t})}var Pd=g("ZodTuple",(e,t)=>{Nt(),Ni.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Ir({type:"optional",innerType:t}))})}});function Rd(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new Pd({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var yn=g("ZodRecord",(e,t)=>{Nt(),Xu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Cd(e,t,r){return!t||!t._zod?new yn({type:"record",keyType:_r(),valueType:e,...b.normalizeParams(t)}):new yn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function Mv(e,t,r){return new yn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Fv(e,t,r){return new yn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var Od=g("ZodMap",(e,t)=>{Nt(),Qu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(Tt(...r))});function Zv(e,t,r){return new Od({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var Nd=g("ZodSet",(e,t)=>{Nt(),ec.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(Tt(...r))});function Bv(e,t){return new Nd({type:"set",valueType:e,...b.normalizeParams(t)})}var bn=g("ZodEnum",(e,t)=>{tc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Tl(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new bn({...t,checks:[],...b.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new bn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function Qo(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new bn({type:"enum",entries:r,...b.normalizeParams(t)})}function Vv(e,t){return new bn({type:"enum",entries:e,...b.normalizeParams(t)})}var Dd=g("ZodLiteral",(e,t)=>{nc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Gv(e,t){return new Dd({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var zd=g("ZodFile",(e,t)=>{rc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e.min=(r,o)=>e.check(Me(r,o)),e.max=(r,o)=>e.check(it(r,o)),e.mime=(r,o)=>e.check(ln(Array.isArray(r)?r:[r],o))});function qv(e){return ol(zd,e)}var Ud=g("ZodTransform",(e,t)=>{Nt(),ic.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new tt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(b.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push(b.issue(a))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ea(e){return new Ud({type:"transform",transform:e})}var Ir=g("ZodOptional",(e,t)=>{Di.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ot(e){return new Ir({type:"optional",innerType:e})}var ta=g("ZodExactOptional",(e,t)=>{oc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ld(e){return new ta({type:"optional",innerType:e})}var jd=g("ZodNullable",(e,t)=>{ac.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new jd({type:"nullable",innerType:e})}function Hv(e){return Ot(yr(e))}var Md=g("ZodDefault",(e,t)=>{sc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Fd(e,t){return new Md({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Zd=g("ZodPrefault",(e,t)=>{uc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bd(e,t){return new Zd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var na=g("ZodNonOptional",(e,t)=>{cc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Vd(e,t){return new na({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Gd=g("ZodSuccess",(e,t)=>{lc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Wv(e){return new Gd({type:"success",innerType:e})}var qd=g("ZodCatch",(e,t)=>{dc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Hd(e,t){return new qd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Wd=g("ZodNaN",(e,t)=>{pc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Kv(e){return rl(Wd,e)}var kr=g("ZodPipe",(e,t)=>{zi.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.in=t.in,e.out=t.out});function Co(e,t){return new kr({type:"pipe",in:e,out:t})}var Er=g("ZodCodec",(e,t)=>{kr.init(e,t),ir.init(e,t)});function Jv(e,t,r){return new Er({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Yv(e){let t=e._zod.def;return new Er({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Kd=g("ZodPreprocess",(e,t)=>{kr.init(e,t),mc.init(e,t)}),Jd=g("ZodReadonly",(e,t)=>{fc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Yd(e){return new Jd({type:"readonly",innerType:e})}var Xd=g("ZodTemplateLiteral",(e,t)=>{gc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Xv(e,t){return new Xd({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Qd=g("ZodLazy",(e,t)=>{or.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function ep(e){return new Qd({type:"lazy",getter:e})}var tp=g("ZodPromise",(e,t)=>{hc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qv(e){return new tp({type:"promise",innerType:e})}var np=g("ZodFunction",(e,t)=>{vc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n)});function eh(e){return new np({type:"function",input:Array.isArray(e?.input)?Rd(e?.input):e?.input??$r(Ct()),output:e?.output??Ct()})}var Tr=g("ZodCustom",(e,t)=>{_c.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function th(e){let t=new J({check:"custom"});return t._zod.check=e,t}function nh(e,t){return al(Tr,e??(()=>!0),t)}function rp(e,t={}){return sl(Tr,e,t)}function ip(e,t){return ul(e,t)}var rh=cl,ih=ll,op=g("ZodInstanceOf",(e,t)=>{Tr.init(e,t)},{properties(e,t){return this.check(cn(e,t))}});function oh(e,t={}){let r=new op({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...b.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var ah=(...e)=>dl({Codec:Er,Boolean:xn,String:wn},...e);function sh(e){let t=ep(()=>In([_r(e),gd(),vd(),bd(),$r(t),Cd(_r(),t)]));return t}function uh(e,t){return new Kd({type:"pipe",in:ea(e),out:t})}var fI={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function gI(e){te({customError:e})}function vI(){return te().customError}var ap;ap||(ap={});var Ar={};Be(Ar,{ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,date:()=>_I,datetime:()=>hI,duration:()=>bI,time:()=>yI});function hI(e){return pr(ut,e)}function _I(e){return mr(ct,e)}function yI(e){return fr(lt,e)}function bI(e){return gr(dt,e)}var T={...kn,...Ao,iso:Ar},wI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function $I(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function ch(e,t){return e.map((r,o)=>o<t?r:r.optional())}function xI(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function SI(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:xI(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function II(e,t){return T.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function sp(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let s=sp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=sp(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var kI=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),EI=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Pr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Pr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>kI.has(t)?Pr(r):!EI.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Pr))}function lh(e){return e===1?"element":"elements"}function TI(e,t){return T.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let s=sp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${lh(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${lh(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function dh(e,t){if(e!==!1)return e===void 0||e===!0?T.any():ve(e,t)}var AI=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function ph(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return T.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return T.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=SI(n,t),a=ve(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return T.null();if(n.length===0)return T.never();if(n.length===1)return T.literal(n[0]);if(n.every(a=>typeof a=="string"))return T.enum(n);let i=n.map(a=>T.literal(a));return i.length<2?i[0]:T.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return T.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return ph(a,t)});return n.length===0?T.never():n.length===1?n[0]:T.union(n)}if(!r)return T.any();let o;switch(r){case"string":{let n=T.string();if(e.format){let i=e.format;i==="email"?n=n.check(T.email()):i==="uri"||i==="uri-reference"?n=n.check(T.url()):i==="uuid"||i==="guid"?n=n.check(T.uuid()):i==="date-time"?n=n.check(T.iso.datetime({offset:!0})):i==="date"?n=n.check(T.iso.date()):i==="time"?n=n.check(T.regex(AI)):i==="duration"?n=n.check(T.iso.duration()):i==="hostname"?n=n.check(T.hostname()):i==="ipv4"?n=n.check(T.ipv4()):i==="ipv6"?n=n.check(T.ipv6()):i==="mac"?n=n.check(T.mac()):i==="cidr"?n=n.check(T.cidrv4()):i==="cidr-v6"?n=n.check(T.cidrv6()):i==="base64"?n=n.check(T.base64()):i==="base64url"?n=n.check(T.base64url()):i==="e164"?n=n.check(T.e164()):i==="credit_card"?n=n.check(T.creditCard()):i==="iban"?n=n.check(T.iban()):i==="jwt"?n=n.check(T.jwt()):i==="emoji"?n=n.check(T.emoji()):i==="nanoid"?n=n.check(T.nanoid()):i==="cuid"?n=n.check(T.cuid()):i==="cuid2"?n=n.check(T.cuid2()):i==="ulid"?n=n.check(T.ulid()):i==="xid"?n=n.check(T.xid()):i==="ksuid"&&(n=n.check(T.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?T.number().int():T.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=T.boolean();break}case"null":{o=T.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ve(e.additionalProperties,t):void 0;for(let[d,m]of Object.entries(i)){let p=ve(m,t);se(n,d,a.has(d)?p:p.optional())}if(e.patternProperties){let d=e.patternProperties,m=Object.keys(d),p=[];for(let _ of m){let x=ve(d[_],t),E=T.string().regex(new RegExp(_));p.push(T.looseRecord(E,x))}let v=[];if(Object.keys(n).length>0&&v.push(T.object(n).passthrough()),v.push(...p),v.length===0)o=T.object({}).passthrough();else if(v.length===1)o=v[0];else{let _=T.intersection(v[0],v[1]);for(let x=2;x<v.length;x++)_=T.intersection(_,v[x]);o=_}if(e.additionalProperties===!1){let _=Object.keys(n),x=m.map(k=>new RegExp(k)),E=o;o=o.check(k=>{if(!Ae(k.value))return;let A=[];for(let S of Object.keys(k.value))_.includes(S)||x.some(O=>O.test(S))||A.push(S);A.length&&k.issues.push({code:"unrecognized_keys",keys:A,input:k.value,inst:E})})}}else{let d=T.object(n);e.additionalProperties===!1?o=d.strict():s?o=d.catchall(s):o=d.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||l!==void 0){let d;if(u){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=ve(m,t)}o=II(o,{keySchema:d,minProperties:c,maxProperties:l})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(d=>ve(d,t)),u=ch(s,a),c=Array.isArray(i)?void 0:dh(i,t),l=T.tuple(u);o=c?l.rest(c):l,typeof e.minItems=="number"&&(o=o.check(T.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(T.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(d=>ve(d,t)),u=ch(s,a),c=dh(e.additionalItems,t),l=T.tuple(u);o=c?l.rest(c):l,typeof e.minItems=="number"&&(o=o.check(T.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(T.maxLength(e.maxItems)))}else if(i!==void 0){let a=ve(i,t),s=T.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=T.array(T.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=TI(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ve(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function ve(e,t){if(typeof e=="boolean")return e?T.any():T.never();let r=ph(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(c=>ve(c,t)),u=T.union(s);r=o?T.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(c=>ve(c,t)),u=T.xor(s);r=o?T.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:T.any();else{let s=o?r:ve(e.allOf[0],t),u=o?0:1;for(let c=u;c<e.allOf.length;c++)s=T.intersection(s,ve(e.allOf[c],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=T.nullable(r)),e.readOnly===!0&&(r=T.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Pr(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Pr(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))wI.has(s)||se(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function mh(e,t){if(typeof e=="boolean")return e?T.any():T.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=$I(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??ue};return ve(r,i)}var fh=Symbol("z.visit/resolving");function Rr(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===fh)return new or({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,fh);let u=i(a),c=r(u,u!==a);return o.set(a,c),c}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,l=Object.keys(c),d=!1,m={};for(let v of l){let _=n(c[v]);_!==c[v]&&(d=!0),m[v]=_}let p=s.catchall;return s.catchall&&(p=n(s.catchall),p!==s.catchall&&(d=!0)),d?q(a,{...s,shape:m,catchall:p}):a}case"array":{let c=n(s.element);return c===s.element?a:q(a,{...s,element:c})}case"tuple":{let c=s.items,l=!1,d=[];for(let p of c){let v=n(p);v!==p&&(l=!0),d.push(v)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(l=!0)),l?q(a,{...s,items:d,rest:m}):a}case"record":case"map":{let c=n(s.keyType),l=n(s.valueType);return c===s.keyType&&l===s.valueType?a:q(a,{...s,keyType:c,valueType:l})}case"set":{let c=n(s.valueType);return c===s.valueType?a:q(a,{...s,valueType:c})}case"union":{let c=s.options,l=!1,d=[];for(let m of c){let p=n(m);p!==m&&(l=!0),d.push(p)}return l?q(a,{...s,options:d}):a}case"intersection":{let c=n(s.left),l=n(s.right);return c===s.left&&l===s.right?a:q(a,{...s,left:c,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=n(s.innerType);return c===s.innerType?a:q(a,{...s,innerType:c})}case"pipe":{let c=n(s.in),l=n(s.out);return c===s.in&&l===s.out?a:q(a,{...s,in:c,out:l})}case"function":{let c=n(s.input),l=n(s.output);return c===s.input&&l===s.output?a:q(a,{...s,input:c,output:l})}case"lazy":{let c=s.getter,{_cachedInner:l,...d}=s;return q(a,{...d,getter:()=>n(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function gh(e){return Rr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:In(r.options)}})}function PI(e,t){if(!t?.length)return e;let r=e._zod.def;return q(e,Ne(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function vh(e){return PI(e.out,e.checks)}function RI(e){return e.in._zod.traits.has("$ZodTransform")?vh(e):e.in}function hh(e){return Rr(e,{pipe:t=>RI(t._zod.def),default:(t,r)=>r?Ot(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function _h(e){return Rr(e,{pipe:t=>vh(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var up={};Be(up,{bigint:()=>DI,boolean:()=>NI,date:()=>zI,number:()=>OI,string:()=>CI});function CI(e){return Pc(wn,e)}function OI(e){return zc($n,e)}function NI(e){return Bc(xn,e)}function DI(e){return Gc(Sn,e)}function zI(e){return nl(wr,e)}var UI=f.object({id:f.string().regex(/^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/).max(120),scope:f.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/)}).strict(),yh=f.array(UI).max(8).superRefine((e,t)=>{let r=e.map(({id:o,scope:n})=>`${o}:${n}`);new Set(r).size!==r.length&&t.addIssue({code:"custom",message:"Duplicate fixture binding"})});function cp(e){return new TextEncoder().encode(e).byteLength}var bh=128*1024,wh=512*1024,$h=64,xh=f.string().max(240).regex(/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*(\/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*)*$/,"Use a relative file path such as db/restore.py; absolute paths and dot segments are not allowed"),Sh=f.string().refine(e=>cp(e)<=bh&&!e.includes("\0"),`File contents must be text without null bytes, at most ${bh} UTF-8 bytes`),CD=f.record(xh,Sh.nullable()),lp=f.record(xh,Sh).superRefine((e,t)=>{let r=Object.keys(e);(r.length>$h||Object.values(e).reduce((o,n)=>o+cp(n),0)>wh)&&t.addIssue({code:"custom",message:`Save at most ${$h} helper files totaling ${wh} UTF-8 bytes`});for(let o of r){let n=o.split("/");for(let i=1;i<n.length;i++)Object.prototype.hasOwnProperty.call(e,n.slice(0,i).join("/"))&&t.addIssue({code:"custom",message:`File ${o} has a parent that is also a file`})}});var LI=/'/g,jI=/^[A-Za-z0-9_./:=@,+-]+$/,ra=/^[A-Za-z_][A-Za-z0-9_]*$/;function MI(e){return`'${e.replace(LI,"'\\''")}'`}function pt(e){return e===""?"''":jI.test(e)?e:MI(e)}var FI=12,ZI=10;var BI=f.object({name:f.string().regex(ra).max(128),description:f.string().trim().min(1).max(300),values:f.array(f.string().min(1).max(200)).min(2).max(ZI).describe("Public non-secret setting values. Sent to QA models and shown in GitHub results.").optional()}).strict(),Ih=f.array(BI).max(FI);var Cr={Compose:"compose",Command:"command"};var kh=8,VI=64,Ah=/^\/workspace\/(?!\.+$)(?!.*\.\.)[A-Za-z0-9._-]+$/,GI=f.object({repoOwner:f.string().trim().min(1,"repoOwner is required"),repoName:f.string().trim().min(1,"repoName is required"),sandboxPath:f.string().regex(Ah,"sandboxPath must be a single path segment under /workspace").optional()}).strict();function qI(e){return e.sandboxPath??`/workspace/${e.repoName}`}var WD=f.array(GI).min(1,"at least one repo is required").max(kh,`at most ${kh} repos are allowed`).superRefine((e,t)=>{if(e.length===0)return;let r=e[0].repoOwner.toLowerCase();e[0].sandboxPath!==void 0&&t.addIssue({code:"custom",path:[0,"sandboxPath"],message:`the primary repo is always cloned to /workspace/${e[0].repoName}`});let o=new Set,n=new Set;e.forEach((i,a)=>{i.repoOwner.toLowerCase()!==r&&t.addIssue({code:"custom",path:[a,"repoOwner"],message:"all repos must share the primary repo's owner"});let s=`${i.repoOwner}/${i.repoName}`.toLowerCase();o.has(s)&&t.addIssue({code:"custom",path:[a],message:`duplicate repo ${i.repoOwner}/${i.repoName}`}),o.add(s);let u=qI(i);if(!Ah.test(u)){t.addIssue({code:"custom",path:[a],message:`repo name ${i.repoName} needs an explicit sandboxPath`});return}n.has(u)&&t.addIssue({code:"custom",path:[a],message:`sandbox path ${u} is already taken`}),n.add(u)})}),Eh=f.object({name:f.string(),envVar:f.string()}),Or=f.record(f.string().regex(ra,"must be a POSIX-style environment variable name"),f.string()),Ph=f.object({type:f.enum([Cr.Compose]),files:f.array(f.string()).optional(),service:f.string().optional(),profiles:f.array(f.string()).optional()}).strict(),dp=f.object({fixtures:yh.optional(),cwd:f.string().optional(),bootScript:f.string().max(65536).describe("Optional bash bringup script. When set it overrides the entry: arcanist-app start runs it on the sandbox host from cwd with runtimeVariables plus HOST and PORT, and waits on ready.path. The app must listen on url.hostPort. Leave unset to boot from the entry.").optional(),kind:f.string().optional(),runner:f.string().optional(),entry:Ph.optional(),url:f.object({hostPort:f.number().int().optional(),path:f.string().optional()}).strict().optional(),portMapping:f.object({containerPort:f.number().int().optional()}).strict().optional(),additionalPorts:f.array(f.object({service:f.string().optional(),hostPort:f.number().int().optional(),containerPort:f.number().int().optional()}).strict()).optional(),runtimeVariables:Or.optional(),composeEnv:Or.optional(),generatedComposeEnv:f.record(f.string(),f.union([f.object({type:f.literal("alphanumeric"),length:f.number().int()}).strict(),f.object({type:f.literal("hex"),bytes:f.number().int()}).strict()])).optional(),env:Or.optional(),ready:f.object({path:f.string().optional(),nonEmptyPath:f.string().optional(),timeoutSeconds:f.number().int().optional()}).strict().optional(),open:f.object({path:f.string().optional()}).strict().optional(),renderedPathPrefixes:f.array(f.string().max(512)).max(VI).describe("Repo-relative directories the booted app is built from. When set, a review boots the app only when the diff touches a non-test file under one of them; when unset, the file-extension heuristic decides.").optional(),auth:f.object({command:f.string().optional(),validatePath:f.string().optional(),browserStateEnvVar:f.string().optional(),credentials:f.array(Eh).optional()}).strict().optional(),e2e:f.object({testCommand:f.string(),seedCommand:f.string().optional(),resetCommand:f.string().optional(),credentials:f.array(Eh).optional()}).strict().optional(),qaSwitches:Ih.describe("Runtime variables QA may switch, each with the only values it may take (default true/false). A QA run restarts the app with the chosen values so a flag-gated change can be tested on and off.").optional()}).strict(),HI="dockerfile",WI=f.union([f.object({type:f.literal(Cr.Command),command:f.string().optional()}).passthrough(),f.object({type:f.literal(HI),context:f.string().optional(),dockerfile:f.string().optional(),service:f.string().optional()}).passthrough()]),Rh=dp.extend({entry:f.union([Ph,WI]).optional()}),KI=/^[a-z][a-z0-9-]*$/;var Ch=f.object({id:f.string().trim().min(1).regex(KI),description:f.string().trim().min(1),config:dp}).strict(),JI=Ch.extend({config:Rh}),YI=f.array(Ch).superRefine((e,t)=>{new Set(e.map(r=>r.id)).size!==e.length&&t.addIssue({code:"custom",message:"App runtime names must be unique"})}),Th=["defect","walkthrough","edge-case"];var Oh=f.object({appDir:f.string().trim().min(1).max(512).describe("Repo-relative directory of the Expo or Xcode project."),bundleIdentifier:f.string().trim().min(1).optional(),scheme:f.string().trim().min(1).optional(),workspace:f.string().trim().min(1).optional(),backend:f.object({startCommand:f.string().trim().min(1).max(2e3).describe("Runs in the verifier sandbox from the repo root; exits 0 once the backend answers."),ports:f.array(f.number().int().min(1).max(65535)).min(1).max(8).describe("Localhost ports the app build dials; each is tunneled from the simulator to the same port.")}).strict().optional(),films:f.array(f.enum(Th)).min(1).max(Th.length).optional().describe("What a filmed review posts: `defect` (the flow to a confirmed defect, under its finding; the default), `walkthrough` (every screen the pull request touches, in the summary), `edge-case` (each edge case the planner asks and a run confirms).")}).strict(),KD=f.object({sandbox:f.object({appRuntime:dp.optional(),appRuntimes:YI.optional(),helperFiles:lp.optional(),runtimeVariables:Or.optional(),iosApp:Oh.optional()}).strict().refine(e=>e.appRuntime===void 0||e.appRuntimes===void 0,{message:"Supply appRuntimes or legacy appRuntime, not both"}).optional()}).strict(),JD=f.object({sandbox:f.object({appRuntime:Rh.optional(),appRuntimes:f.array(JI).optional(),helperFiles:lp.optional(),runtimeVariables:Or.optional(),iosApp:Oh.optional()}).strict().optional()}).strict();function pp(e){if(!e)return null;let t=e.entry;if(t===void 0||t.type===Cr.Compose)return e;let{entry:r,...o}=e,n=t.type===Cr.Command?t.command?.trim():void 0,i=e.bootScript?.trim()?e.bootScript:n||e.bootScript;return{...o,...i!==void 0?{bootScript:i}:{}}}var ia=1,XI=["name","description","provisioningKind","provisioningConfig","helperFiles","cache","networkPolicy"];function QI(e){let t=e?.sandbox;if(!t)return e;let{appRuntime:r,appRuntimes:o,...n}=t;return{...e,sandbox:{...n,...r?{appRuntime:pp(r)}:{},...o?{appRuntimes:o.map(i=>({...i,config:pp(i.config)}))}:{}}}}function oa(e){let{status:t,setupScript:r,maintenanceScript:o,smokeTestScript:n,dependencies:i,cpuCount:a,memoryMB:s}=e.cache;return{name:e.name,description:e.description,provisioningKind:e.provisioningKind,provisioningConfig:QI(e.provisioningConfig),...e.helperFiles!==void 0?{helperFiles:e.helperFiles}:{},cache:{status:t,setupScript:r,maintenanceScript:o,smokeTestScript:n,dependencies:i,cpuCount:a,memoryMB:s},networkPolicy:e.networkPolicy}}function Nh(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([o],[n])=>o.localeCompare(n))):r)}function Dh(e,t){let r={...oa(e),repos:e.repos},o={...t.environment,repos:t.repos};return[...XI,"repos"].filter(n=>Nh(r[n]??null)!==Nh(o[n]??null))}function zh(e,t){let r=oa(e).helperFiles??{},o=t.environment.helperFiles??{},i=[...new Set([...Object.keys(r),...Object.keys(o)])].filter(a=>(r[a]??null)!==(o[a]??null)).sort();return i.length>0?i:void 0}var ek=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+)$/,tk=/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/,nk=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/,rk=/^(\d+)(?:\.(diff|patch))?$/i,Uh=/^[A-Za-z0-9_.-]+$/,ik=/^[A-Za-z0-9_.][A-Za-z0-9_.-]*$/;function Lh(e){return typeof e!="string"||!e||e.length>100||e==="."||e===".."?!1:ik.test(e)}function ok(e,t){return Lh(e)&&Lh(t)?{owner:e,repo:t}:null}function aa(e){let t=e.match(ek)??e.match(tk)??e.match(nk);return t?ok(t[1],t[2]):null}var ak=500;function sk(e){if(typeof e!="string")return null;let t=e.trim();if(!t||t.length>ak)return null;let r;try{r=new URL(t)}catch{return null}if(r.protocol!=="https:"||r.hostname.toLowerCase()!=="github.com")return null;let o=r.pathname.split("/").filter(Boolean),n=o.length>=4?rk.exec(o[3]):null;return o[2]!=="pull"||n===null||n[2]!==void 0&&o.length!==4||!Uh.test(o[0])||!Uh.test(o[1])?null:`https://github.com/${o[0]}/${o[1]}/pull/${n[1]}`}function jh(e){let t=sk(e);if(!t)return null;let r=t.slice(19).split("/"),o=Number(r[3]);return!Number.isInteger(o)||o<=0?null:{prUrl:t,owner:r[0],repo:r[1],number:o}}import{execFileSync as Mh}from"node:child_process";function Nr(e,t={}){try{return Mh("git",e,{encoding:"utf8",stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.input===void 0?{}:{input:t.input},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(r){throw new y("user",`git ${e.join(" ")} failed: ${xe(r)}`)}}function Fh(e,t={}){let r;try{r=Mh("git",e,{stdio:["ignore","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(o){throw new y("user",`git ${e.join(" ")} failed: ${xe(o)}`)}try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new y("user","A changed file has a file name that is not valid UTF-8, so it cannot be reviewed.",{hint:"Rename the file, commit, then run the review again."})}}function Dr(e,t={}){return Nr(e,t).trim()}function Zh(e="repo"){let t=`Pass the ${e} as owner/name.`,r;try{r=Dr(["remote","get-url","origin"])}catch{throw new y("user","This directory has no git `origin` remote to read the repository from.",{hint:t})}let o=aa(r);if(!o)throw new y("user","origin remote must point at a GitHub repository",{hint:t});return{owner:o.owner,repo:o.repo}}var uk=/\.git$/;function ck(e,t="repo"){let r=aa(e);if(!r)throw new y("user",`${t} must be owner/name or a GitHub URL`);return{owner:r.owner,repo:r.repo.replace(uk,"")}}function mt(e,t="repo"){return e===void 0?Zh(t):ck(e,t)}var lk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Bh(e){return(await R(e,P("/api/environments"))).data.environments}function Vh(e,t){return e.find(r=>r.scope==="team"&&r.repoOwner.toLowerCase()===t.owner.toLowerCase()&&r.repoName.toLowerCase()===t.repo.toLowerCase())}async function Gh(e,t){return Vh(await Bh(e),t)??null}async function mp(e,t){let r=await Bh(e);if(t&&lk.test(t)){let i=r.find(a=>a.id===t);if(!i)throw new y("user",`No environment with id ${t}.`);return i}let o=mt(t,"environment"),n=Vh(r,o);if(!n)throw new y("user",`No team environment for ${o.owner}/${o.repo}.`,{hint:"Run `arcanist environments status` first."});return n}async function qh(e,t){return(await R(e,P("/api/environments/:id",{id:t}))).data}function mk(e,t){let r;try{r=JSON.parse(e)}catch{throw new y("user",`${t} is not valid JSON.`)}let o=r;if(!o||o.version!==ia||!o.environment||typeof o.environment.name!="string"||!o.environment.cache||!Array.isArray(o.repos)||o.repos.length===0)throw new y("user",`${t} is not an Environment export (version ${ia}).`,{hint:"Write one with `arcanist environments export owner/repo -o <file>`."});return o}async function Hh(e,t={},r){let{config:o}=Y(r,t),n=await mp(o,e),i=await qh(o,n.id),a={version:ia,exportedFrom:{apiUrl:o.apiUrl,environmentId:i.id,configurationGeneration:i.cache.configurationGeneration,exportedAt:new Date().toISOString()},repos:i.repos,environment:oa(i)},s=`${JSON.stringify(a,null,2)}
71
- `;if(t.output){await pk(t.output,s,"utf8"),D(r,t,{environmentId:i.id,name:i.name,configurationGeneration:i.cache.configurationGeneration,path:t.output},u=>{console.log(`Exported "${F(u.name)}" (generation ${u.configurationGeneration}) to ${u.path}`)});return}process.stdout.write(s)}async function fk(e,t,r,o){let n=t.repos[0],i=`${n.repoOwner}/${n.repoName}`,{name:a}=t.environment;if(r.dryRun){D(o,r,{environmentId:null,name:a,created:!1,applied:!1},u=>{console.log(`Would create "${F(u.name)}" for ${i} (dry run; nothing was sent).`)});return}let s=await R(e,P("/api/environments"),{method:"POST",body:JSON.stringify({...t.environment,repos:t.repos,scope:"team"})});D(o,r,{environmentId:s.data.id,name:s.data.name,created:!0,applied:!0,configurationGeneration:{after:s.data.cache.configurationGeneration},buildScheduled:s.data.cache.status==="enabled"},u=>{console.log(`Created "${F(u.name)}" for ${i} (${u.environmentId}).`),u.buildScheduled&&console.log("A build is scheduled; watch it with `arcanist environments status --wait`.")})}async function Wh(e,t,r={},o){let n=mk(await dk(e,"utf8"),e),{config:i}=Y(o,r),a=n.repos[0],s=t===void 0?await Gh(i,{owner:a.repoOwner,repo:a.repoName}):await mp(i,t);if(!s){if(!r.create)throw new y("user",`No team environment for ${a.repoOwner}/${a.repoName}.`,{hint:"Pass --create to create it from this file."});await fk(i,n,r,o);return}let u=await qh(i,s.id),c=u.repos[0]??{repoOwner:u.repoOwner,repoName:u.repoName};if(c.repoOwner.toLowerCase()!==a.repoOwner.toLowerCase()||c.repoName.toLowerCase()!==a.repoName.toLowerCase())throw new y("user",`${e} was exported for ${a.repoOwner}/${a.repoName}, but the target environment's primary repository is ${c.repoOwner}/${c.repoName}.`,{hint:"An Environment's primary repository cannot change; export from a matching repository."});let l=Dh(u,n),d=zh(u,n),m={environmentId:u.id,name:u.name,changedFields:l,...d?{driftedHelperFilePaths:d}:{},configurationGeneration:{before:u.cache.configurationGeneration}};if(r.dryRun&&l.length>0&&await R(i,`${P("/api/environments/:id",{id:u.id})}?dryRun=1`,{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),r.dryRun||l.length===0){D(o,r,{...m,applied:!1},_=>{console.log(_.changedFields.length===0?`"${F(_.name)}" already matches ${e}; nothing to apply.`:`Would change ${_.changedFields.join(", ")} on "${F(_.name)}" (dry run).`)});return}let p=await R(i,P("/api/environments/:id",{id:u.id}),{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),v=p.data.cache.configurationGeneration;D(o,r,{...m,applied:!0,configurationGeneration:{before:u.cache.configurationGeneration,after:v},rebuildScheduled:v!==u.cache.configurationGeneration&&p.data.cache.status==="enabled"},_=>{console.log(`Applied ${_.changedFields.join(", ")} to "${F(_.name)}" (generation ${_.configurationGeneration.before} -> ${_.configurationGeneration.after}).`),_.rebuildScheduled&&console.log("A rebuild is scheduled; watch it with `arcanist environments status --wait`.")})}var zr="GitHub could not verify your organization role because the Arcanist GitHub App needs additional permissions. Ask an organization owner to approve the pending permissions in GitHub's installed apps settings, then try again.",sa="Arcanist could not verify your GitHub account permissions. Try again. If this continues, reconnect GitHub and authorize your organization's SSO if required.";async function En(e){let t=Date.now()+e.timeoutMs,r=null;for(;Date.now()<t;){try{let o=await e.fetchStatus();if(r=null,o!==null)return o}catch(o){if(!rm(o))throw o;if(r===null){let n=o instanceof Error?o.message:String(o);process.stderr.write(`Status check failed (${n}). Still waiting; retrying every ${e.pollIntervalMs}ms.
72
- `)}r=o}await Gr(e.pollIntervalMs)}throw r!==null?r:new y("server",e.timeoutMessage)}var Kh=250,ua=1e3,Jh=6e4,Yh=200;function Xh(e){return Bp(e)}var gk=/^\d+$/;function Ze(e,t={}){let r=t.defaultMs??ua,o=t.minMs??Kh,n=t.maxMs===void 0?Jh:t.maxMs;if(!e)return r;if(!gk.test(e))throw new y("user","Polling interval must be a non-negative integer.");let i=Number(e);if(i<o||n!==null&&i>n){let a=n===null?`at least ${o}`:`between ${o} and ${n}`;throw new y("user",`Polling interval must be ${a} milliseconds.`)}return i}var Tn=5e3,vk=7200*1e3;function fp(e){let t=mt(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function ft(e,t){let o=(await R(e,P("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=_k(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${pt(o.question.id)} --answer-stdin --json`:Qh(n,o.fullName);return{fullName:o.fullName,status:o.status,stage:o.stage,...o.buildStatus===void 0?{}:{buildStatus:o.buildStatus},...o.failureReason===void 0?{}:{failureReason:o.failureReason},...o.question===void 0?{}:{question:o.question},nextAction:n,command:i}}function hk(e){return e.nextAction==="wait"}function Qh(e,t){switch(e){case"prepare":return`arcanist environments prepare ${t}`;case"wait":return`arcanist environments status ${t} --wait`;case"retry":return`arcanist environments retry ${t}`;case"review":return null;case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function _k(e){return e.status==="not_started"?"prepare":e.status==="ready"?"review":e.question?"answer_question":e.status==="failed"?e.failureReason==="installation_missing"?"authorize_github":"retry":e.status==="escalated"&&e.stage!=="escalated_to_customer"&&e.stage!=="question_for_customer"?"wait_for_arcanist":"wait"}function ca(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${F(e.fullName)}: ${F(e.status)}${t?` (${F(t)})`:""}`)}async function gp(e,t,r){return En({pollIntervalMs:r,timeoutMs:vk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await ft(e,t);return hk(o)?null:o}})}async function vp(e,t){return(await R(e,P("/api/settings/repositories/onboarding"),{method:"POST",body:JSON.stringify({repositories:t.repositories.map(({owner:o,repo:n})=>({owner:o,name:n})),...t.workspace?{workspace:!0}:{}})})).repositories}async function e_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t);await R(i,P("/api/repos"));let a=t.wait?await gp(i,n.fullName,o??Tn):await ft(i,n.fullName);D(r,t,{repository:a},({repository:s})=>ca(s))}async function t_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t),[a]=await vp(i,{repositories:[n]});if(!a)throw new y("server","Environment setup returned no repository result.");if(a.status==="forbidden"&&a.reason==="installation_admin_required")throw new y("auth",`Ask a workspace admin to connect the Arcanist GitHub App for ${n.owner} before preparing ${n.fullName}.`);if(a.status==="forbidden"&&a.reason==="installation_github_admin_required")throw new y("auth",`An admin of the ${n.owner} GitHub account must connect the Arcanist GitHub App before ${n.fullName} can be prepared.`);if(a.status==="forbidden"&&a.reason==="repository_limit")throw new y("auth",`This workspace has reached its limit of repositories with an environment, so ${n.fullName} cannot be prepared. Upgrade to Team, or ask Arcanist to raise the limit.`);if(a.status==="forbidden")throw new y("auth",`You must have write access to ${n.fullName} to prepare its environment.`);if(a.status==="failed")throw a.reason==="installation_github_permissions_required"?new y("auth",zr):a.reason==="installation_github_check_failed"?new y("server",sa):new y("server",`Environment setup could not be started for ${n.fullName}.`);if(t.wait&&(a.status==="queued"||a.status==="already_queued")){let c=await gp(i,n.fullName,o??Tn);D(r,t,{repository:c},({repository:l})=>ca(l));return}let s=a.status==="already_ready"?"review":"wait",u={fullName:a.fullName,status:a.status==="already_ready"?"ready":"pending",stage:null,nextAction:s,command:Qh(s,a.fullName)};D(r,t,{repository:u},({repository:c})=>ca(c))}async function n_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t);await R(i,P("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await gp(i,n.fullName,o??Tn):await ft(i,n.fullName);D(r,t,{repository:a},({repository:s})=>ca(s))}var yk=["openai","anthropic","baseten"],r_=f.enum(yk),i_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),qz=f.object({managedFallback:f.boolean()}).strict(),o_=f.object({name:f.string().trim().min(1).max(80)}).strict();var la=class e{static register(t){let r=t.command("keys").description("Manage workspace inference-only API keys (admins)");r.command("list").description("List key metadata; secrets are never returned").option("--cursor <cursor>","Continue from nextCursor").option("--limit <limit>","Page size: 10, 25, or 50","25").action((o,n)=>e.list(o,n)),r.command("create <name>").description("Create an inference key and print its secret once; save it securely").action((o,n,i)=>e.create(o,n,i)),r.command("revoke <id>").description("Revoke a key for subsequent inference requests").action((o,n,i)=>e.revoke(o,n,i))}static async list(t,r){let{config:o}=Y(r,t);if(!["10","25","50"].includes(t.limit??"25"))throw new y("user","limit must be 10, 25, or 50.");let n=new URLSearchParams({limit:t.limit??"25"});t.cursor&&n.set("cursor",t.cursor);let i=await R(o,`${P("/api/inference/keys")}?${n}`);D(r,t,i,a=>{for(let s of a.keys)console.log(`${s.id} ${s.name} ${s.keyPrefix}\u2026 ${s.revokedAt===null?"active":"revoked"}`);a.nextCursor&&console.log(`Next page: --cursor ${a.nextCursor}`)})}static async create(t,r,o){let n=o_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=Y(o,r),a=await R(i,P("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});D(o,r,a,s=>{console.log(`Created ${s.key.name} (${s.key.id}). Save this secret now; it cannot be retrieved again.`),console.log(s.secret)})}static async revoke(t,r,o){let{config:n}=Y(o,r),i=await R(n,P("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});D(o,r,i,()=>console.log("Inference key revoked. Existing streams may finish."))}};var da=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");la.register(r);let o=r.command("providers").description("Manage OpenAI, Anthropic, and Baseten keys (workspace admins)");o.command("list").description("Show saved keys and fallback preferences; never reveals keys").action((n,i)=>e.list(n,i)),o.command("set-key <provider>").description("Add or replace a provider key through stdin").option("--key-stdin","Read the key from stdin; never include keys in command arguments").action((n,i,a)=>e.setKey(n,i,a)),o.command("remove-key <provider>").description("Remove the saved key, keeping the fallback preference").action((n,i,a)=>e.removeKey(n,i,a)),o.command("fallback <provider> <on|off>").description("Save opt-in fallback to Arcanist-managed inference at public provider prices").action((n,i,a,s)=>e.fallback(n,i,a,s)),r.command("usage").description("Show workflow usage availability; proxy metering is not connected yet").action((n,i)=>e.usage(n,i))}static provider(t){let r=r_.safeParse(t);if(!r.success)throw new y("user","Provider must be openai, anthropic, or baseten.");return r.data}static async settings(t,r,o,n){let{config:i}=Y(o,r),a=await R(i,t,n);D(o,r,a,s=>{for(let u of s.providers)console.log(`${u.provider} ${u.configured?`key \u2026${u.keySuffix} (not verified)`:"no key"} fallback ${u.managedFallback?"on":"off"}`);console.log("Preferences saved for future proxy routing; live traffic is unchanged.")})}static list(t,r){return e.settings(P("/api/inference/providers"),t,r)}static async setKey(t,r,o){let n=e.provider(t);if(!r.keyStdin||process.stdin.isTTY)throw new y("user","Pipe the key through --key-stdin.");let i=i_.safeParse({key:await jt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(P("/api/inference/providers/:provider/key",{provider:n}),r,o,{method:"PUT",body:JSON.stringify(i.data)})}static removeKey(t,r,o){let n=e.provider(t);return e.settings(P("/api/inference/providers/:provider/key",{provider:n}),r,o,{method:"DELETE"})}static fallback(t,r,o,n){let i=e.provider(t);if(r!=="on"&&r!=="off")throw new y("user","Fallback must be on or off.");return e.settings(P("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async usage(t,r){let{config:o}=Y(r,t),n=await R(o,P("/api/inference/usage"));D(r,t,n,()=>console.log("Workflow usage is unavailable until proxy metering is connected. No spend totals are being reported."))}};var a_="The prepared environment was unavailable for this review. Arcanist may have run checks from a fresh checkout, but could not use the prepared app environment.";import{execFileSync as v_}from"node:child_process";import{basename as Pk,extname as Rk}from"node:path";function s_(e){return e.blocking===!0}var bk=/[.!]+$/u,u_=["clear","issues_found","inconclusive"];var wk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},c_="blocks merge";var l_="\u2705 Ruled out";function d_(e){return e.replace(bk,"")}function p_(e){return wk[e==="do_not_merge"?"do_not_merge":"merge"]}function $k(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function xk(e){return s_(e)?"blocking":"non_blocking"}function Sk(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function m_(e){let t=$k(e).prFindings,r=t.map(s=>({finding:s,impact:xk(s)})),o=[...r].sort((s,u)=>+(s.impact!=="blocking")-+(u.impact!=="blocking")),n=r.filter(s=>s.impact==="blocking").length,i={blocking:n,nonBlocking:r.length-n,nits:0},a=Sk(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var _p=3e6,hp=f.string().regex(/^[0-9a-f]{40}$/),Ik=["added","modified","removed","renamed"],kk=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(Ik),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),Ek=f.object({sha:hp,subject:f.string(),body:f.string()}),fU=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:hp,headRef:f.string().min(1),headSha:hp,files:f.array(kk).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(Ek),heldBackPaths:f.array(f.string())});function f_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var Tk=["running","completed","failed"],Ak=f.object({requestId:f.string().min(1),sessionId:f.string().min(1).nullable(),createdAt:f.number().int(),repoOwner:f.string().min(1),repoName:f.string().min(1),headRef:f.string().min(1),baseRef:f.string().min(1),headShortSha:f.string().min(1),status:f.enum(Tk),verdict:f.enum(u_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),gU=f.object({reviews:f.array(Ak),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var Ck=/^origin\//,Ok=/^new file mode /m,Nk=/^deleted file mode /m,Dk=/^\.\//,zk=/\/+$/,g_=64*1024*1024,Uk=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),Lk=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),jk=[".example",".sample",".template"];function h_(e={}){let t=e.cwd;if(Ur(["rev-parse","--is-inside-work-tree"],t)!=="true")throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Ur(["remote","get-url","origin"],t);if(!r)throw new y("user","This checkout has no origin remote.",{hint:"Add your GitHub repository as origin: git remote add origin <url>"});if(e.base&&!Ur(["rev-parse","--verify","--quiet",`${e.base}^{commit}`],t))throw new y("user",`Base ref ${e.base} was not found.`,{hint:"Run `git fetch origin`, or pass a --base ref that exists locally, such as origin/main."});let o=e.base?{ref:e.base,label:e.base}:Mk(t),n=Dr(["rev-parse","HEAD"],{cwd:t}),i=Dr(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=Fk(Fh([...s,"--numstat","-z",a],{cwd:t,maxBuffer:g_})),c=Wk(t);if(u.length===0)throw new y("user",`No committed changes to review against ${o.ref}.`,{...c.length>0?{hint:`You have uncommitted changes in ${c.length} file(s). Commit them, then run arcanist review again.`}:{}});let l=Zk(Nr([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:g_}));if(l.length!==u.length)throw new y("user",`git diff listed ${u.length} files but printed ${l.length} patches.`);let d=new Set((e.include??[]).map(qk)),m=A=>d.has(A)||[...d].some(S=>A.startsWith(`${S}/`)),p=A=>A.previousPath?[A.path,A.previousPath]:[A.path],v=Gk(u.flatMap(p),t),_=[],x=[],E=[];if(u.forEach((A,S)=>{let O=l[S]??"";if(A.binary){x.push(A.path);return}if(p(A).some(G=>Vk(G)||v.has(G))&&!m(A.path)){E.push(A.path);return}_.push({path:A.path,...A.previousPath?{previousPath:A.previousPath}:{},status:Bk(O,A),additions:A.additions,deletions:A.deletions,patch:O})}),_.length===0)throw new y("user",`No reviewable changes against ${o.ref}.`,{hint:"Binary files are skipped and secret-looking files are held back; pass --include <path> to upload one."});let k={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Dr(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:f_(_),commitMessages:Hk(`${i}..HEAD`,t),heldBackPaths:E.sort()};return Kk(k),{payload:k,skippedBinaryPaths:x.sort(),uncommittedPaths:c}}function Mk(e){let t=[Ur(["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"],e)].concat(["origin/main","origin/master"]).filter(r=>typeof r=="string"&&r.length>0);for(let r of t)if(Ur(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(Ck,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Ur(e,t){try{return v_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).trim()}catch{return null}}function Fk(e){let t=e.split("\0"),r=[];for(let o=0;o<t.length;o+=1){let n=t[o];if(!n)continue;let[i="",a="",s=""]=n.split(" "),u={additions:i==="-"?0:Number(i),deletions:a==="-"?0:Number(a),binary:i==="-"&&a==="-"};if(s.length>0){r.push({path:s,...u});continue}let c=t[o+1]??"",l=t[o+2]??"";o+=2,r.push({path:l,previousPath:c,...u})}return r}function Zk(e){let t=[],r=null;for(let o of e.split(`
70
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let c=e.external.registry.get(a[0])?.id;if(t!==a[0]&&c){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Pg(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Pg(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Rg=new Set(["type","properties","required","additionalProperties"]),Tg=["oneOf","anyOf"];function Ag(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function pl(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Rg.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let s=[];for(let c of t){let l=c.properties?.[a]??Ag(c);l!=null&&(s.some(d=>JSON.stringify(d)===JSON.stringify(l))||s.push(l))}let u=s.length===1?s[0]:pl(s)??{allOf:s};se(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let s=Ag(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function oI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Rg)if(n in e)return;let r=t.filter(n=>Tg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=pl(t);else{let n=r[0],i=Tg.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>pl([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,vr(e,o))}function st(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){o(d);let p=e.seen.get(d),v=p.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(v)):vr(c,v),vr(c,l),s._zod.parent===d)for(let x in c)x==="$ref"||x==="allOf"||x in l||delete c[x];if(v.$ref&&p.def)for(let x in c)x==="$ref"||x==="allOf"||x in p.def&&JSON.stringify(c[x])===JSON.stringify(p.def[x])&&delete c[x]}let m=s._zod.parent;if(m&&m!==d){o(m);let p=e.seen.get(m);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let v in c)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(c[v])===JSON.stringify(p.def[v])&&delete c[v]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Pg(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let l=c?.allOf;if(!Array.isArray(l))continue;let d=s.get(l);d?d.push(c):s.set(l,[c])}for(let u of e.intersections)for(let c of s.get(u)??[])oI(c)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}vr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,se(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:vn(t,"input",e.processors),output:vn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ge(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ge(o.element,r);if(o.type==="set")return ge(o.valueType,r);if(o.type==="lazy")return ge(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return ge(o.innerType,r);if(o.type==="intersection")return ge(o.left,r)||ge(o.right,r);if(o.type==="record"||o.type==="map")return ge(o.keyType,r)||ge(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ge(o.in,r)||ge(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ge(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ge(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ge(n,r))return!0;return!!(o.rest&&ge(o.rest,r))}return!1}var ml=(e,t={})=>r=>{let o=ot({...r,processors:t});return W(e,o),at(o,e),st(o,e)},vn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=ot({...n??{},target:i,io:t,processors:r});return W(e,a),at(a,e),st(a,e)};var hn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},_n=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Cg=(e,t)=>{hn(e,"minimum",t),_n(e,"maximum",t)},zg=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Ug=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Lg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},jg=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Og=(e,t)=>hn(e,"minimum",t.minimum),Ng=(e,t)=>_n(e,"maximum",t.maximum),Dg=e=>(t,r)=>{jg(t,r.format);let[o,n]=e[r.format];hn(t,"minimum",o),_n(t,"maximum",n)},aI={greater_than:(e,t)=>hn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>_n(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>zg(e,t.value),number_format:Dg(Un),bigint_format:Dg(Ln),min_length:Og,max_length:Ng,length_equals:(e,t)=>Cg(e,t.length),min_size:Og,max_size:Ng,size_equals:(e,t)=>Cg(e,t.size),string_format:(e,t)=>{jg(e,t.format),t.pattern&&Ug(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Lg(e,t.mime)};function ie(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)aI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&hn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&hn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&_n(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&_n(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&zg(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Lg(t,n.mime);for(let i of n.patterns??[])Ug(t,i);return t}var sI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uI=new Map([[Ei,ys],[tr,bs]]),Mg=e=>uI.get(e)??e,vl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:c,laxFormat:l}=ie(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=sI[s]??s,n.format===""&&delete n.format,(s==="time"||l)&&delete n.format),c&&(n.contentEncoding=c),u&&u.size>0){let d=[...u].map(Mg);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},hl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:c,isInt:l}=ie(e);n.type=l?"integer":"number";let d=typeof c=="number"&&c>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(n.minimum=c,n.exclusiveMinimum=!0):n.exclusiveMinimum=c:typeof i=="number"&&(n.minimum=i),m?p?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let E of s)Number.isFinite(E)&&E!==0?v.add(Math.abs(E)):re(e,t,n,o,`A multipleOf divisor of ${E} cannot be represented in JSON Schema`);let[_,...x]=v;_!==void 0&&(n.multipleOf=_),x.length&&(n.allOf=[...n.allOf??[],...x.map(E=>({multipleOf:E}))])}},_l=(e,t,r,o)=>{r.type="boolean"},yl=(e,t,r,o)=>{re(e,t,r,o,"BigInt cannot be represented in JSON Schema")},bl=(e,t,r,o)=>{re(e,t,r,o,"Symbols cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},$l=(e,t,r,o)=>{re(e,t,r,o,"Undefined cannot be represented in JSON Schema")},xl=(e,t,r,o)=>{re(e,t,r,o,"Void cannot be represented in JSON Schema")},Sl=(e,t,r,o)=>{r.not={}},Il=(e,t,r,o)=>{},kl=(e,t,r,o)=>{},El=(e,t,r,o)=>{re(e,t,r,o,"Date cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{let n=e._zod.def,i=Ft(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Al=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(re(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(re(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Pl=(e,t,r,o)=>{re(e,t,r,o,"NaN cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Cl=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ie(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},Ol=(e,t,r,o)=>{r.type="boolean"},Nl=(e,t,r,o)=>{re(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{re(e,t,r,o,"Function types cannot be represented in JSON Schema")},zl=(e,t,r,o)=>{re(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Ul=(e,t,r,o)=>{re(e,t,r,o,"Map cannot be represented in JSON Schema")},Ll=(e,t,r,o)=>{re(e,t,r,o,"Set cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ie(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=W(i.element,t,{...o,path:[...o.path,"items"]})};function hr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?hr(t.out):t.type==="catch"?hr(t.innerType):e._zod.optin}var Ml=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&re(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let c in a)se(n.properties,c,W(a[c],t,{...o,path:[...o.path,"properties",c]}));let u=[];for(let c of Object.keys(a)){let l=i.shape[c];(t.io==="input"?hr(l)===void 0:l._zod.optout===void 0)&&u.push(c)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=W(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Io=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>W(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Fl=(e,t,r,o)=>{let n=e._zod.def,i=W(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=W(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},Zl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((_,x)=>W(_,t,{...o,path:[...o.path,a,x]})),c=i.rest?W(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let _=i.items[l-1];if(!(t.io==="input"?hr(_)!==void 0:_._zod.optout==="optional"))break;l--}let d=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:c&&(n.items=c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:u},c&&n.items.anyOf.push(c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):(n.items=u,m?n.additionalItems=!1:c&&(n.additionalItems=c),l>0&&(n.minItems=l),m&&(n.maxItems=d));let{minimum:p,maximum:v}=ie(e);typeof p=="number"&&(n.minItems=p),typeof v=="number"&&(n.maxItems=v)};function fl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let v=e.get(t)?.def;if(!v)return t;let _=fl(e,v,r);return _===v?t:_}for(let v of["anyOf","oneOf"]){let _=t[v];if(!Array.isArray(_))continue;let x=_.map(E=>fl(e,E,r));x.some((E,k)=>E!==_[k])&&(t={...t,[v]:x})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(v=>v==="number"||v==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(v=>typeof v=="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:l,format:d,id:m,...p}=t;return p.enum?p.enum=p.enum.map(v=>typeof v=="number"?String(v):v):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?He:Wn).source)),p}var gl=new WeakMap;function cI(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of gl.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=fl(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var Bl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ie(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let l=W(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of s)se(n.patternProperties,Mg(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=W(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let l=gl.get(t);l||(l=[],gl.set(t,l),t.deferred.push(()=>cI(t))),l.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=t.io==="input"&&hr(i.valueType)!==void 0;if(u&&!i.partial&&!c){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},Vl=(e,t,r,o)=>{let n=e._zod.def,i=W(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Gl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ql=Symbol();function Fg(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(re(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),ql):JSON.parse(a)}var Hl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Fg(n.defaultValue,e,t,r,o);a!==ql&&(r.default=a)},Wl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Fg(n.defaultValue,e,t,r,o);a!==ql&&(r._prefault=a)},Kl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{re(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Jl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;W(a,t,o);let s=t.seen.get(e);s.ref=a},Yl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Xl=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ko=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ql=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},So={string:vl,number:hl,boolean:_l,bigint:yl,symbol:bl,null:wl,undefined:$l,void:xl,never:Sl,any:Il,unknown:kl,date:El,enum:Tl,literal:Al,nan:Pl,template_literal:Rl,file:Cl,success:Ol,custom:Nl,function:Dl,transform:zl,map:Ul,set:Ll,array:jl,object:Ml,union:Io,intersection:Fl,tuple:Zl,record:Bl,nullable:Vl,nonoptional:Gl,default:Hl,prefault:Wl,catch:Kl,pipe:Jl,readonly:Yl,promise:Xl,optional:ko,lazy:Ql};function Eo(e,t){if("_idmap"in e){let o=e,n=ot({...t,processors:So}),i={};for(let u of o._idmap.entries()){let[c,l]=u;W(l,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[c,l]=u;at(n,l),se(a,c,st(n,l))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=ot({...t,processors:So});return W(e,r),at(r,e),st(r,e)}var To=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ot({processors:So,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return W(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,at(this.ctx,t);let o=st(this.ctx,t),{"~standard":n,...i}=o;return i}};var Zg={};var kn={};Be(kn,{ZodAny:()=>wd,ZodArray:()=>Id,ZodBase64:()=>Ho,ZodBase64URL:()=>Wo,ZodBigInt:()=>Sn,ZodBigIntFormat:()=>Yo,ZodBoolean:()=>xn,ZodCIDRv4:()=>Go,ZodCIDRv6:()=>qo,ZodCUID:()=>Lo,ZodCUID2:()=>jo,ZodCatch:()=>qd,ZodCodec:()=>Er,ZodCreditCard:()=>md,ZodCustom:()=>Tr,ZodCustomStringFormat:()=>Dt,ZodDate:()=>wr,ZodDefault:()=>Md,ZodDiscriminatedUnion:()=>Ed,ZodE164:()=>Ko,ZodEmail:()=>No,ZodEmoji:()=>zo,ZodEnum:()=>bn,ZodExactOptional:()=>ta,ZodFile:()=>zd,ZodFunction:()=>np,ZodGUID:()=>Do,ZodIBAN:()=>fd,ZodIPv4:()=>Bo,ZodIPv6:()=>Vo,ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,ZodInstanceOf:()=>op,ZodIntersection:()=>Td,ZodJWT:()=>Jo,ZodKSUID:()=>Zo,ZodLazy:()=>Qd,ZodLiteral:()=>Dd,ZodMAC:()=>pd,ZodMap:()=>Od,ZodNaN:()=>Wd,ZodNanoID:()=>Uo,ZodNever:()=>xd,ZodNonOptional:()=>na,ZodNull:()=>yd,ZodNullable:()=>jd,ZodNumber:()=>$n,ZodNumberFormat:()=>zt,ZodObject:()=>xr,ZodOptional:()=>Ir,ZodPipe:()=>kr,ZodPrefault:()=>Zd,ZodPreprocess:()=>Kd,ZodPromise:()=>tp,ZodReadonly:()=>Jd,ZodRecord:()=>yn,ZodSet:()=>Nd,ZodString:()=>wn,ZodStringFormat:()=>K,ZodSuccess:()=>Gd,ZodSymbol:()=>hd,ZodTemplateLiteral:()=>Xd,ZodTransform:()=>Ud,ZodTuple:()=>Pd,ZodType:()=>L,ZodULID:()=>Mo,ZodURL:()=>br,ZodUUID:()=>Fe,ZodUndefined:()=>_d,ZodUnion:()=>Sr,ZodUnknown:()=>$d,ZodVoid:()=>Sd,ZodXID:()=>Fo,ZodXor:()=>kd,_ZodString:()=>Oo,_default:()=>Fd,_function:()=>eh,any:()=>Rv,array:()=>$r,base64:()=>dv,base64url:()=>pv,bigint:()=>kv,boolean:()=>vd,catch:()=>Hd,check:()=>th,cidrv4:()=>cv,cidrv6:()=>lv,codec:()=>Jv,creditCard:()=>fv,cuid:()=>tv,cuid2:()=>nv,currencyCode:()=>bv,custom:()=>nh,date:()=>Ov,describe:()=>rh,discriminatedUnion:()=>jv,e164:()=>mv,email:()=>Gg,emoji:()=>Qg,enum:()=>Qo,exactOptional:()=>Ld,file:()=>qv,float32:()=>$v,float64:()=>xv,function:()=>eh,guid:()=>qg,hash:()=>wv,hex:()=>yv,hostname:()=>_v,httpUrl:()=>Xg,iban:()=>gv,instanceof:()=>oh,int:()=>Ro,int32:()=>Sv,int64:()=>Ev,intersection:()=>Ad,invertCodec:()=>Yv,ipv4:()=>av,ipv6:()=>uv,json:()=>sh,jwt:()=>vv,keyof:()=>Nv,ksuid:()=>ov,lazy:()=>ep,literal:()=>Gv,looseObject:()=>Uv,looseRecord:()=>Fv,mac:()=>sv,map:()=>Zv,meta:()=>ih,nan:()=>Kv,nanoid:()=>ev,nativeEnum:()=>Vv,never:()=>Xo,nonoptional:()=>Vd,null:()=>bd,nullable:()=>yr,nullish:()=>Hv,number:()=>gd,object:()=>Dv,optional:()=>Ot,partialRecord:()=>Mv,pipe:()=>Co,prefault:()=>Bd,preprocess:()=>uh,promise:()=>Qv,readonly:()=>Yd,record:()=>Cd,refine:()=>rp,set:()=>Bv,strictObject:()=>zv,string:()=>_r,stringFormat:()=>hv,stringbool:()=>ah,success:()=>Wv,superRefine:()=>ip,symbol:()=>Av,templateLiteral:()=>Xv,transform:()=>ea,tuple:()=>Rd,uint32:()=>Iv,uint64:()=>Tv,ulid:()=>rv,undefined:()=>Pv,union:()=>In,unknown:()=>Ct,url:()=>Yg,uuid:()=>Hg,uuidv4:()=>Wg,uuidv6:()=>Kg,uuidv7:()=>Jg,void:()=>Cv,xid:()=>iv,xor:()=>Lv});var Ao={};Be(Ao,{endsWith:()=>un,gt:()=>je,gte:()=>ke,includes:()=>an,length:()=>Pt,lowercase:()=>rn,lt:()=>Le,lte:()=>Ie,maxLength:()=>At,maxSize:()=>it,mime:()=>ln,minLength:()=>We,minSize:()=>Me,multipleOf:()=>rt,negative:()=>bo,nonnegative:()=>$o,nonpositive:()=>wo,normalize:()=>dn,overwrite:()=>ze,positive:()=>yo,properties:()=>cn,property:()=>xo,regex:()=>nn,size:()=>Tt,slugify:()=>gn,startsWith:()=>sn,toLowerCase:()=>mn,toUpperCase:()=>fn,trim:()=>pn,uppercase:()=>on});var Bg=new WeakSet([Object.prototype,Error.prototype]);function Po(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Vg=(e,t)=>{Qa.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Bg.has(r)||(Bg.add(r),Po(r,"format",o=>n=>Vn(o,n)),Po(r,"flatten",o=>n=>Bn(o,n)),Po(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Zt,2)}),Po(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Zt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},dI=g("ZodError",Vg),$e=g("ZodError",Vg,void 0,{Parent:Error});var ed=Ht($e),td=Wt($e),nd=Kt($e),rd=Jt($e),id=ii($e),od=oi($e),ad=ai($e),sd=si($e),ud=ui($e),cd=ci($e),ld=li($e),dd=di($e);function mI(){oe.localeError||te(Bi())}function Nt(){oe.memoizer||te({memoizer:ur()})}var L=g("ZodType",(e,t)=>(mI(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return q(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rp(e,t))},superRefine(e,t){return this.check(ip(e,t))},overwrite(e){return this.check(ze(e))},optional(){return Ot(this)},exactOptional(){return Ld(this)},nullable(){return yr(this)},nullish(){return Ot(yr(this))},nonoptional(e){return Vd(this,e)},array(){return $r(this)},or(e){return In([this,e])},and(e){return Ad(this,e)},transform(e){return Co(this,ea(e))},default(e){return Fd(this,e)},prefault(e){return Bd(this,e)},catch(e){return Hd(this,e)},pipe(e){return Co(this,e)},readonly(){return Yd(this)},describe(e){let t=this.clone();return ue.add(t,{description:e}),t},meta(...e){if(e.length===0)return ue.get(this);let t=this.clone();return ue.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return b.hide(this,"~standard",{...$i(this),jsonSchema:{input:vn(this,"input"),output:vn(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return ed(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await td(this,t,r,{callee:e})},safeParse(e,t){return nd(this,e,t)},async safeParseAsync(e,t){return rd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return Gn(this,e,t)},validateAsync(e,t){return qn(this,e,t)},encode:function e(t,r){return id(this,t,r,{callee:e})},decode:function e(t,r){return od(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ad(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await sd(this,t,r,{callee:e})},safeEncode(e,t){return ud(this,e,t)},safeDecode(e,t){return cd(this,e,t)},async safeEncodeAsync(e,t){return ld(this,e,t)},async safeDecodeAsync(e,t){return dd(this,e,t)},toJSONSchema(e){return ml(this,{})(e)},get description(){return ue.get(this)?.description},get _def(){return this._zod.def}}),Oo=g("_ZodString",(e,t)=>{St.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)},b.derived({format:e=>ie(e).format??null,minLength:e=>ie(e).minimum??null,maxLength:e=>ie(e).maximum??null},{regex(...e){return this.check(nn(...e))},includes(...e){return this.check(an(...e))},startsWith(...e){return this.check(sn(...e))},endsWith(...e){return this.check(un(...e))},min(...e){return this.check(We(...e))},max(...e){return this.check(At(...e))},length(...e){return this.check(Pt(...e))},nonempty(...e){return this.check(We(1,...e))},lowercase(e){return this.check(rn(e))},uppercase(e){return this.check(on(e))},trim(){return this.check(pn())},normalize(...e){return this.check(dn(...e))},toLowerCase(){return this.check(mn())},toUpperCase(){return this.check(fn())},slugify(){return this.check(gn())}})),wn=g("ZodString",(e,t)=>{St.init(e,t),Oo.init(e,t)},{email(e){return this.check(Yi(No,e))},url(e){return this.check(dr(br,e))},jwt(e){return this.check(_o(Jo,e))},emoji(e){return this.check(ro(zo,e))},guid(e){return this.check(Xi(Do,e))},uuid(e){return this.check(Qi(Fe,e))},uuidv4(e){return this.check(eo(Fe,e))},uuidv6(e){return this.check(to(Fe,e))},uuidv7(e){return this.check(no(Fe,e))},nanoid(e){return this.check(io(Uo,e))},cuid(e){return this.check(oo(Lo,e))},cuid2(e){return this.check(ao(jo,e))},ulid(e){return this.check(so(Mo,e))},base64(e){return this.check(go(Ho,e))},base64url(e){return this.check(vo(Wo,e))},xid(e){return this.check(uo(Fo,e))},ksuid(e){return this.check(co(Zo,e))},ipv4(e){return this.check(lo(Bo,e))},ipv6(e){return this.check(po(Vo,e))},cidrv4(e){return this.check(mo(Go,e))},cidrv6(e){return this.check(fo(qo,e))},e164(e){return this.check(ho(Ko,e))},datetime(e){return this.check(pr(ut,e))},date(e){return this.check(mr(ct,e))},time(e){return this.check(fr(lt,e))},duration(e){return this.check(gr(dt,e))}});function _r(e){return Ac(wn,e)}var K=g("ZodStringFormat",(e,t)=>{H.init(e,t),Oo.init(e,t)}),ut=g("ZodISODateTime",(e,t)=>{yu.init(e,t),K.init(e,t)}),ct=g("ZodISODate",(e,t)=>{bu.init(e,t),K.init(e,t)}),lt=g("ZodISOTime",(e,t)=>{wu.init(e,t),K.init(e,t)}),dt=g("ZodISODuration",(e,t)=>{$u.init(e,t),K.init(e,t)}),No=g("ZodEmail",(e,t)=>{uu.init(e,t),K.init(e,t)});function Gg(e){return Yi(No,e)}var Do=g("ZodGUID",(e,t)=>{au.init(e,t),K.init(e,t)});function qg(e){return Xi(Do,e)}var Fe=g("ZodUUID",(e,t)=>{su.init(e,t),K.init(e,t)});function Hg(e){return Qi(Fe,e)}function Wg(e){return eo(Fe,e)}function Kg(e){return to(Fe,e)}function Jg(e){return no(Fe,e)}var br=g("ZodURL",(e,t)=>{du.init(e,t),K.init(e,t)});function Yg(e){return dr(br,e)}function Xg(e){return dr(br,{protocol:Hn,hostname:$s,...b.normalizeParams(e)})}var zo=g("ZodEmoji",(e,t)=>{pu.init(e,t),K.init(e,t)});function Qg(e){return ro(zo,e)}var Uo=g("ZodNanoID",(e,t)=>{mu.init(e,t),K.init(e,t)});function ev(e){return io(Uo,e)}var Lo=g("ZodCUID",(e,t)=>{fu.init(e,t),K.init(e,t)});function tv(e){return oo(Lo,e)}var jo=g("ZodCUID2",(e,t)=>{gu.init(e,t),K.init(e,t)});function nv(e){return ao(jo,e)}var Mo=g("ZodULID",(e,t)=>{vu.init(e,t),K.init(e,t)});function rv(e){return so(Mo,e)}var Fo=g("ZodXID",(e,t)=>{hu.init(e,t),K.init(e,t)});function iv(e){return uo(Fo,e)}var Zo=g("ZodKSUID",(e,t)=>{_u.init(e,t),K.init(e,t)});function ov(e){return co(Zo,e)}var Bo=g("ZodIPv4",(e,t)=>{xu.init(e,t),K.init(e,t)});function av(e){return lo(Bo,e)}var pd=g("ZodMAC",(e,t)=>{Iu.init(e,t),K.init(e,t)});function sv(e){return Rc(pd,e)}var Vo=g("ZodIPv6",(e,t)=>{Su.init(e,t),K.init(e,t)});function uv(e){return po(Vo,e)}var Go=g("ZodCIDRv4",(e,t)=>{ku.init(e,t),K.init(e,t)});function cv(e){return mo(Go,e)}var qo=g("ZodCIDRv6",(e,t)=>{Eu.init(e,t),K.init(e,t)});function lv(e){return fo(qo,e)}var Ho=g("ZodBase64",(e,t)=>{Tu.init(e,t),K.init(e,t)});function dv(e){return go(Ho,e)}var Wo=g("ZodBase64URL",(e,t)=>{Au.init(e,t),K.init(e,t)});function pv(e){return vo(Wo,e)}var Ko=g("ZodE164",(e,t)=>{Pu.init(e,t),K.init(e,t)});function mv(e){return ho(Ko,e)}var md=g("ZodCreditCard",(e,t)=>{Ru.init(e,t),K.init(e,t)});function fv(e){return Cc(md,e)}var fd=g("ZodIBAN",(e,t)=>{Cu.init(e,t),K.init(e,t)});function gv(e){return Oc(fd,e)}var Jo=g("ZodJWT",(e,t)=>{Ou.init(e,t),K.init(e,t)});function vv(e){return _o(Jo,e)}var Dt=g("ZodCustomStringFormat",(e,t)=>{Nu.init(e,t),K.init(e,t)});function hv(e,t,r={}){return Rt(Dt,e,t,r)}function _v(e){return Rt(Dt,"hostname",ws,e)}function yv(e){return Rt(Dt,"hex",zs,e)}function bv(e){return Rt(Dt,"currency_code",Ss,e)}function wv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Re[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Rt(Dt,o,n,t)}var $n=g("ZodNumber",(e,t)=>{Ci.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hl(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ie(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ie(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ie(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ie(e).format??null},{gt(e,t){return this.check(je(e,t))},gte(e,t){return this.check(ke(e,t))},min(e,t){return this.check(ke(e,t))},lt(e,t){return this.check(Le(e,t))},lte(e,t){return this.check(Ie(e,t))},max(e,t){return this.check(Ie(e,t))},int(e){return this.check(Ro(e))},safe(e){return this.check(Ro(e))},positive(e){return this.check(je(0,e))},nonnegative(e){return this.check(ke(0,e))},negative(e){return this.check(Le(0,e))},nonpositive(e){return this.check(Ie(0,e))},multipleOf(e,t){return this.check(rt(e,t))},step(e,t){return this.check(rt(e,t))},finite(){return this}}));function gd(e){return Dc($n,e)}var zt=g("ZodNumberFormat",(e,t)=>{Du.init(e,t),$n.init(e,t)});function Ro(e){return Uc(zt,e)}function $v(e){return Lc(zt,e)}function xv(e){return jc(zt,e)}function Sv(e){return Mc(zt,e)}function Iv(e){return Fc(zt,e)}var xn=g("ZodBoolean",(e,t)=>{nr.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_l(e,r,o,n)});function vd(e){return Zc(xn,e)}var Sn=g("ZodBigInt",(e,t)=>{Oi.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yl(e,r,o,n)},b.derived({minValue:e=>ie(e).minimum??null,maxValue:e=>ie(e).maximum??null,format:e=>ie(e).format??null},{gte(e,t){return this.check(ke(e,t))},min(e,t){return this.check(ke(e,t))},gt(e,t){return this.check(je(e,t))},lt(e,t){return this.check(Le(e,t))},lte(e,t){return this.check(Ie(e,t))},max(e,t){return this.check(Ie(e,t))},positive(e){return this.check(je(BigInt(0),e))},negative(e){return this.check(Le(BigInt(0),e))},nonpositive(e){return this.check(Ie(BigInt(0),e))},nonnegative(e){return this.check(ke(BigInt(0),e))},multipleOf(e,t){return this.check(rt(e,t))}}));function kv(e){return Vc(Sn,e)}var Yo=g("ZodBigIntFormat",(e,t)=>{zu.init(e,t),Sn.init(e,t)});function Ev(e){return qc(Yo,e)}function Tv(e){return Hc(Yo,e)}var hd=g("ZodSymbol",(e,t)=>{Uu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bl(e,r,o,n)});function Av(e){return Wc(hd,e)}var _d=g("ZodUndefined",(e,t)=>{Lu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n)});function Pv(e){return Kc(_d,e)}var yd=g("ZodNull",(e,t)=>{ju.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function bd(e){return Jc(yd,e)}var wd=g("ZodAny",(e,t)=>{Mu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function Rv(){return Yc(wd)}var $d=g("ZodUnknown",(e,t)=>{Fu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)});function Ct(){return Xc($d)}var xd=g("ZodNever",(e,t)=>{Zu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sl(e,r,o,n)});function Xo(e){return Qc(xd,e)}var Sd=g("ZodVoid",(e,t)=>{Bu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Cv(e){return el(Sd,e)}var wr=g("ZodDate",(e,t)=>{Vu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.min=(r,o)=>e.check(ke(r,o)),e.max=(r,o)=>e.check(Ie(r,o))},b.derived({minDate:e=>{let{minimum:t}=ie(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ie(e);return t?new Date(t):null}},{}));function Ov(e){return tl(wr,e)}var Id=g("ZodArray",(e,t)=>{Nt(),qu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.element=t.element},{min(e,t){return this.check(We(e,t))},nonempty(e){return this.check(We(1,e))},max(e,t){return this.check(At(e,t))},length(e,t){return this.check(Pt(e,t))},unwrap(){return this.element}});function $r(e,t){return il(Id,e,t)}function Nv(e){let t=e._zod.def.shape;return Qo(Object.keys(t))}var xr=g("ZodObject",(e,t)=>{Nt(),Hu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Qo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ct()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ct()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Xo()}))},strip(){return this.clone(b.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return b.extend(this,e)},safeExtend(e){return b.safeExtend(this,e)},merge(e){return b.merge(this,e)},pick(e){return b.pick(this,e)},omit(e){return b.omit(this,e)},partial(...e){return b.partial(Ir,this,e[0])},exactPartial(...e){return b.partial(ta,this,e[0],"exactPartial")},required(...e){return b.required(na,this,e[0])}});function Dv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new xr(r)}function zv(e,t){return new xr({type:"object",shape:e,catchall:Xo(),...b.normalizeParams(t)})}function Uv(e,t){return new xr({type:"object",shape:e,catchall:Ct(),...b.normalizeParams(t)})}var Sr=g("ZodUnion",(e,t)=>{rr.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Io(e,r,o,n),e.options=t.options});function In(e,t){return new Sr({type:"union",options:e,...b.normalizeParams(t)})}var kd=g("ZodXor",(e,t)=>{Sr.init(e,t),Wu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Io(e,r,o,n),e.options=t.options});function Lv(e,t){return new kd({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var Ed=g("ZodDiscriminatedUnion",(e,t)=>{Sr.init(e,t),Ju.init(e,t)});function jv(e,t,r){return new Ed({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var Td=g("ZodIntersection",(e,t)=>{Yu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function Ad(e,t){return new Td({type:"intersection",left:e,right:t})}var Pd=g("ZodTuple",(e,t)=>{Nt(),Ni.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Ir({type:"optional",innerType:t}))})}});function Rd(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new Pd({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var yn=g("ZodRecord",(e,t)=>{Nt(),Xu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Cd(e,t,r){return!t||!t._zod?new yn({type:"record",keyType:_r(),valueType:e,...b.normalizeParams(t)}):new yn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function Mv(e,t,r){return new yn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Fv(e,t,r){return new yn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var Od=g("ZodMap",(e,t)=>{Nt(),Qu.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(Tt(...r))});function Zv(e,t,r){return new Od({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var Nd=g("ZodSet",(e,t)=>{Nt(),ec.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(Tt(...r))});function Bv(e,t){return new Nd({type:"set",valueType:e,...b.normalizeParams(t)})}var bn=g("ZodEnum",(e,t)=>{tc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Tl(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new bn({...t,checks:[],...b.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new bn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function Qo(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new bn({type:"enum",entries:r,...b.normalizeParams(t)})}function Vv(e,t){return new bn({type:"enum",entries:e,...b.normalizeParams(t)})}var Dd=g("ZodLiteral",(e,t)=>{nc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Gv(e,t){return new Dd({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var zd=g("ZodFile",(e,t)=>{rc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e.min=(r,o)=>e.check(Me(r,o)),e.max=(r,o)=>e.check(it(r,o)),e.mime=(r,o)=>e.check(ln(Array.isArray(r)?r:[r],o))});function qv(e){return ol(zd,e)}var Ud=g("ZodTransform",(e,t)=>{Nt(),ic.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new tt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(b.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push(b.issue(a))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ea(e){return new Ud({type:"transform",transform:e})}var Ir=g("ZodOptional",(e,t)=>{Di.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ot(e){return new Ir({type:"optional",innerType:e})}var ta=g("ZodExactOptional",(e,t)=>{oc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ld(e){return new ta({type:"optional",innerType:e})}var jd=g("ZodNullable",(e,t)=>{ac.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new jd({type:"nullable",innerType:e})}function Hv(e){return Ot(yr(e))}var Md=g("ZodDefault",(e,t)=>{sc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Fd(e,t){return new Md({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Zd=g("ZodPrefault",(e,t)=>{uc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bd(e,t){return new Zd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var na=g("ZodNonOptional",(e,t)=>{cc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Vd(e,t){return new na({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Gd=g("ZodSuccess",(e,t)=>{lc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Wv(e){return new Gd({type:"success",innerType:e})}var qd=g("ZodCatch",(e,t)=>{dc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Hd(e,t){return new qd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Wd=g("ZodNaN",(e,t)=>{pc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Kv(e){return rl(Wd,e)}var kr=g("ZodPipe",(e,t)=>{zi.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.in=t.in,e.out=t.out});function Co(e,t){return new kr({type:"pipe",in:e,out:t})}var Er=g("ZodCodec",(e,t)=>{kr.init(e,t),ir.init(e,t)});function Jv(e,t,r){return new Er({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Yv(e){let t=e._zod.def;return new Er({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Kd=g("ZodPreprocess",(e,t)=>{kr.init(e,t),mc.init(e,t)}),Jd=g("ZodReadonly",(e,t)=>{fc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Yd(e){return new Jd({type:"readonly",innerType:e})}var Xd=g("ZodTemplateLiteral",(e,t)=>{gc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Xv(e,t){return new Xd({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Qd=g("ZodLazy",(e,t)=>{or.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function ep(e){return new Qd({type:"lazy",getter:e})}var tp=g("ZodPromise",(e,t)=>{hc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qv(e){return new tp({type:"promise",innerType:e})}var np=g("ZodFunction",(e,t)=>{vc.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n)});function eh(e){return new np({type:"function",input:Array.isArray(e?.input)?Rd(e?.input):e?.input??$r(Ct()),output:e?.output??Ct()})}var Tr=g("ZodCustom",(e,t)=>{_c.init(e,t),L.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function th(e){let t=new J({check:"custom"});return t._zod.check=e,t}function nh(e,t){return al(Tr,e??(()=>!0),t)}function rp(e,t={}){return sl(Tr,e,t)}function ip(e,t){return ul(e,t)}var rh=cl,ih=ll,op=g("ZodInstanceOf",(e,t)=>{Tr.init(e,t)},{properties(e,t){return this.check(cn(e,t))}});function oh(e,t={}){let r=new op({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...b.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var ah=(...e)=>dl({Codec:Er,Boolean:xn,String:wn},...e);function sh(e){let t=ep(()=>In([_r(e),gd(),vd(),bd(),$r(t),Cd(_r(),t)]));return t}function uh(e,t){return new Kd({type:"pipe",in:ea(e),out:t})}var fI={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function gI(e){te({customError:e})}function vI(){return te().customError}var ap;ap||(ap={});var Ar={};Be(Ar,{ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,date:()=>_I,datetime:()=>hI,duration:()=>bI,time:()=>yI});function hI(e){return pr(ut,e)}function _I(e){return mr(ct,e)}function yI(e){return fr(lt,e)}function bI(e){return gr(dt,e)}var T={...kn,...Ao,iso:Ar},wI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function $I(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function ch(e,t){return e.map((r,o)=>o<t?r:r.optional())}function xI(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function SI(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:xI(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function II(e,t){return T.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function sp(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let s=sp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=sp(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var kI=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),EI=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Pr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Pr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>kI.has(t)?Pr(r):!EI.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Pr))}function lh(e){return e===1?"element":"elements"}function TI(e,t){return T.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let s=sp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${lh(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${lh(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function dh(e,t){if(e!==!1)return e===void 0||e===!0?T.any():ve(e,t)}var AI=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function ph(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return T.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return T.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=SI(n,t),a=ve(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return T.null();if(n.length===0)return T.never();if(n.length===1)return T.literal(n[0]);if(n.every(a=>typeof a=="string"))return T.enum(n);let i=n.map(a=>T.literal(a));return i.length<2?i[0]:T.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return T.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return ph(a,t)});return n.length===0?T.never():n.length===1?n[0]:T.union(n)}if(!r)return T.any();let o;switch(r){case"string":{let n=T.string();if(e.format){let i=e.format;i==="email"?n=n.check(T.email()):i==="uri"||i==="uri-reference"?n=n.check(T.url()):i==="uuid"||i==="guid"?n=n.check(T.uuid()):i==="date-time"?n=n.check(T.iso.datetime({offset:!0})):i==="date"?n=n.check(T.iso.date()):i==="time"?n=n.check(T.regex(AI)):i==="duration"?n=n.check(T.iso.duration()):i==="hostname"?n=n.check(T.hostname()):i==="ipv4"?n=n.check(T.ipv4()):i==="ipv6"?n=n.check(T.ipv6()):i==="mac"?n=n.check(T.mac()):i==="cidr"?n=n.check(T.cidrv4()):i==="cidr-v6"?n=n.check(T.cidrv6()):i==="base64"?n=n.check(T.base64()):i==="base64url"?n=n.check(T.base64url()):i==="e164"?n=n.check(T.e164()):i==="credit_card"?n=n.check(T.creditCard()):i==="iban"?n=n.check(T.iban()):i==="jwt"?n=n.check(T.jwt()):i==="emoji"?n=n.check(T.emoji()):i==="nanoid"?n=n.check(T.nanoid()):i==="cuid"?n=n.check(T.cuid()):i==="cuid2"?n=n.check(T.cuid2()):i==="ulid"?n=n.check(T.ulid()):i==="xid"?n=n.check(T.xid()):i==="ksuid"&&(n=n.check(T.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?T.number().int():T.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=T.boolean();break}case"null":{o=T.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ve(e.additionalProperties,t):void 0;for(let[d,m]of Object.entries(i)){let p=ve(m,t);se(n,d,a.has(d)?p:p.optional())}if(e.patternProperties){let d=e.patternProperties,m=Object.keys(d),p=[];for(let _ of m){let x=ve(d[_],t),E=T.string().regex(new RegExp(_));p.push(T.looseRecord(E,x))}let v=[];if(Object.keys(n).length>0&&v.push(T.object(n).passthrough()),v.push(...p),v.length===0)o=T.object({}).passthrough();else if(v.length===1)o=v[0];else{let _=T.intersection(v[0],v[1]);for(let x=2;x<v.length;x++)_=T.intersection(_,v[x]);o=_}if(e.additionalProperties===!1){let _=Object.keys(n),x=m.map(k=>new RegExp(k)),E=o;o=o.check(k=>{if(!Ae(k.value))return;let A=[];for(let S of Object.keys(k.value))_.includes(S)||x.some(O=>O.test(S))||A.push(S);A.length&&k.issues.push({code:"unrecognized_keys",keys:A,input:k.value,inst:E})})}}else{let d=T.object(n);e.additionalProperties===!1?o=d.strict():s?o=d.catchall(s):o=d.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||l!==void 0){let d;if(u){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=ve(m,t)}o=II(o,{keySchema:d,minProperties:c,maxProperties:l})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(d=>ve(d,t)),u=ch(s,a),c=Array.isArray(i)?void 0:dh(i,t),l=T.tuple(u);o=c?l.rest(c):l,typeof e.minItems=="number"&&(o=o.check(T.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(T.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(d=>ve(d,t)),u=ch(s,a),c=dh(e.additionalItems,t),l=T.tuple(u);o=c?l.rest(c):l,typeof e.minItems=="number"&&(o=o.check(T.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(T.maxLength(e.maxItems)))}else if(i!==void 0){let a=ve(i,t),s=T.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=T.array(T.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=TI(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ve(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function ve(e,t){if(typeof e=="boolean")return e?T.any():T.never();let r=ph(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(c=>ve(c,t)),u=T.union(s);r=o?T.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(c=>ve(c,t)),u=T.xor(s);r=o?T.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:T.any();else{let s=o?r:ve(e.allOf[0],t),u=o?0:1;for(let c=u;c<e.allOf.length;c++)s=T.intersection(s,ve(e.allOf[c],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=T.nullable(r)),e.readOnly===!0&&(r=T.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Pr(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Pr(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))wI.has(s)||se(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function mh(e,t){if(typeof e=="boolean")return e?T.any():T.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=$I(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??ue};return ve(r,i)}var fh=Symbol("z.visit/resolving");function Rr(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===fh)return new or({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,fh);let u=i(a),c=r(u,u!==a);return o.set(a,c),c}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,l=Object.keys(c),d=!1,m={};for(let v of l){let _=n(c[v]);_!==c[v]&&(d=!0),m[v]=_}let p=s.catchall;return s.catchall&&(p=n(s.catchall),p!==s.catchall&&(d=!0)),d?q(a,{...s,shape:m,catchall:p}):a}case"array":{let c=n(s.element);return c===s.element?a:q(a,{...s,element:c})}case"tuple":{let c=s.items,l=!1,d=[];for(let p of c){let v=n(p);v!==p&&(l=!0),d.push(v)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(l=!0)),l?q(a,{...s,items:d,rest:m}):a}case"record":case"map":{let c=n(s.keyType),l=n(s.valueType);return c===s.keyType&&l===s.valueType?a:q(a,{...s,keyType:c,valueType:l})}case"set":{let c=n(s.valueType);return c===s.valueType?a:q(a,{...s,valueType:c})}case"union":{let c=s.options,l=!1,d=[];for(let m of c){let p=n(m);p!==m&&(l=!0),d.push(p)}return l?q(a,{...s,options:d}):a}case"intersection":{let c=n(s.left),l=n(s.right);return c===s.left&&l===s.right?a:q(a,{...s,left:c,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=n(s.innerType);return c===s.innerType?a:q(a,{...s,innerType:c})}case"pipe":{let c=n(s.in),l=n(s.out);return c===s.in&&l===s.out?a:q(a,{...s,in:c,out:l})}case"function":{let c=n(s.input),l=n(s.output);return c===s.input&&l===s.output?a:q(a,{...s,input:c,output:l})}case"lazy":{let c=s.getter,{_cachedInner:l,...d}=s;return q(a,{...d,getter:()=>n(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function gh(e){return Rr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:In(r.options)}})}function PI(e,t){if(!t?.length)return e;let r=e._zod.def;return q(e,Ne(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function vh(e){return PI(e.out,e.checks)}function RI(e){return e.in._zod.traits.has("$ZodTransform")?vh(e):e.in}function hh(e){return Rr(e,{pipe:t=>RI(t._zod.def),default:(t,r)=>r?Ot(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function _h(e){return Rr(e,{pipe:t=>vh(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var up={};Be(up,{bigint:()=>DI,boolean:()=>NI,date:()=>zI,number:()=>OI,string:()=>CI});function CI(e){return Pc(wn,e)}function OI(e){return zc($n,e)}function NI(e){return Bc(xn,e)}function DI(e){return Gc(Sn,e)}function zI(e){return nl(wr,e)}var UI=f.object({id:f.string().regex(/^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/).max(120),scope:f.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/)}).strict(),yh=f.array(UI).max(8).superRefine((e,t)=>{let r=e.map(({id:o,scope:n})=>`${o}:${n}`);new Set(r).size!==r.length&&t.addIssue({code:"custom",message:"Duplicate fixture binding"})});function cp(e){return new TextEncoder().encode(e).byteLength}var bh=128*1024,wh=512*1024,$h=64,xh=f.string().max(240).regex(/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*(\/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*)*$/,"Use a relative file path such as db/restore.py; absolute paths and dot segments are not allowed"),Sh=f.string().refine(e=>cp(e)<=bh&&!e.includes("\0"),`File contents must be text without null bytes, at most ${bh} UTF-8 bytes`),OD=f.record(xh,Sh.nullable()),lp=f.record(xh,Sh).superRefine((e,t)=>{let r=Object.keys(e);(r.length>$h||Object.values(e).reduce((o,n)=>o+cp(n),0)>wh)&&t.addIssue({code:"custom",message:`Save at most ${$h} helper files totaling ${wh} UTF-8 bytes`});for(let o of r){let n=o.split("/");for(let i=1;i<n.length;i++)Object.prototype.hasOwnProperty.call(e,n.slice(0,i).join("/"))&&t.addIssue({code:"custom",message:`File ${o} has a parent that is also a file`})}});var LI=/'/g,jI=/^[A-Za-z0-9_./:=@,+-]+$/,ra=/^[A-Za-z_][A-Za-z0-9_]*$/;function MI(e){return`'${e.replace(LI,"'\\''")}'`}function pt(e){return e===""?"''":jI.test(e)?e:MI(e)}var FI=12,ZI=10;var BI=f.object({name:f.string().regex(ra).max(128),description:f.string().trim().min(1).max(300),values:f.array(f.string().min(1).max(200)).min(2).max(ZI).describe("Public non-secret setting values. Sent to QA models and shown in GitHub results.").optional()}).strict(),Ih=f.array(BI).max(FI);var Cr={Compose:"compose",Command:"command"};var kh=8,VI=64,Ah=/^\/workspace\/(?!\.+$)(?!.*\.\.)[A-Za-z0-9._-]+$/,GI=f.object({repoOwner:f.string().trim().min(1,"repoOwner is required"),repoName:f.string().trim().min(1,"repoName is required"),sandboxPath:f.string().regex(Ah,"sandboxPath must be a single path segment under /workspace").optional()}).strict();function qI(e){return e.sandboxPath??`/workspace/${e.repoName}`}var KD=f.array(GI).min(1,"at least one repo is required").max(kh,`at most ${kh} repos are allowed`).superRefine((e,t)=>{if(e.length===0)return;let r=e[0].repoOwner.toLowerCase();e[0].sandboxPath!==void 0&&t.addIssue({code:"custom",path:[0,"sandboxPath"],message:`the primary repo is always cloned to /workspace/${e[0].repoName}`});let o=new Set,n=new Set;e.forEach((i,a)=>{i.repoOwner.toLowerCase()!==r&&t.addIssue({code:"custom",path:[a,"repoOwner"],message:"all repos must share the primary repo's owner"});let s=`${i.repoOwner}/${i.repoName}`.toLowerCase();o.has(s)&&t.addIssue({code:"custom",path:[a],message:`duplicate repo ${i.repoOwner}/${i.repoName}`}),o.add(s);let u=qI(i);if(!Ah.test(u)){t.addIssue({code:"custom",path:[a],message:`repo name ${i.repoName} needs an explicit sandboxPath`});return}n.has(u)&&t.addIssue({code:"custom",path:[a],message:`sandbox path ${u} is already taken`}),n.add(u)})}),Eh=f.object({name:f.string(),envVar:f.string()}),Or=f.record(f.string().regex(ra,"must be a POSIX-style environment variable name"),f.string()),Ph=f.object({type:f.enum([Cr.Compose]),files:f.array(f.string()).optional(),service:f.string().optional(),profiles:f.array(f.string()).optional()}).strict(),dp=f.object({fixtures:yh.optional(),cwd:f.string().optional(),bootScript:f.string().max(65536).describe("Optional bash bringup script. When set it overrides the entry: arcanist-app start runs it on the sandbox host from cwd with runtimeVariables plus HOST and PORT, and waits on ready.path. The app must listen on url.hostPort. Leave unset to boot from the entry.").optional(),kind:f.string().optional(),runner:f.string().optional(),entry:Ph.optional(),url:f.object({hostPort:f.number().int().optional(),path:f.string().optional()}).strict().optional(),portMapping:f.object({containerPort:f.number().int().optional()}).strict().optional(),additionalPorts:f.array(f.object({service:f.string().optional(),hostPort:f.number().int().optional(),containerPort:f.number().int().optional()}).strict()).optional(),runtimeVariables:Or.optional(),composeEnv:Or.optional(),generatedComposeEnv:f.record(f.string(),f.union([f.object({type:f.literal("alphanumeric"),length:f.number().int()}).strict(),f.object({type:f.literal("hex"),bytes:f.number().int()}).strict()])).optional(),env:Or.optional(),ready:f.object({path:f.string().optional(),nonEmptyPath:f.string().optional(),timeoutSeconds:f.number().int().optional()}).strict().optional(),open:f.object({path:f.string().optional()}).strict().optional(),renderedPathPrefixes:f.array(f.string().max(512)).max(VI).describe("Repo-relative directories the booted app is built from. When set, a review boots the app only when the diff touches a non-test file under one of them; when unset, the file-extension heuristic decides.").optional(),auth:f.object({command:f.string().optional(),validatePath:f.string().optional(),browserStateEnvVar:f.string().optional(),credentials:f.array(Eh).optional()}).strict().optional(),e2e:f.object({testCommand:f.string(),seedCommand:f.string().optional(),resetCommand:f.string().optional(),credentials:f.array(Eh).optional()}).strict().optional(),qaSwitches:Ih.describe("Runtime variables QA may switch, each with the only values it may take (default true/false). A QA run restarts the app with the chosen values so a flag-gated change can be tested on and off.").optional()}).strict(),HI="dockerfile",WI=f.union([f.object({type:f.literal(Cr.Command),command:f.string().optional()}).passthrough(),f.object({type:f.literal(HI),context:f.string().optional(),dockerfile:f.string().optional(),service:f.string().optional()}).passthrough()]),Rh=dp.extend({entry:f.union([Ph,WI]).optional()}),KI=/^[a-z][a-z0-9-]*$/;var Ch=f.object({id:f.string().trim().min(1).regex(KI),description:f.string().trim().min(1),config:dp}).strict(),JI=Ch.extend({config:Rh}),YI=f.array(Ch).superRefine((e,t)=>{new Set(e.map(r=>r.id)).size!==e.length&&t.addIssue({code:"custom",message:"App runtime names must be unique"})}),Th=["defect","walkthrough","edge-case"];var Oh=f.object({appDir:f.string().trim().min(1).max(512).describe("Repo-relative directory of the Expo or Xcode project."),bundleIdentifier:f.string().trim().min(1).optional(),scheme:f.string().trim().min(1).optional(),workspace:f.string().trim().min(1).optional(),backend:f.object({startCommand:f.string().trim().min(1).max(2e3).describe("Runs in the verifier sandbox from the repo root; exits 0 once the backend answers."),ports:f.array(f.number().int().min(1).max(65535)).min(1).max(8).describe("Localhost ports the app build dials; each is tunneled from the simulator to the same port.")}).strict().optional(),films:f.array(f.enum(Th)).min(1).max(Th.length).optional().describe("What a filmed review posts: `defect` (the flow to a confirmed defect, under its finding; the default), `walkthrough` (every screen the pull request touches, in the summary), `edge-case` (each edge case the planner asks and a run confirms).")}).strict(),JD=f.object({sandbox:f.object({appRuntime:dp.optional(),appRuntimes:YI.optional(),helperFiles:lp.optional(),runtimeVariables:Or.optional(),iosApp:Oh.optional()}).strict().refine(e=>e.appRuntime===void 0||e.appRuntimes===void 0,{message:"Supply appRuntimes or legacy appRuntime, not both"}).optional()}).strict(),YD=f.object({sandbox:f.object({appRuntime:Rh.optional(),appRuntimes:f.array(JI).optional(),helperFiles:lp.optional(),runtimeVariables:Or.optional(),iosApp:Oh.optional()}).strict().optional()}).strict();function pp(e){if(!e)return null;let t=e.entry;if(t===void 0||t.type===Cr.Compose)return e;let{entry:r,...o}=e,n=t.type===Cr.Command?t.command?.trim():void 0,i=e.bootScript?.trim()?e.bootScript:n||e.bootScript;return{...o,...i!==void 0?{bootScript:i}:{}}}var ia=1,XI=["name","description","provisioningKind","provisioningConfig","helperFiles","cache","networkPolicy"];function QI(e){let t=e?.sandbox;if(!t)return e;let{appRuntime:r,appRuntimes:o,...n}=t;return{...e,sandbox:{...n,...r?{appRuntime:pp(r)}:{},...o?{appRuntimes:o.map(i=>({...i,config:pp(i.config)}))}:{}}}}function oa(e){let{status:t,setupScript:r,maintenanceScript:o,smokeTestScript:n,dependencies:i,cpuCount:a,memoryMB:s}=e.cache;return{name:e.name,description:e.description,provisioningKind:e.provisioningKind,provisioningConfig:QI(e.provisioningConfig),...e.helperFiles!==void 0?{helperFiles:e.helperFiles}:{},cache:{status:t,setupScript:r,maintenanceScript:o,smokeTestScript:n,dependencies:i,cpuCount:a,memoryMB:s},networkPolicy:e.networkPolicy}}function Nh(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([o],[n])=>o.localeCompare(n))):r)}function Dh(e,t){let r={...oa(e),repos:e.repos},o={...t.environment,repos:t.repos};return[...XI,"repos"].filter(n=>Nh(r[n]??null)!==Nh(o[n]??null))}function zh(e,t){let r=oa(e).helperFiles??{},o=t.environment.helperFiles??{},i=[...new Set([...Object.keys(r),...Object.keys(o)])].filter(a=>(r[a]??null)!==(o[a]??null)).sort();return i.length>0?i:void 0}var ek=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+)$/,tk=/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/,nk=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/,rk=/^(\d+)(?:\.(diff|patch))?$/i,Uh=/^[A-Za-z0-9_.-]+$/,ik=/^[A-Za-z0-9_.][A-Za-z0-9_.-]*$/;function Lh(e){return typeof e!="string"||!e||e.length>100||e==="."||e===".."?!1:ik.test(e)}function ok(e,t){return Lh(e)&&Lh(t)?{owner:e,repo:t}:null}function aa(e){let t=e.match(ek)??e.match(tk)??e.match(nk);return t?ok(t[1],t[2]):null}var ak=500;function sk(e){if(typeof e!="string")return null;let t=e.trim();if(!t||t.length>ak)return null;let r;try{r=new URL(t)}catch{return null}if(r.protocol!=="https:"||r.hostname.toLowerCase()!=="github.com")return null;let o=r.pathname.split("/").filter(Boolean),n=o.length>=4?rk.exec(o[3]):null;return o[2]!=="pull"||n===null||n[2]!==void 0&&o.length!==4||!Uh.test(o[0])||!Uh.test(o[1])?null:`https://github.com/${o[0]}/${o[1]}/pull/${n[1]}`}function jh(e){let t=sk(e);if(!t)return null;let r=t.slice(19).split("/"),o=Number(r[3]);return!Number.isInteger(o)||o<=0?null:{prUrl:t,owner:r[0],repo:r[1],number:o}}import{execFileSync as Mh}from"node:child_process";function Nr(e,t){try{return Mh("git",e,{encoding:"utf8",stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.input===void 0?{}:{input:t.input},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(r){throw new y("user",`git ${e.join(" ")} failed: ${xe(r)}`)}}function Fh(e,t){let r;try{r=Mh("git",e,{stdio:["ignore","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(o){throw new y("user",`git ${e.join(" ")} failed: ${xe(o)}`)}try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new y("user","A changed file has a file name that is not valid UTF-8, so it cannot be reviewed.",{hint:"Rename the file, commit, then run the review again."})}}function Dr(e,t={}){return Nr(e,t).trim()}function Zh(e){let t=`Pass the ${e} as owner/name.`,r;try{r=Dr(["remote","get-url","origin"])}catch{throw new y("user","This directory has no git `origin` remote to read the repository from.",{hint:t})}let o=aa(r);if(!o)throw new y("user","origin remote must point at a GitHub repository",{hint:t});return{owner:o.owner,repo:o.repo}}var uk=/\.git$/;function ck(e,t){let r=aa(e);if(!r)throw new y("user",`${t} must be owner/name or a GitHub URL`);return{owner:r.owner,repo:r.repo.replace(uk,"")}}function mt(e,t="repo"){return e===void 0?Zh(t):ck(e,t)}var lk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Bh(e){return(await R(e,P("/api/environments"))).data.environments}function Vh(e,t){return e.find(r=>r.scope==="team"&&r.repoOwner.toLowerCase()===t.owner.toLowerCase()&&r.repoName.toLowerCase()===t.repo.toLowerCase())}async function Gh(e,t){return Vh(await Bh(e),t)??null}async function mp(e,t){let r=await Bh(e);if(t&&lk.test(t)){let i=r.find(a=>a.id===t);if(!i)throw new y("user",`No environment with id ${t}.`);return i}let o=mt(t,"environment"),n=Vh(r,o);if(!n)throw new y("user",`No team environment for ${o.owner}/${o.repo}.`,{hint:"Run `arcanist environments status` first."});return n}async function qh(e,t){return(await R(e,P("/api/environments/:id",{id:t}))).data}function mk(e,t){let r;try{r=JSON.parse(e)}catch{throw new y("user",`${t} is not valid JSON.`)}let o=r;if(!o||o.version!==ia||!o.environment||typeof o.environment.name!="string"||!o.environment.cache||!Array.isArray(o.repos)||o.repos.length===0)throw new y("user",`${t} is not an Environment export (version ${ia}).`,{hint:"Write one with `arcanist environments export owner/repo -o <file>`."});return o}async function Hh(e,t={},r){let{config:o}=Y(r,t),n=await mp(o,e),i=await qh(o,n.id),a={version:ia,exportedFrom:{apiUrl:o.apiUrl,environmentId:i.id,configurationGeneration:i.cache.configurationGeneration,exportedAt:new Date().toISOString()},repos:i.repos,environment:oa(i)},s=`${JSON.stringify(a,null,2)}
71
+ `;if(t.output){await pk(t.output,s,"utf8"),D(r,t,{environmentId:i.id,name:i.name,configurationGeneration:i.cache.configurationGeneration,path:t.output},u=>{console.log(`Exported "${F(u.name)}" (generation ${u.configurationGeneration}) to ${u.path}`)});return}process.stdout.write(s)}async function fk(e,t,r,o){let n=t.repos[0],i=`${n.repoOwner}/${n.repoName}`,{name:a}=t.environment;if(r.dryRun){D(o,r,{environmentId:null,name:a,created:!1,applied:!1},u=>{console.log(`Would create "${F(u.name)}" for ${i} (dry run; nothing was sent).`)});return}let s=await R(e,P("/api/environments"),{method:"POST",body:JSON.stringify({...t.environment,repos:t.repos,scope:"team"})});D(o,r,{environmentId:s.data.id,name:s.data.name,created:!0,applied:!0,configurationGeneration:{after:s.data.cache.configurationGeneration},buildScheduled:s.data.cache.status==="enabled"},u=>{console.log(`Created "${F(u.name)}" for ${i} (${u.environmentId}).`),u.buildScheduled&&console.log("A build is scheduled; watch it with `arcanist environments status --wait`.")})}async function Wh(e,t,r={},o){let n=mk(await dk(e,"utf8"),e),{config:i}=Y(o,r),a=n.repos[0],s=t===void 0?await Gh(i,{owner:a.repoOwner,repo:a.repoName}):await mp(i,t);if(!s){if(!r.create)throw new y("user",`No team environment for ${a.repoOwner}/${a.repoName}.`,{hint:"Pass --create to create it from this file."});await fk(i,n,r,o);return}let u=await qh(i,s.id),c=u.repos[0]??{repoOwner:u.repoOwner,repoName:u.repoName};if(c.repoOwner.toLowerCase()!==a.repoOwner.toLowerCase()||c.repoName.toLowerCase()!==a.repoName.toLowerCase())throw new y("user",`${e} was exported for ${a.repoOwner}/${a.repoName}, but the target environment's primary repository is ${c.repoOwner}/${c.repoName}.`,{hint:"An Environment's primary repository cannot change; export from a matching repository."});let l=Dh(u,n),d=zh(u,n),m={environmentId:u.id,name:u.name,changedFields:l,...d?{driftedHelperFilePaths:d}:{},configurationGeneration:{before:u.cache.configurationGeneration}};if(r.dryRun&&l.length>0&&await R(i,`${P("/api/environments/:id",{id:u.id})}?dryRun=1`,{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),r.dryRun||l.length===0){D(o,r,{...m,applied:!1},_=>{console.log(_.changedFields.length===0?`"${F(_.name)}" already matches ${e}; nothing to apply.`:`Would change ${_.changedFields.join(", ")} on "${F(_.name)}" (dry run).`)});return}let p=await R(i,P("/api/environments/:id",{id:u.id}),{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos,expectedWriteVersion:u.writeVersion})}),v=p.data.cache.configurationGeneration;D(o,r,{...m,applied:!0,configurationGeneration:{before:u.cache.configurationGeneration,after:v},rebuildScheduled:v!==u.cache.configurationGeneration&&p.data.cache.status==="enabled"},_=>{console.log(`Applied ${_.changedFields.join(", ")} to "${F(_.name)}" (generation ${_.configurationGeneration.before} -> ${_.configurationGeneration.after}).`),_.rebuildScheduled&&console.log("A rebuild is scheduled; watch it with `arcanist environments status --wait`.")})}var zr="GitHub could not verify your organization role because the Arcanist GitHub App needs additional permissions. Ask an organization owner to approve the pending permissions in GitHub's installed apps settings, then try again.",sa="Arcanist could not verify your GitHub account permissions. Try again. If this continues, reconnect GitHub and authorize your organization's SSO if required.";async function En(e){let t=Date.now()+e.timeoutMs,r=null;for(;Date.now()<t;){try{let o=await e.fetchStatus();if(r=null,o!==null)return o}catch(o){if(!rm(o))throw o;if(r===null){let n=o instanceof Error?o.message:String(o);process.stderr.write(`Status check failed (${n}). Still waiting; retrying every ${e.pollIntervalMs}ms.
72
+ `)}r=o}await Gr(e.pollIntervalMs)}throw r!==null?r:new y("server",e.timeoutMessage)}var Kh=250,ua=1e3,Jh=6e4,Yh=200;function Xh(e){return Bp(e)}var gk=/^\d+$/;function Ze(e,t={}){let r=t.defaultMs??ua,o=t.minMs??Kh,n=t.maxMs===void 0?Jh:t.maxMs;if(!e)return r;if(!gk.test(e))throw new y("user","Polling interval must be a non-negative integer.");let i=Number(e);if(i<o||n!==null&&i>n){let a=n===null?`at least ${o}`:`between ${o} and ${n}`;throw new y("user",`Polling interval must be ${a} milliseconds.`)}return i}var Tn=5e3,vk=7200*1e3;function fp(e){let t=mt(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function ft(e,t){let o=(await R(e,P("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=_k(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${pt(o.question.id)} --answer-stdin --json`:Qh(n,o.fullName);return{fullName:o.fullName,status:o.status,stage:o.stage,...o.buildStatus===void 0?{}:{buildStatus:o.buildStatus},...o.failureReason===void 0?{}:{failureReason:o.failureReason},...o.question===void 0?{}:{question:o.question},nextAction:n,command:i}}function hk(e){return e.nextAction==="wait"}function Qh(e,t){switch(e){case"prepare":return`arcanist environments prepare ${t}`;case"wait":return`arcanist environments status ${t} --wait`;case"retry":return`arcanist environments retry ${t}`;case"review":return null;case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function _k(e){return e.status==="not_started"?"prepare":e.status==="ready"?"review":e.question?"answer_question":e.status==="failed"?e.failureReason==="installation_missing"?"authorize_github":"retry":e.status==="escalated"&&e.stage!=="escalated_to_customer"&&e.stage!=="question_for_customer"?"wait_for_arcanist":"wait"}function ca(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${F(e.fullName)}: ${F(e.status)}${t?` (${F(t)})`:""}`)}async function gp(e,t,r){return En({pollIntervalMs:r,timeoutMs:vk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await ft(e,t);return hk(o)?null:o}})}async function vp(e,t){return(await R(e,P("/api/settings/repositories/onboarding"),{method:"POST",body:JSON.stringify({repositories:t.repositories.map(({owner:o,repo:n})=>({owner:o,name:n})),...t.workspace?{workspace:!0}:{}})})).repositories}async function e_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t);await R(i,P("/api/repos"));let a=t.wait?await gp(i,n.fullName,o??Tn):await ft(i,n.fullName);D(r,t,{repository:a},({repository:s})=>ca(s))}async function t_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t),[a]=await vp(i,{repositories:[n]});if(!a)throw new y("server","Environment setup returned no repository result.");if(a.status==="forbidden"&&a.reason==="installation_admin_required")throw new y("auth",`Ask a workspace admin to connect the Arcanist GitHub App for ${n.owner} before preparing ${n.fullName}.`);if(a.status==="forbidden"&&a.reason==="installation_github_admin_required")throw new y("auth",`An admin of the ${n.owner} GitHub account must connect the Arcanist GitHub App before ${n.fullName} can be prepared.`);if(a.status==="forbidden"&&a.reason==="repository_limit")throw new y("auth",`This workspace has reached its limit of repositories with an environment, so ${n.fullName} cannot be prepared. Upgrade to Team, or ask Arcanist to raise the limit.`);if(a.status==="forbidden")throw new y("auth",`You must have write access to ${n.fullName} to prepare its environment.`);if(a.status==="failed")throw a.reason==="installation_github_permissions_required"?new y("auth",zr):a.reason==="installation_github_check_failed"?new y("server",sa):new y("server",`Environment setup could not be started for ${n.fullName}.`);if(t.wait&&(a.status==="queued"||a.status==="already_queued")){let c=await gp(i,n.fullName,o??Tn);D(r,t,{repository:c},({repository:l})=>ca(l));return}let s=a.status==="already_ready"?"review":"wait",u={fullName:a.fullName,status:a.status==="already_ready"?"ready":"pending",stage:null,nextAction:s,command:Qh(s,a.fullName)};D(r,t,{repository:u},({repository:c})=>ca(c))}async function n_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=fp(e),{config:i}=Y(r,t);await R(i,P("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await gp(i,n.fullName,o??Tn):await ft(i,n.fullName);D(r,t,{repository:a},({repository:s})=>ca(s))}var yk=["openai","anthropic","baseten"],r_=f.enum(yk),i_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),Hz=f.object({managedFallback:f.boolean()}).strict(),o_=f.object({name:f.string().trim().min(1).max(80)}).strict();var la=class e{static register(t){let r=t.command("keys").description("Manage workspace inference-only API keys (admins)");r.command("list").description("List key metadata; secrets are never returned").option("--cursor <cursor>","Continue from nextCursor").option("--limit <limit>","Page size: 10, 25, or 50","25").action((o,n)=>e.list(o,n)),r.command("create <name>").description("Create an inference key and print its secret once; save it securely").action((o,n,i)=>e.create(o,n,i)),r.command("revoke <id>").description("Revoke a key for subsequent inference requests").action((o,n,i)=>e.revoke(o,n,i))}static async list(t,r){let{config:o}=Y(r,t);if(!["10","25","50"].includes(t.limit??"25"))throw new y("user","limit must be 10, 25, or 50.");let n=new URLSearchParams({limit:t.limit??"25"});t.cursor&&n.set("cursor",t.cursor);let i=await R(o,`${P("/api/inference/keys")}?${n}`);D(r,t,i,a=>{for(let s of a.keys)console.log(`${s.id} ${s.name} ${s.keyPrefix}\u2026 ${s.revokedAt===null?"active":"revoked"}`);a.nextCursor&&console.log(`Next page: --cursor ${a.nextCursor}`)})}static async create(t,r,o){let n=o_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=Y(o,r),a=await R(i,P("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});D(o,r,a,s=>{console.log(`Created ${s.key.name} (${s.key.id}). Save this secret now; it cannot be retrieved again.`),console.log(s.secret)})}static async revoke(t,r,o){let{config:n}=Y(o,r),i=await R(n,P("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});D(o,r,i,()=>console.log("Inference key revoked. Existing streams may finish."))}};var da=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");la.register(r);let o=r.command("providers").description("Manage OpenAI, Anthropic, and Baseten keys (workspace admins)");o.command("list").description("Show saved keys and fallback preferences; never reveals keys").action((n,i)=>e.list(n,i)),o.command("set-key <provider>").description("Add or replace a provider key through stdin").option("--key-stdin","Read the key from stdin; never include keys in command arguments").action((n,i,a)=>e.setKey(n,i,a)),o.command("remove-key <provider>").description("Remove the saved key, keeping the fallback preference").action((n,i,a)=>e.removeKey(n,i,a)),o.command("fallback <provider> <on|off>").description("Save opt-in fallback to Arcanist-managed inference at public provider prices").action((n,i,a,s)=>e.fallback(n,i,a,s)),r.command("usage").description("Show workflow usage availability; proxy metering is not connected yet").action((n,i)=>e.usage(n,i))}static provider(t){let r=r_.safeParse(t);if(!r.success)throw new y("user","Provider must be openai, anthropic, or baseten.");return r.data}static async settings(t,r,o,n){let{config:i}=Y(o,r),a=await R(i,t,n);D(o,r,a,s=>{for(let u of s.providers)console.log(`${u.provider} ${u.configured?`key \u2026${u.keySuffix} (not verified)`:"no key"} fallback ${u.managedFallback?"on":"off"}`);console.log("Preferences saved for future proxy routing; live traffic is unchanged.")})}static list(t,r){return e.settings(P("/api/inference/providers"),t,r)}static async setKey(t,r,o){let n=e.provider(t);if(!r.keyStdin||process.stdin.isTTY)throw new y("user","Pipe the key through --key-stdin.");let i=i_.safeParse({key:await jt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(P("/api/inference/providers/:provider/key",{provider:n}),r,o,{method:"PUT",body:JSON.stringify(i.data)})}static removeKey(t,r,o){let n=e.provider(t);return e.settings(P("/api/inference/providers/:provider/key",{provider:n}),r,o,{method:"DELETE"})}static fallback(t,r,o,n){let i=e.provider(t);if(r!=="on"&&r!=="off")throw new y("user","Fallback must be on or off.");return e.settings(P("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async usage(t,r){let{config:o}=Y(r,t),n=await R(o,P("/api/inference/usage"));D(r,t,n,()=>console.log("Workflow usage is unavailable until proxy metering is connected. No spend totals are being reported."))}};var a_="The prepared environment was unavailable for this review. Arcanist may have run checks from a fresh checkout, but could not use the prepared app environment.";import{execFileSync as v_}from"node:child_process";import{basename as Pk,extname as Rk}from"node:path";function s_(e){return e.blocking===!0}var bk=/[.!]+$/u,u_=["clear","issues_found","inconclusive"];var wk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},c_="blocks merge";var l_="\u2705 Ruled out";function d_(e){return e.replace(bk,"")}function p_(e){return wk[e==="do_not_merge"?"do_not_merge":"merge"]}function $k(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function xk(e){return s_(e)?"blocking":"non_blocking"}function Sk(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function m_(e){let t=$k(e).prFindings,r=t.map(s=>({finding:s,impact:xk(s)})),o=[...r].sort((s,u)=>+(s.impact!=="blocking")-+(u.impact!=="blocking")),n=r.filter(s=>s.impact==="blocking").length,i={blocking:n,nonBlocking:r.length-n,nits:0},a=Sk(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var _p=3e6,hp=f.string().regex(/^[0-9a-f]{40}$/),Ik=["added","modified","removed","renamed"],kk=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(Ik),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),Ek=f.object({sha:hp,subject:f.string(),body:f.string()}),gU=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:hp,headRef:f.string().min(1),headSha:hp,files:f.array(kk).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(Ek),heldBackPaths:f.array(f.string())});function f_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var Tk=["running","completed","failed"],Ak=f.object({requestId:f.string().min(1),sessionId:f.string().min(1).nullable(),createdAt:f.number().int(),repoOwner:f.string().min(1),repoName:f.string().min(1),headRef:f.string().min(1),baseRef:f.string().min(1),headShortSha:f.string().min(1),status:f.enum(Tk),verdict:f.enum(u_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),vU=f.object({reviews:f.array(Ak),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var Ck=/^origin\//,Ok=/^new file mode /m,Nk=/^deleted file mode /m,Dk=/^\.\//,zk=/\/+$/,g_=64*1024*1024,Uk=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),Lk=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),jk=[".example",".sample",".template"];function h_(e){let t=e.cwd;if(Ur(["rev-parse","--is-inside-work-tree"],t)!=="true")throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Ur(["remote","get-url","origin"],t);if(!r)throw new y("user","This checkout has no origin remote.",{hint:"Add your GitHub repository as origin: git remote add origin <url>"});if(e.base&&!Ur(["rev-parse","--verify","--quiet",`${e.base}^{commit}`],t))throw new y("user",`Base ref ${e.base} was not found.`,{hint:"Run `git fetch origin`, or pass a --base ref that exists locally, such as origin/main."});let o=e.base?{ref:e.base,label:e.base}:Mk(t),n=Dr(["rev-parse","HEAD"],{cwd:t}),i=Dr(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=Fk(Fh([...s,"--numstat","-z",a],{cwd:t,maxBuffer:g_})),c=Wk(t);if(u.length===0)throw new y("user",`No committed changes to review against ${o.ref}.`,{...c.length>0?{hint:`You have uncommitted changes in ${c.length} file(s). Commit them, then run arcanist review again.`}:{}});let l=Zk(Nr([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:g_}));if(l.length!==u.length)throw new y("user",`git diff listed ${u.length} files but printed ${l.length} patches.`);let d=new Set((e.include??[]).map(qk)),m=A=>d.has(A)||[...d].some(S=>A.startsWith(`${S}/`)),p=A=>A.previousPath?[A.path,A.previousPath]:[A.path],v=Gk(u.flatMap(p),t),_=[],x=[],E=[];if(u.forEach((A,S)=>{let O=l[S]??"";if(A.binary){x.push(A.path);return}if(p(A).some(G=>Vk(G)||v.has(G))&&!m(A.path)){E.push(A.path);return}_.push({path:A.path,...A.previousPath?{previousPath:A.previousPath}:{},status:Bk(O,A),additions:A.additions,deletions:A.deletions,patch:O})}),_.length===0)throw new y("user",`No reviewable changes against ${o.ref}.`,{hint:"Binary files are skipped and secret-looking files are held back; pass --include <path> to upload one."});let k={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Dr(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:f_(_),commitMessages:Hk(`${i}..HEAD`,t),heldBackPaths:E.sort()};return Kk(k),{payload:k,skippedBinaryPaths:x.sort(),uncommittedPaths:c}}function Mk(e){let t=[Ur(["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"],e)].concat(["origin/main","origin/master"]).filter(r=>typeof r=="string"&&r.length>0);for(let r of t)if(Ur(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(Ck,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Ur(e,t){try{return v_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).trim()}catch{return null}}function Fk(e){let t=e.split("\0"),r=[];for(let o=0;o<t.length;o+=1){let n=t[o];if(!n)continue;let[i="",a="",s=""]=n.split(" "),u={additions:i==="-"?0:Number(i),deletions:a==="-"?0:Number(a),binary:i==="-"&&a==="-"};if(s.length>0){r.push({path:s,...u});continue}let c=t[o+1]??"",l=t[o+2]??"";o+=2,r.push({path:l,previousPath:c,...u})}return r}function Zk(e){let t=[],r=null;for(let o of e.split(`
73
73
  `))o.startsWith("diff --git ")?(r&&t.push(`${r.join(`
74
74
  `)}
75
75
  `),r=[o]):r&&r.push(o);return r&&(r[r.length-1]===""&&r.pop(),t.push(`${r.join(`
@@ -77,7 +77,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
77
77
  `)),t}function Bk(e,t){if(t.previousPath)return"renamed";let r=e.slice(0,e.indexOf(`
78
78
  @@`)===-1?e.length:e.indexOf(`
79
79
  @@`));return Ok.test(r)?"added":Nk.test(r)?"removed":"modified"}function Vk(e){let t=Pk(e).toLowerCase();return t===".env"||t.startsWith(".env.")||t.endsWith(".env")?!jk.some(r=>t.endsWith(r)):Lk.has(t)||Uk.has(Rk(t))}function Gk(e,t){if(e.length===0)return new Set;try{let r=v_("git",["check-ignore","--no-index","-z","--stdin"],{encoding:"utf8",input:`${e.join("\0")}\0`,stdio:["pipe","pipe","ignore"],...t?{cwd:t}:{}});return new Set(r.split("\0").filter(o=>o.length>0))}catch(r){if(r.status===1)return new Set;throw new y("user","git check-ignore failed; could not tell which files are gitignored.")}}function qk(e){return e.replace(Dk,"").replace(zk,"")}function Hk(e,t){let r=Nr(["log","--reverse","-z","--format=%H%x00%s%x00%b",e],{cwd:t}).split("\0"),o=[];for(let n=0;n+2<r.length;n+=3)o.push({sha:r[n]??"",subject:r[n+1]??"",body:(r[n+2]??"").trim()});return o}function Wk(e){let t=Nr(["status","--porcelain","-z"],{cwd:e}).split("\0"),r=[];for(let o=0;o<t.length;o+=1){let n=t[o];n&&(r.push(n.slice(3)),(n[0]==="R"||n[0]==="C")&&(o+=1))}return r.sort()}function Kk(e){let t=new TextEncoder().encode(JSON.stringify(e)).byteLength;if(t<=_p)return;let r=[...e.files].sort((o,n)=>n.patch.length-o.patch.length).slice(0,3).map(o=>`${o.path} (${yp(o.patch.length)})`);throw new y("user",`This diff is too large to review: ${yp(t)}, over the ${yp(_p)} limit. Largest files: ${r.join(", ")}.`,{hint:"Review a smaller range with --base <ref>."})}function yp(e){return`${(e/1e6).toFixed(1)} MB`}var Jk=/\s+/gu,Lr=1;function bp(e){return m_(e.map(t=>({source:t,...t.blocksMerge===!0?{blocking:!0}:{}})))}function jr(e){return bp(e).counts.blocking>0}function Mr(e,t){if(e!=="clear"&&e!=="issues_found")return`Arcanist review: ${F(e)}.`;let{tier:r}=bp(t);return`Arcanist review: ${p_(r)}.`}function __(e,t){return Oe(e).trim().split(`
80
- `).map(r=>r.length>0?`${t}${r}`:"")}function Yk(e,t){let r=F(e);return t===null?r:`${r}:${t}`}function Ut(e,t){let r=bp(e).ordered,o=[],n=(i,a)=>{t.withBody&&o.push(""),o.push(`${Yk(i.file,i.line)} - ${F(i.title)}${a}`),t.withBody&&(o.push(...__(i.body," ")),i.agentPrompt&&o.push(""," Agent prompt:",...__(i.agentPrompt," ")))};for(let{finding:i}of r)n(i.source,i.source.blocksMerge?` (${c_})`:"");return o}function y_(e){return F(e.replace(Jk," ")).trim()}function b_(e){return e.length===0?[]:["",`${l_} (${e.length})`,...e.flatMap(t=>[`- ${d_(y_(t.title))}`,` ${y_(t.conclusion)}`])]}var pa=1e4,wp=1800*1e3,w_={e2b:"e2b_cloud",modal:"modal_cloud"};function Xk(e){return Object.hasOwn(w_,e)}function Qk(e){if(e===void 0)return null;if(!Xk(e))throw new y("user","Sandbox runtime must be modal or e2b.");return w_[e]}async function $_(e,t={},r){let o=Qk(t.sandboxRuntime),n=t.wait?Ze(t.pollInterval,{defaultMs:pa,maxMs:null}):null,{config:i}=Y(r,t),a=await R(i,P("/api/pr-reviews"),{method:"POST",body:JSON.stringify({prUrl:e,...o!==null?{sandboxRuntimeBackend:o}:{}})});if(!t.wait||a.cached){D(r,t,a,c=>{if(!c.cached){console.log(`Started Arcanist review${c.requestId?` (${c.requestId})`:""}.`);return}let l=c.findings??[];console.log(Mr(c.verdict??"unknown",l));for(let d of Ut(l,{withBody:!1}))console.log(d)}),jr(a.findings??[])&&(process.exitCode=Lr);return}let s=a.requestId?.trim()??"";if(s.length===0)throw new y("server","Arcanist review start did not return a requestId.");let u=await En({pollIntervalMs:n??pa,timeoutMs:wp,timeoutMessage:"Timed out waiting for Arcanist review results.",fetchStatus:async()=>{let c=await R(i,P("/api/pr-reviews/requests/:requestId",{requestId:s}));if(c.status==="cancelled")throw new y("conflict",c.terminalReason?`Arcanist review was cancelled: ${c.terminalReason}`:"Arcanist review was cancelled.");if(c.status==="admission_rejected")throw new y("user",c.terminalReason?`Arcanist review was rejected at admission: ${c.terminalReason}`:"Arcanist review was rejected at admission.");return c.status!=="completed"?null:{...c,status:"completed",sessionId:c.sessionId??a.sessionId??null,verdict:c.verdict??"unknown"}}});D(r,t,u,c=>{console.log(Mr(c.verdict,c.findings));for(let l of Ut(c.findings,{withBody:!1}))console.log(l)}),jr(u.findings)&&(process.exitCode=Lr)}var k_=P("/api/local-reviews"),$p="Timed out waiting for Arcanist review results.",eE=6e4,x_=["SIGINT","SIGTERM"];async function E_(e,t={},r){let o=[["--base",t.base!==void 0],["--include",t.include!==void 0],["--request",t.request!==void 0]];if(e!==void 0){let n=o.find(([,i])=>i);if(n)throw new y("user",`${n[0]} cannot be used with a pull request URL.`);await $_(e,t,r);return}if(t.sandboxRuntime!==void 0)throw new y("user","--sandbox-runtime needs a pull request URL.");if(t.request!==void 0&&(t.base!==void 0||t.include!==void 0))throw new y("user","--request cannot be used with --base or --include.");await tE(t,r)}async function tE(e={},t){let r=Ze(e.pollInterval,{defaultMs:pa,maxMs:null}),o=Se(t,e),n=oE(t,e),i=e.request?.trim();if(e.request!==void 0&&!i)throw new y("user","--request needs a request id.");let a=e.wait===!1,s,u,c;if(i)({config:u}=Y(t,e)),s=i;else{let p=h_({...e.base!==void 0?{base:e.base}:{},...e.include!==void 0?{include:e.include}:{}});({config:u}=Y(t,e)),aE(n,p),c={heldBack:p.payload.heldBackPaths,binary:p.skippedBinaryPaths,uncommitted:p.uncommittedPaths};let v=await P_(u,k_,{method:"POST",body:JSON.stringify(p.payload)});if(s=v.requestId?.trim()??"",s.length===0)throw new y("server","Arcanist review start did not return a request id.");let _=F(s),x=a?`Check it with \`arcanist review --request ${_} --no-wait\`.`:"Waiting for the result.";if(process.stderr.write(`Started Arcanist review (${_}). ${x}
80
+ `).map(r=>r.length>0?`${t}${r}`:"")}function Yk(e,t){let r=F(e);return t===null?r:`${r}:${t}`}function Ut(e,t){let r=bp(e).ordered,o=[],n=(i,a)=>{t.withBody&&o.push(""),o.push(`${Yk(i.file,i.line)} - ${F(i.title)}${a}`),t.withBody&&(o.push(...__(i.body," ")),i.agentPrompt&&o.push(""," Agent prompt:",...__(i.agentPrompt," ")))};for(let{finding:i}of r)n(i.source,i.source.blocksMerge?` (${c_})`:"");return o}function y_(e){return F(e.replace(Jk," ")).trim()}function b_(e){return e.length===0?[]:["",`${l_} (${e.length})`,...e.flatMap(t=>[`- ${d_(y_(t.title))}`,` ${y_(t.conclusion)}`])]}var pa=1e4,wp=1800*1e3,w_={e2b:"e2b_cloud",modal:"modal_cloud"};function Xk(e){return Object.hasOwn(w_,e)}function Qk(e){if(e===void 0)return null;if(!Xk(e))throw new y("user","Sandbox runtime must be modal or e2b.");return w_[e]}async function $_(e,t,r){let o=Qk(t.sandboxRuntime),n=t.wait?Ze(t.pollInterval,{defaultMs:pa,maxMs:null}):null,{config:i}=Y(r,t),a=await R(i,P("/api/pr-reviews"),{method:"POST",body:JSON.stringify({prUrl:e,...o!==null?{sandboxRuntimeBackend:o}:{}})});if(!t.wait||a.cached){D(r,t,a,c=>{if(!c.cached){console.log(`Started Arcanist review${c.requestId?` (${c.requestId})`:""}.`);return}let l=c.findings??[];console.log(Mr(c.verdict??"unknown",l));for(let d of Ut(l,{withBody:!1}))console.log(d)}),jr(a.findings??[])&&(process.exitCode=Lr);return}let s=a.requestId?.trim()??"";if(s.length===0)throw new y("server","Arcanist review start did not return a requestId.");let u=await En({pollIntervalMs:n??pa,timeoutMs:wp,timeoutMessage:"Timed out waiting for Arcanist review results.",fetchStatus:async()=>{let c=await R(i,P("/api/pr-reviews/requests/:requestId",{requestId:s}));if(c.status==="cancelled")throw new y("conflict",c.terminalReason?`Arcanist review was cancelled: ${c.terminalReason}`:"Arcanist review was cancelled.");if(c.status==="admission_rejected")throw new y("user",c.terminalReason?`Arcanist review was rejected at admission: ${c.terminalReason}`:"Arcanist review was rejected at admission.");return c.status!=="completed"?null:{...c,status:"completed",sessionId:c.sessionId??a.sessionId??null,verdict:c.verdict??"unknown"}}});D(r,t,u,c=>{console.log(Mr(c.verdict,c.findings));for(let l of Ut(c.findings,{withBody:!1}))console.log(l)}),jr(u.findings)&&(process.exitCode=Lr)}var k_=P("/api/local-reviews"),$p="Timed out waiting for Arcanist review results.",eE=6e4,x_=["SIGINT","SIGTERM"];async function E_(e,t={},r){let o=[["--base",t.base!==void 0],["--include",t.include!==void 0],["--request",t.request!==void 0]];if(e!==void 0){let n=o.find(([,i])=>i);if(n)throw new y("user",`${n[0]} cannot be used with a pull request URL.`);await $_(e,t,r);return}if(t.sandboxRuntime!==void 0)throw new y("user","--sandbox-runtime needs a pull request URL.");if(t.request!==void 0&&(t.base!==void 0||t.include!==void 0))throw new y("user","--request cannot be used with --base or --include.");await tE(t,r)}async function tE(e,t){let r=Ze(e.pollInterval,{defaultMs:pa,maxMs:null}),o=Se(t,e),n=oE(t,e),i=e.request?.trim();if(e.request!==void 0&&!i)throw new y("user","--request needs a request id.");let a=e.wait===!1,s,u,c;if(i)({config:u}=Y(t,e)),s=i;else{let p=h_({...e.base!==void 0?{base:e.base}:{},...e.include!==void 0?{include:e.include}:{}});({config:u}=Y(t,e)),aE(n,p),c={heldBack:p.payload.heldBackPaths,binary:p.skippedBinaryPaths,uncommitted:p.uncommittedPaths};let v=await P_(u,k_,{method:"POST",body:JSON.stringify(p.payload)});if(s=v.requestId?.trim()??"",s.length===0)throw new y("server","Arcanist review start did not return a request id.");let _=F(s),x=a?`Check it with \`arcanist review --request ${_} --no-wait\`.`:"Waiting for the result.";if(process.stderr.write(`Started Arcanist review (${_}). ${x}
81
81
  `),a){D(t,e,{status:"in_flight",requestId:s,sessionId:v.sessionId??null,baseSha:p.payload.baseSha,headSha:p.payload.headSha,leftOut:c},I_),process.exitCode=Aa;return}}let l=`arcanist review --request ${F(s)}`,d;if(a){let p=await T_(u,s),v=A_(p);if(v===null){let{baseSha:_,headSha:x}=p;D(t,e,{status:"in_flight",requestId:s,sessionId:p.sessionId,baseSha:_,headSha:x},I_),process.exitCode=Aa;return}d=v}else d=await nE({config:u,requestId:s,pollIntervalMs:r,resumeCommand:l,json:o,note:n});let m={...d,requestId:s,...c?{leftOut:c}:{}};D(t,e,m,sE),jr(m.findings??[])&&(process.exitCode=Lr)}function T_(e,t){return P_(e,P("/api/local-reviews/:requestId",{requestId:t}))}function A_(e){if(e.status==="failed")throw S_("server",e,"Arcanist review failed.");if(e.status==="admission_rejected")throw S_("user",e,"Arcanist review was not started.");return e.status==="completed"?e:null}async function nE(e){let t=()=>{let n=new y("user","Interrupted. The review is still running.",{exitCode:vt,hint:`Get its result with \`${e.resumeCommand}\`.`});process.stderr.write(e.json?`${qr(n)}
82
82
  `:`
83
83
  ${n.message}
@@ -85,11 +85,11 @@ Hint: ${n.hint??""}
85
85
  `),process.exit(vt)};for(let n of x_)process.once(n,t);let r=Date.now(),o=r;try{return await En({pollIntervalMs:e.pollIntervalMs,timeoutMs:wp,timeoutMessage:$p,fetchStatus:async()=>{let n=A_(await T_(e.config,e.requestId)),i=Date.now();if(n===null&&i-o>=eE){o=i;let a=Math.floor((i-r)/6e4);e.note(`Still reviewing (${a}m). Get the result later with \`${e.resumeCommand}\`.`)}return n}})}catch(n){throw n instanceof y&&n.message===$p?new y("server",$p,{hint:`The review may still finish. Get its result with \`${e.resumeCommand}\`.`}):n}finally{for(let n of x_)process.off(n,t)}}function S_(e,t,r){let o=Oe(t.failure?.message??"").trim(),n=t.failure?.code;return new y(e,o.length>0?o:r,{...n?{data:{serverCode:n}}:{}})}async function P_(e,t,r){try{return await(r===void 0?R(e,t):R(e,t,r))}catch(o){if(!(o instanceof ae))throw o;let n=o.data?.serverCode,i=n==="active_request_exists"?iE(o.body):null,a=rE(o,n,t,i),s=i?{...o.data,requestId:i}:o.data;throw new y(o.code,Oe(o.message),{exitCode:o.exitCode,...a?{hint:a}:{},...o.requestId?{requestId:o.requestId}:{},...s?{data:s}:{}})}}function rE(e,t,r,o){switch(t){case"active_request_exists":return o?`Get its result with \`arcanist review --request ${o}\`.`:"Wait for your running review to finish, then retry.";case"paid_plan_required":case"review_limit_exceeded":return e.data?.billingUrl?`A workspace admin can change the plan at ${Oe(e.data.billingUrl)}.`:"Ask a workspace admin about your Arcanist plan.";case"repository_not_connected":return"Check accessible repositories with `arcanist repos list`.";case"payload_too_large":return"Review a smaller range with --base <ref>.";case"base_commit_not_found":return"Run `git fetch origin`, or pass --base <ref> with a ref that is on GitHub.";default:return e.status===404?r===k_?void 0:"Check the id passed to --request.":e.hint}}function iE(e){try{let t=JSON.parse(e);if(typeof t.requestId!="string")return null;let r=F(t.requestId).trim();return r.length>0?r:null}catch{return null}}function oE(e,t){return e.optsWithGlobals().quiet===!0||t.quiet===!0?()=>{}:o=>{process.stderr.write(`${o}
86
86
  `)}}function aE(e,t){let r=[["Committed but not uploaded for review (pass --include <path> to upload)",t.payload.heldBackPaths],["Skipped binary files",t.skippedBinaryPaths],["Uncommitted changes are not reviewed",t.uncommittedPaths]];for(let[o,n]of r)n.length>0&&e(`${o}: ${n.map(F).join(", ")}`)}function sE(e){let t=e.findings??[];console.log(Mr(e.verdict??"unknown",t)),e.environmentDegradedReason&&console.log(a_);let r=Oe(e.summary??"").trim();r.length>0&&console.log(r);for(let o of Ut(t,{withBody:!0}))console.log(o);for(let o of b_(e.alsoChecked??[]))console.log(o)}function I_(e){let t=F(e.requestId);console.log("Arcanist review is still running."),console.log(`Check again with \`arcanist review --request ${t} --no-wait\`, or wait for it with \`arcanist review --request ${t}\`.`)}import{spawn as _E}from"node:child_process";import{createHash as yE,randomBytes as bE}from"node:crypto";import{createHash as O_,randomBytes as cE}from"node:crypto";import{chmodSync as lE,mkdirSync as dE,readFileSync as pE,rmSync as mE}from"node:fs";import{homedir as fE}from"node:os";import{join as N_}from"node:path";import gE from"proper-lockfile";var R_="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function C_(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`arcanist-cli-login-approval-code:${e}`))),r="";for(let o=0;o<8;o+=1)r+=R_[t[o]%R_.length];return uE(r)}function uE(e){return`${e.slice(0,4)}-${e.slice(4)}`}var vE=f.object({verifier:f.string().regex(/^[a-f0-9]{64}$/),expiresAt:f.number()}),hE=10*6e4;async function xp(e){let t=await C_(e.challenge);return{url:`${e.apiUrl}/cli/login?challenge=${e.challenge}&scope=${e.scope}&code=${t}`,approvalCode:t}}async function D_(e,t,r){let o=N_(fE(),".arcanist");dE(o,{recursive:!0,mode:448});let n=N_(o,`login-${O_("sha256").update(e).digest("hex")}.json`),i;try{i=await gE.lock(n,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(a){throw a.code==="ELOCKED"?new y("conflict","Another sign-in command is running or recovering. Retry this command shortly."):a}try{let a=Cn({json:!0});if(a?.apiUrl===e&&a.token!==r)return{status:"approved",config:a};let s=null;try{s=vE.parse(JSON.parse(pE(n,"utf8")))}catch(l){if(l.code!=="ENOENT")throw l}if(s){lE(n,384);try{let l=await R({apiUrl:e},P("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:s.verifier})});if(l.token){let d={apiUrl:e,token:l.token};return Wr(d,t),mE(n,{force:!0}),{status:"approved",config:d}}s.expiresAt<=Date.now()&&(s=null)}catch(l){if(!(l instanceof ae)||l.status!==410)throw l;s=null}}s||(s={verifier:cE(32).toString("hex"),expiresAt:Date.now()+hE},ht(n,s));let u=O_("sha256").update(s.verifier).digest("hex"),c=await xp({apiUrl:e,challenge:u,scope:"write"});return{status:"approval_required",authorizationUrl:c.url,approvalCode:c.approvalCode,expiresAt:s.expiresAt}}finally{await i()}}var wE=2e3,$E=10*6e4;async function z_(e,t){let r=ee(t,e),o=Kr(r.apiUrl),n=za(r,!1),i=null,a=null;if(e.tokenStdin?i=await jt():n?.token&&(i=n.token),!i){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new y("user","No token provided.",{hint:"Pipe a token with --token-stdin or set ARCANIST_TOKEN. In a terminal, `arcanist auth login` opens the browser."});({token:i,scope:a}=await SE(o,xE(e.scope)))}if(!i.startsWith("arc_"))throw new y("user","Invalid token format. Token must start with 'arc_'.");try{await R({apiUrl:o,token:i},P("/api/auth/whoami"));let s={apiUrl:o,token:i};return Wr(s),e.emitResult===!1||(r.json?Ve({ok:!0,apiUrl:o,...a?{scope:a}:{}}):r.quiet||(console.log(`Logged in. API: ${o}`),console.log("Token verified."))),s}catch(s){throw s instanceof ae&&(s.status===401||s.status===403)?new y("auth","Token could not be verified. It may be invalid or expired."):s}}function xE(e){let t=e??"read";if(t!=="read"&&t!=="write")throw new y("user",`Invalid scope "${t}". Use read or write.`);return t}async function SE(e,t){let r=bE(32).toString("hex"),o=yE("sha256").update(r).digest("hex"),{url:n,approvalCode:i}=await xp({apiUrl:e,challenge:o,scope:t});console.error(`Your code: ${i}`),console.error("Opening your browser to sign in. Check that the page shows this code, or enter it there. Then approve."),console.error(`If it does not open, open this URL:
87
87
  ${n}`),IE(n);let a=Date.now()+$E,s=()=>{process.exit(vt)};process.once("SIGINT",s);try{for(;Date.now()<a;){let u;try{u=await R({apiUrl:e},P("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:r})})}catch(c){throw c instanceof ae&&(c.status===409||c.status===410)?new y("user",c.message):c}if(u.token)return{token:u.token,scope:u.scope??t};await new Promise(c=>setTimeout(c,wE))}}finally{process.off("SIGINT",s)}throw new y("user","Login timed out. Run arcanist auth login again.")}function IE(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]],o=_E(t,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}var Fr=[{label:"Understanding your code",stages:["repo_scan_started","stack_detected","dependencies_resolved"]},{label:"Configuring the environment",stages:["setup_authored","runtime_profile_authored","boot_attempt_started","boot_verified","environment_saved","build_started"]},{label:"Verifying it works",stages:["smoke_started","smoke_passed","smoke_failed"]}],L_=Fr.length-1,kE="Finishing up";function U_(e){return e?Fr.findIndex(t=>t.stages.includes(e)):-1}function EE(e){if(e.status==="ready")return Fr.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?L_:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=U_(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=U_(o)}return Math.max(t,r)}function j_(e){let t=EE(e);if(t>=Fr.length)return null;let r=[...e.history??[],e.stage];return t===L_&&(r.includes("smoke_passed")||r.includes("completed"))?kE:Fr[t].label}import{createHash as TE,randomUUID as AE}from"node:crypto";import{mkdirSync as PE,readFileSync as RE,rmSync as Sp}from"node:fs";import{homedir as CE}from"node:os";import{join as M_}from"node:path";import OE from"proper-lockfile";var NE=f.union([f.object({requestId:f.string().min(1),idempotencyKey:f.string().min(1).optional()}),f.object({requestId:f.undefined().optional(),idempotencyKey:f.string().min(1)})]);async function F_(e,t,r){let o=M_(CE(),".arcanist");PE(o,{recursive:!0,mode:448});let n=TE("sha256").update(JSON.stringify({apiUrl:e.apiUrl,...t})).digest("hex"),i=M_(o,`onboarding-review-${n}.json`),a;try{a=await OE.lock(i,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(s){throw s.code==="ELOCKED"?new y("conflict","Another review command is running or recovering. Retry this command shortly."):s}try{r&&Sp(i,{force:!0});let s=null;try{s=NE.parse(JSON.parse(RE(i,"utf8")))}catch(u){if(u.code!=="ENOENT")throw u}if(s||(s={requestId:void 0,idempotencyKey:AE()},ht(i,s)),s.requestId===void 0){let u=await R(e,P("/api/pr-reviews"),{method:"POST",headers:{"Idempotency-Key":s.idempotencyKey},body:JSON.stringify({prUrl:t.prUrl})});if(!u.requestId)throw new y("server","The review did not return a request ID.");s={...s,requestId:u.requestId},ht(i,s)}try{let u=await R(e,P("/api/pr-reviews/requests/:requestId",{requestId:s.requestId}));return(u.status==="cancelled"||u.status==="admission_rejected")&&Sp(i,{force:!0}),u}catch(u){throw u instanceof ae&&u.status===404&&Sp(i,{force:!0}),u}}finally{await a()}}function Ip(e){if(e===void 0||e==="every-pull-request"||e==="on-request")return e;throw new y("user","--automatic-review must be every-pull-request or on-request.")}async function ma(e,t,r){let o=ee(r,t),n=Ip(t.automaticReview),i=mt(e),a=`${i.owner}/${i.repo}`;if(t.restartReview&&!t.pr)throw new y("user","--restart-review requires --pr.");let s=t.pr===void 0?null:jh(t.pr);if(t.pr!==void 0&&(!s||`${s.owner}/${s.repo}`.toLowerCase()!==a.toLowerCase()))throw new y("user","--pr must be a GitHub pull request URL in the repository being onboarded.");let u=S=>`arcanist onboard ${a}${s?` --pr ${s.prUrl}`:""}${S?` --automatic-review ${S}`:""}${o.apiUrl?` --api-url ${pt(o.apiUrl)}`:""} --json`,c=u(n),l=Cn(o),d=l?.token,m=l?.apiUrl??Kr(o.apiUrl),p=null;if(l)try{p=await R(l,P("/api/auth/whoami")),p.tokenScope!=="write"&&(l=null)}catch(S){if(!(S instanceof ae)||S.status!==401)throw S;l=null}if(!l){if(o.token||process.env.ARCANIST_TOKEN)throw new y("auth","The explicit token was rejected or lacks write access. Replace or unset it before onboarding.");let S=Da(),O=await D_(m,S?.apiUrl===m?S.token:void 0,d);if(O.status==="approval_required"){D(r,t,{...O,message:`One quick approval, then your agent can take it from here. Open this link, check that it shows code ${O.approvalCode} or enter it there, and approve. Then return to your agent.`,command:c},z=>{console.log(z.message),console.log(z.authorizationUrl),console.log(`Code: ${z.approvalCode}`),console.log(`Then run: ${z.command}`)});return}l=O.config,p=await R(l,P("/api/auth/whoami"))}if(!p?.businessId||p.tokenScope!=="write")throw new y("auth","Onboarding needs write access to a workspace. Run arcanist onboard again to request it.");let v=await R(l,P("/api/settings/business/review-default"));if(v.automaticReviewChosen===!1&&n){if(p.businessRole!=="admin")throw new y("auth","Only a workspace admin can choose when Arcanist reviews.");await R(l,P("/api/settings/business/review-default"),{method:"PUT",body:JSON.stringify({autoReviewOnOpenEnabled:n==="every-pull-request",reviewOnPushEnabled:!1})})}else if(v.automaticReviewChosen===!1&&p.businessRole==="admin"){D(r,t,{status:"review_choice_required",message:"Ask the user: should Arcanist review every new pull request, or only when asked?",commands:{"every-pull-request":u("every-pull-request"),"on-request":u("on-request")}},S=>{console.log(S.message),console.log(`Every new pull request: ${S.commands["every-pull-request"]}`),console.log(`Only when asked: ${S.commands["on-request"]}`)});return}else v.automaticReviewChosen===!0&&n&&!o.json&&!o.quiet&&process.stderr.write(`This workspace already chose. Change it in Settings.
88
- `);c=u();let _=(S,O,z=c)=>{D(r,t,{status:"github_approval_required",authorizationUrl:S,command:z,resumeCommand:c,message:O},G=>{console.log(G.message),console.log(G.authorizationUrl),console.log(`Then run: ${G.command}`)})},x;try{x=await ft(l,a)}catch(S){if(!(S instanceof ae)||S.data?.serverCode!=="github_not_connected")throw S;let O=new URL("/auth/github/connect",l.apiUrl);O.searchParams.set("returnTo","/cli/onboarding"),_(O.toString(),"Connect your GitHub account, then resume onboarding.");return}let E=`Approve Arcanist access to ${a} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(x.nextAction==="prepare"){let[S]=await vp(l,{repositories:[i]});if(!S)throw new y("server","Environment setup returned no repository result.");if(S.status==="failed"&&S.reason==="installation_github_permissions_required"){if(p.businessRole!=="admin")throw new y("auth",zr);E=zr,x={...x,nextAction:"authorize_github"}}else if(S.status==="forbidden"){if(S.reason==="repository_limit"||p.businessRole!=="admin")throw new y("auth",`Cannot prepare ${a}: ${S.reason??"repository access required"}.`);x={...x,nextAction:"authorize_github"}}else{if(S.status==="failed"&&S.reason==="installation_github_check_failed")throw new y("server",sa);if(S.status==="failed")throw new y("server",`Could not start setup for ${a}.`);x=await ft(l,a)}}if(x.nextAction==="authorize_github"){let S=await R(l,P("/api/onboarding/github-installation"));_(S.authorizationUrl,E,x.status==="failed"?`arcanist environments retry ${a}${o.apiUrl?` --api-url ${pt(l.apiUrl)}`:""} --json`:c);return}if(x.command&&o.apiUrl&&(x={...x,command:`${x.command} --api-url ${pt(l.apiUrl)}`}),x.nextAction==="review"&&s){let S=await F_(l,{businessId:p.businessId,userId:p.userId,prUrl:s.prUrl},t.restartReview===!0);if(S.status==="cancelled"||S.status==="admission_rejected")throw new y("user",S.terminalReason??`First review ${S.status}.`);let O=S.status==="completed"&&(S.verdict==="clear"||S.verdict==="issues_found")&&!!S.headSha,z=O?`You're set. Arcanist has completed its first review of ${a}. ${S.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:S.status==="completed"?"The first review needs attention before setup can be verified. Your agent can inspect the result and help with the next step.":`Arcanist is reviewing ${a}. Your agent can follow its progress; nothing is needed from you right now.`;D(r,t,{message:z,status:O?"complete":S.status==="completed"?"review_needs_attention":"review_pending",repository:x,reviewVerified:O,review:S,pullRequestUrl:s.prUrl,command:S.status==="completed"?null:c},G=>{console.log(G.message),console.log(s.prUrl),G.command&&console.log(`Continue with: ${G.command}`)});return}let A={review:`${a} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${j_({...x,status:x.status==="not_started"?"pending":x.status})??"Configuring the environment"} for ${a}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${a}. Your agent will share the question and continue with your answer.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${a}. Your progress is saved.`,retry:`Setup for ${a} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${a}.`,authorize_github:`GitHub access is needed for ${a}.`}[x.nextAction];D(r,t,{message:A,status:x.nextAction==="review"?"repository_ready":x.nextAction==="wait"?"setup_pending":"action_required",repository:x,reviewVerified:!1,command:x.nextAction==="wait"?c:x.command,resumeCommand:c},S=>{console.log(S.message),S.command&&console.log(`Continue with: ${S.command}`)})}async function Z_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await jt();if(!o)throw new y("user","The answer must not be empty.");let n=mt(e),{config:i}=Y(r,t);if((await ft(i,`${n.owner}/${n.repo}`)).question?.id!==t.question)throw new y("conflict","That question is no longer pending. Run arcanist onboard again.");let s=await R(i,P("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});D(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function B_(e={},t){let{config:r}=Y(t,e),o=await R(r,P("/api/repos"));D(t,e,{repos:o.repos,ssoOrgs:o.ssoOrgs},n=>{for(let i of n.repos)console.log(`${String(i.fullName??i.name??i.repo??"")} ${String(i.defaultBranch??"")}`);n.ssoOrgs.length>0&&console.log(`SSO withheld orgs: ${n.ssoOrgs.length}`)})}async function V_(e,t,r){let o=ee(r,t),n=he(o),[i,a]=await Promise.all([R(n,P("/api/pr-reviews/requests/:requestId",{requestId:e})),R(n,P("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);D(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(Oe(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of Ut(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=F(l);console.log(`Next: arcanist sessions view ${d}`)}})}var G_=["published","publish_failed","gate_rejected"],q_=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var H_=["bundle","ledger","disposition","lineage"];var DE=/^\d{1,3}$/,zE=/^fe[89ab]/,UE=/^f[cd]/,LE=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,jE=/^\[/,ME=/\]$/;var W_=300,Zr=500,Ep=3,FE=6e3;var K_=/^dl-[0-9a-f]{8}$/,ZE=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function kp(e){let t=e.split(".");if(t.length===4&&t.every(r=>DE.test(r)&&Number(r)<=255)){let[r,o]=t.map(Number);return r===0||r===10||r===127||r===169&&o===254||r===172&&o>=16&&o<=31||r===192&&o===168||r===100&&o>=64&&o<=127||r===198&&(o===18||o===19)}if(e.includes(":")){let r=e.toLowerCase();if(r==="::"||r==="::1"||zE.test(r)||UE.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(LE);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return kp(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return kp(o)}return!1}return!1}function BE(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(jE,"").replace(ME,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!ZE.has(r)&&!kp(r)}catch{return!1}}var sj=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(W_)}).strict(),f.object({kind:f.literal("fetch"),url:f.string().url().max(Zr).refine(BE,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(W_).optional(),offset:f.number().int().min(0).optional()}).strict()]),VE=f.object({url:f.string().max(Zr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(FE)}).strict(),uj=f.object({results:f.array(VE).max(Ep)}).strict();var J_=f.string().regex(/^q-[1-9][0-9]*$/).max(16);var Tp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],gj=f.object({lookupId:f.string().regex(K_),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(Zr),status:f.enum(Tp),resultUrls:f.array(f.string().max(Zr)).max(Ep),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:J_.optional()}).strict();function B(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var Ap="zeus_telemetry";var Y_=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],X_={state:{kind:"string_enum",values:["no_notification","turn_completed","command_running","tool_running","model_output_open","awaiting_model_output"]},lastNotificationMethod:"string",maxNotificationGapMs:"number",modelResponseCount:"number",streamRetryCount:"number",itemsInFlight:"number",oldestItemInFlight:{kind:"object",fields:{type:"string",tool:"string",msSinceStarted:"number"}},recentNotifications:"string_array"},GE={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},Pj={"zeus.publish_rejected":{reason:"string",checkCount:"number",findingCount:"number",verdict:"string",firstAttempt:"boolean",attemptOrdinal:"number",contractVersion:"string",schemaPath:"string",schemaIssue:"string",schemaValue:"string"},"zeus.publish_secret_value_redacted":{count:"number"},"zeus.publish_notes_unverified":{attemptOrdinal:"number",findingCount:"number",contractVersion:"string"},"zeus.publish_empty_review_unattested":{attemptOrdinal:"number",noteCount:"number",contractVersion:"string"},"zeus.publish_blocking_downgraded":{detail:{kind:"string_enum",values:["no_base_run","no_matched_pair"]},blockingCount:"number",attemptOrdinal:"number"},"zeus.scout.health":{health:{kind:"string_enum",values:q_},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:G_},candidateTotal:"number",expectedScoutCount:"number",observedScoutCount:"number",statuses:"string_array"},"zeus.scout.agreement":{candidateCount:"number",publishedCandidateCount:"number",examinedRejectedCount:"number",notExaminedCount:"number",notExaminedEnvironmentCount:"number",notExaminedExternalCount:"number",notExaminedNoneCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",verifierReportedPublishedCount:"number"},"zeus.candidate_ledger":{conserved:"boolean",candidateCount:"number",droppedCount:"number",publishedCandidateCount:"number",rejectedCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",violationStage:{kind:"string_enum",values:["none",...H_]}},"zeus.stage.peer_triage_completed":{reason:"string",threads:"number",stageStatus:{kind:"string_enum",values:["ok","failed","skipped"]}},"zeus.verifier.terminal":{verifierStatus:{kind:"string_enum",values:Y_},effort:"string",stall:{kind:"object",fields:X_},codexTcpSockets:{kind:"object",fields:GE}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:Y_},stall:{kind:"object",fields:X_},investigationId:"string",effort:"string",theme:"string"},"zeus.scout.completion":{role:"string",status:"string",durationMs:"number",inputTokens:"number",outputTokens:"number",candidateCount:"number"},"zeus.scout.bundle_omitted":{omittedCandidateCount:"number",droppedExcerptCount:"number"},"zeus.scout.patch_truncated":{role:"string",sampleIndex:"number",investigationId:"string",ownedFileCount:"number",truncatedFileCount:"number",omittedFileCount:"number",withheldChars:"number"},"zeus.scout.patch_unavailable":{role:"string",sampleIndex:"number",reason:"string",ownedFileCount:"number",patchedFileCount:"number"},"zeus.doc_lookup":{kind:{kind:"string_enum",values:["search","fetch"]},status:{kind:"string_enum",values:Tp},thread:{kind:"string_enum",values:["primary","scout"]},investigationId:"string",durationMs:"number",resultCount:"number"},"zeus.review.prompt_budget_truncated":{excessChars:"number",reviewContextPacketTruncated:"boolean",droppedSectionNames:"string_array",truncatedSectionNames:"string_array",beforeChars:"number",afterChars:"number"},"zeus.review.prompt_budget_externalized":{beforeChars:"number",afterChars:"number",budgetChars:"number",externalizedSectionNames:"string_array"},"zeus.scout.investigations_completed":{dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},aggregate_outcome:"string",candidate_total:"number",rate_limited_scout_count:"number",duration_ms:"number",prompt_id:"string",session_id:"string"}};var Q_=["prompt.started","context.selected","files.inspected","tools.run","files.edited","commands.run","publish_gate.result","verification.result","git.commit","git.push","pr.open","onboarding.discovery_delivered","onboarding.discovery_tool_blocked"],ey=["observed"],ty=["sandbox_bridge","control_plane"],ny=["started","completed","failed","skipped","blocked"];var qE=["session.create","sandbox.spawn","bridge.connect","bridge.event","prompt.enqueue","prompt.context","prompt.dispatch","agent.session.create","tool.call","tool.update","tool.result","text.delta","prompt.complete","git.push","pr.open","timeline","error","user_question","idle"],Pp=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Ee(e){return typeof e=="number"&&Number.isFinite(e)}function Q(e){return e===void 0||typeof e=="string"}function ry(e){return e===void 0||B(e)}function fa(e){return e==null||typeof e=="string"}function Ue(e,t){return typeof e=="string"&&t.includes(e)}function HE(e){return typeof e=="string"||B(e)&&typeof e.label=="string"&&Q(e.description)}function ce(e){return B(e)?Q(e.bridgeEventType)&&!iy(e)&&ry(e.bridgeData):!1}function iy(e){return B(e)?typeof e.bridgeEventType=="string"&&Pp.has(e.bridgeEventType):!1}function ga(e,t){if(!B(t))return!1;switch(e){case"session.create":return ce(t)&&Ue(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||Ue(t.sessionKind,["repo"]));case"sandbox.spawn":return ce(t)&&Ue(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Ee(t.attempt))&&Q(t.reason);case"bridge.connect":return ce(t)&&Ue(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!iy(t)&&ry(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ce(t)&&fa(t.actorUserId)&&Q(t.agent)&&fa(t.model);case"prompt.context":return ce(t);case"prompt.dispatch":return ce(t)&&fa(t.startupAttemptId);case"agent.session.create":return ce(t)&&Ue(t.status,["started","complete","failed"])&&Q(t.agentSessionId)&&Q(t.agent);case"tool.call":return ce(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&Q(t.summary)&&(t.args===void 0||B(t.args));case"tool.result":return ce(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&Q(t.error);case"text.delta":return ce(t)&&Ue(t.channel,["output","reasoning"])&&typeof t.text=="string"&&Q(t.partId);case"prompt.complete":return ce(t)&&typeof t.success=="boolean"&&Q(t.error)&&Q(t.errorCode);case"git.push":return ce(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&Q(t.error);case"pr.open":return ce(t)&&typeof t.success=="boolean"&&Q(t.prUrl)&&(t.prNumber===void 0||Ee(t.prNumber))&&Q(t.error);case"timeline":return ce(t)&&Ue(t.eventType,Q_)&&Ue(t.source,ey)&&Ue(t.observer,ty)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||Ue(t.status,ny))&&(t.metadata===void 0||B(t.metadata));case"error":return ce(t)&&typeof t.message=="string"&&Q(t.code);case"user_question":return ce(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(HE));case"idle":return ce(t)&&(t.sessionEditCount===void 0||Ee(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Ee(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function WE(e){return typeof e=="string"&&qE.includes(e)}function oy(e){if(!B(e))throw new Error("Invalid ArcanistEvent");if(!WE(e.phase))throw new Error("Invalid phase");if(typeof e.timestampMs!="number"||!Number.isFinite(e.timestampMs))throw new Error("Invalid timestampMs");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("Invalid sessionId");if(e.promptId!==void 0&&typeof e.promptId!="string")throw new Error("Invalid promptId");if(e.sandboxId!==void 0&&typeof e.sandboxId!="string")throw new Error("Invalid sandboxId");if(!B(e.payload))throw new Error("Invalid payload");if(e.formatVersion!==void 0&&e.formatVersion!==2)throw new Error("Invalid formatVersion");if(e.formatVersion===2&&["type","timestamp","content","messageId","bridgeData","bridgeEventType"].some(r=>r in e))throw new Error("Legacy fields in version 2 envelope");if(!(e.formatVersion===2||!("bridgeData"in e.payload||"bridgeEventType"in e.payload)?KE(e.phase,e.payload):ga(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function KE(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Ee(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Ee(t[o]))return!1;if(!Q(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return JE(t);case"tool.update":return typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.status=="string";case"bridge.connect":return typeof t.status=="string"&&(t.kind===void 0||t.kind==="heartbeat")&&Q(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return fa(t.startupAttemptId);case"prompt_accepted":return Q(t.startupAttemptId);case"agent_prompt_sent":return Q(t.startupAttemptId)&&Q(t.agentSessionId)&&Q(t.agentRuntimeBackend);case"prompt_activity":return Ue(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&Q(t.detail)&&(t.childWorkActive===void 0||t.childWorkActive===!0);case"agent_progress":return typeof t.step=="string"&&typeof t.label=="string"&&(t.terminal===void 0||typeof t.terminal=="boolean");default:return!1}case"text.delta":return ga(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return ga(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&Q(t.btSpanId);default:return ga(e,t)}}function JE(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return Q(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return B(e.runtime);case"sandbox_undersized":return Ee(e.oomKills);case"sandbox_enospc":return typeof e.source=="string";case"sandbox_resource_sample":return["memoryUsedBytes","memoryLimitBytes","memoryUsedPercent","swapUsedBytes","cpuUsedPercent","pidsCurrent","pidsLimit"].every(t=>e[t]===void 0||Ee(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Ee(e[t]));case"estimated_input_composition":return B(e.components);case"retry_status":return Ee(e.attempt)&&typeof e.message=="string";case"tool_truncated":return typeof e.callId=="string"&&typeof e.tool=="string";case"compaction_start":return e.contextTokens===void 0||Ee(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Ee(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Ee(e[t]));case"prompt_result":return!0;case"raw_agent_runtime":return!0;case"todo_update":return Array.isArray(e.todos)&&e.todos.every(t=>B(t)&&typeof t.id=="string"&&typeof t.content=="string"&&typeof t.status=="string");case"zeus_telemetry":return typeof e.eventName=="string";default:return!1}}function ay(e){switch(e.phase){case"bridge.event":return e.payload.kind==="raw_agent_runtime"&&e.payload.runtimeEventType==="codex_event"?"codex_event":e.payload.kind;case"bridge.connect":return e.payload.kind==="heartbeat"?"heartbeat":e.phase;case"prompt.dispatch":return e.payload.kind??"prompt_accepted";case"text.delta":return e.payload.finalAnswer?"final_answer":e.payload.channel==="reasoning"?"reasoning":"token";case"tool.call":return"tool_call";case"tool.update":return"tool_update";case"tool.result":return"tool_result";case"prompt.complete":return"execution_complete";case"user_question":return"question";case"error":return"error";case"idle":return"session_idle";case"agent.session.create":return"agent_session_created";case"timeline":return"agent_timeline";case"git.push":return e.payload.success?"push_complete":"push_error";default:return e.phase}}function Rp(e,t){if(!B(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return oy(e);if(typeof e.phase=="string"&&B(e.payload)){let m=e,p=e.payload;if(!B(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let v=B(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:x,...E}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...v,...E}};let k=typeof p.bridgeEventType=="string"?p.bridgeEventType:ay(m),A=m.phase==="text.delta"&&k==="text"?"token":m.phase==="prompt.dispatch"&&k==="prompt_processing"?"prompt_accepted":k,S=Rp({...v,type:A,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??v.messageId,promptId:m.promptId??v.promptId,ackId:e.ackId},m.sessionId??"");return S.phase==="bridge.connect"&&S.payload.kind==="heartbeat"&&delete E.status,E.startupAttemptId===null&&delete E.startupAttemptId,{...S,payload:{...S.payload,...E}}}if(typeof e.type!="string"||Pp.has(e.type))throw new Error("Removed or invalid bridge event");if(t===void 0)throw new Error("Missing sessionId for legacy event");let{type:r,timestamp:o,messageId:n,promptId:i,sandboxId:a,ackId:s,...u}=e,c={sessionId:t,timestampMs:typeof o=="number"?o:Number.isFinite(Date.parse(String(o)))?Date.parse(String(o)):Date.now(),...typeof i=="string"?{promptId:i}:typeof n=="string"?{promptId:n}:{},...typeof a=="string"?{sandboxId:a}:{},...typeof s=="string"?{ackId:s}:{}},l,d;switch(r){case"heartbeat":l="bridge.connect",d={...u,kind:"heartbeat"};break;case"prompt_activity":{let{phase:m,...p}=u;l="prompt.dispatch",d={...p,kind:r,activityPhase:m};break}case"prompt_accepted":case"agent_progress":case"agent_prompt_sent":l="prompt.dispatch",d={...u,kind:r};break;case"token":case"reasoning":case"final_answer":{let{content:m,...p}=u;l="text.delta",d={...p,channel:r==="reasoning"?"reasoning":"output",text:m,...r==="final_answer"?{finalAnswer:!0,partId:u.partId??`${n}:final_answer`}:{}};break}case"tool_call":{let{args:m,...p}=u;l="tool.call",d=B(m)?{...p,args:m}:p;break}case"tool_update":l="tool.update",d=u;break;case"tool_result":l="tool.result",d={...u,ok:u.error===void 0};break;case"execution_complete":l="prompt.complete",d=u;break;case"error":case"session_error":{let{error:m,errorDetails:p,...v}=u;l="error",d={...v,message:m,...p!==void 0?{details:p}:{}};break}case"question":l="user_question",d=u;break;case"session_idle":l="idle",d=u;break;case"agent_session_created":l="agent.session.create",d={...u,status:"complete"};break;case"agent_timeline":l="timeline",d=u;break;case"codex_event":l="bridge.event",d={kind:"raw_agent_runtime",runtimeEventType:r,...u};break;case"zeus_telemetry":{let{kind:m,...p}=u;l="bridge.event",d={...p,kind:r,...m!==void 0?{lookupKind:m}:{}};break}case"patch":case"prompt_telemetry_start":case"post_execution":case"runtime_info":case"sandbox_undersized":case"sandbox_enospc":case"sandbox_resource_sample":case"usage":case"estimated_input_composition":case"retry_status":case"tool_truncated":case"compaction_start":case"compaction_complete":case"context_fill_warning":case"prompt_result":case"raw_agent_runtime":case"todo_update":l="bridge.event",d={...u,kind:r};break;default:l="bridge.event",d={...u,kind:"raw_agent_runtime",runtimeEventType:r}}return{...c,phase:l,payload:d}}var sy=["repo_scan_started","stack_detected","dependencies_resolved","setup_authored","runtime_profile_authored","boot_attempt_started","boot_verified","environment_saved","build_started","smoke_started","smoke_passed","smoke_failed","escalated_to_engineer","engineer_unblocked","escalated_to_customer","question_for_customer","customer_unblocked","completed","failed"],Vj=sy.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),YE=["started","succeeded","failed"],XE=200;function QE(e){return typeof e=="string"&&sy.includes(e)}function eT(e){return typeof e=="string"&&YE.includes(e)}function uy(e){if(!B(e))return null;let t=e;if(!QE(t.stage))return null;let r=eT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,XE);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var tT="Arcanist blocked this malformed search command before execution.",nT=/\/bin\/bash:\s+-c:\s+line\s+\d+:\s+unexpected EOF while looking for matching [`'\"][`'\"]?/i,rT=24,iT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function va(e){return"phase"in e&&typeof e.phase=="string"}var cy=new WeakMap;function ha(e){let t=cy.get(e);return t||(t=Rp(e),cy.set(e,t)),t}function _a(e){return ha(e).payload}function oT(e){let t=_a(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function gy(e){return _a(e).kind}function vy(e){return ha(e).promptId}function de(e,t){let r=vy(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function aT(e,t,r){switch(t){case"tool_call":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{},...B(r.args)&&r.input===void 0?{input:r.args}:{}});case"tool_update":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{}});default:return de(e,r)}}function Br(e){return va(e)?vy(e):B(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function An(e){if(!va(e))return e.type;let t=_a(e),r=gy(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(ha(e).phase){case"text.delta":return t.channel==="reasoning"?"reasoning":"text";case"tool.call":return"tool_call";case"tool.update":case"tool.result":return"tool_update";case"prompt.enqueue":return"prompt_enqueued";case"prompt.dispatch":return"prompt_processing";case"prompt.complete":return t.success===!1?"prompt_failed":"prompt_completed";case"user_question":return"question";case"error":return"session_error";case"bridge.event":return r??e.phase;case"timeline":return r??"agent_timeline";case"idle":return r??"session_idle";default:return r??e.phase}}function sT(e){if(va(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=B(e.data)?e.data.timestamp:void 0;if(typeof t=="string"&&t.length>0||typeof t=="number"){let o=new Date(t);if(Number.isFinite(o.getTime()))return o.toISOString()}let r=e.timestamp;if(typeof r=="string"&&r.length>0||typeof r=="number"){let o=new Date(r);if(Number.isFinite(o.getTime()))return o.toISOString()}}function uT(e){let t=sT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function Op(e){if(!va(e))return B(e.data)?e.data:void 0;let t=_a(e),r=gy(e),o=de(e,oT(e));switch(ha(e).phase){case"text.delta":return de(e,{...o,...typeof t.partId=="string"&&t.partId.length>0?{id:t.partId}:{},text:t.text});case"tool.call":return de(e,{...o,id:t.callId,tool:t.tool,input:B(t.args)?t.args:{},summary:typeof t.summary=="string"?t.summary:""});case"tool.update":return de(e,{...o,id:t.callId,status:t.status});case"tool.result":return de(e,{...o,id:t.callId,status:typeof o.status=="string"?o.status:t.ok?"completed":"error"});case"prompt.enqueue":return de(e,{...o,source:t.source,...t.actorUserId!==void 0?{actorUserId:t.actorUserId}:{},...typeof t.agent=="string"?{agent:t.agent}:{},...t.model!==void 0?{model:t.model}:{}});case"prompt.dispatch":return de(e,{...o,...t.startupAttemptId!==void 0?{startupAttemptId:t.startupAttemptId}:{}});case"prompt.complete":return de(e,{...o,success:t.success,...typeof t.error=="string"?{error:t.error}:{},...typeof t.errorCode=="string"?{code:t.errorCode}:{},...t.errorDetails!==void 0?{errorDetails:t.errorDetails}:{}});case"user_question":return de(e,{...o,id:t.questionId,question:t.question,...Array.isArray(t.options)?{options:t.options}:{}});case"error":return de(e,{...o,error:t.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.command=="string"?{command:t.command}:{},...t.details!==void 0?{errorDetails:t.details}:{}});case"bridge.event":return aT(e,r,o);case"timeline":return de(e,{...o,...typeof t.eventType=="string"?{eventType:t.eventType}:{},...typeof t.source=="string"?{source:t.source}:{},...typeof t.observer=="string"?{observer:t.observer}:{},...typeof t.summary=="string"?{summary:t.summary}:{},...typeof t.status=="string"?{status:t.status}:{},...B(t.metadata)?{metadata:t.metadata}:{}});case"idle":return de(e,{...o,...typeof t.sessionEditCount=="number"?{sessionEditCount:t.sessionEditCount}:{},...typeof t.sessionPromptCount=="number"?{sessionPromptCount:t.sessionPromptCount}:{}});default:return de(e,o)}}function hy(e){let t=Op(e);return{raw:e,type:An(e),data:t,promptId:Br(e)}}function ly(e){return e.map(t=>hy(t))}function cT(e,t){return t?t.length<rT?!0:!e.endsWith(t):!1}function lT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function dT(e,t){return`${e}:${t}`}function dy(e,t){return t===0?e:`${e}#${t}`}function Lt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function pT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function mT(e){switch(e.type){case"agent_progress":case"retry_status":case"zeus_telemetry":case"agent_timeline":return!0;default:return!1}}function fT(e,t,r,o){if(o===e.length-1)return!0;let n=Math.max(o+1,t.interstitialScanEndByStreamId.get(r)??o+1);for(let i=n;i<e.length;i++)if(!mT(e[i]))return!1;return t.interstitialScanEndByStreamId.set(r,e.length),!0}function V(e){return typeof e?.promptId=="string"?e.promptId:void 0}function gT(e,t,r,o,n,i,a){let s=dT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=cT(u,n);if(c!==void 0){let p=e[c];if(p.type===r&&l&&fT(e,t,s,c))return p.text+=n,t.concatByStreamId.set(s,u+n),!p.promptId&&i&&(p.promptId=i),p.type==="reasoning"&&a!==void 0&&(p.startedAtMs===void 0&&(p.startedAtMs=a),p.endedAtMs=a),!0;if(c===e.length-1||!l)return!1}if(u&&!l)return!1;let d=t.segmentOrdinalByStreamId.get(s),m=d===void 0?0:d+1;return t.segmentOrdinalByStreamId.set(s,m),t.streamableIndexById.set(s,e.length),t.concatByStreamId.set(s,u+n),t.interstitialScanEndByStreamId.set(s,e.length+1),r==="text"?e.push({type:"text",id:dy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:dy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{},...a!==void 0?{startedAtMs:a,endedAtMs:a}:{}}),!0}function vT(e,t){return{...e,...t,tool:t.tool??e.tool,summary:t.summary??e.summary,...t.promptId===void 0&&e.promptId!==void 0?{promptId:e.promptId}:{},...t.input===void 0&&e.input!==void 0?{input:e.input}:{},...t.toolStatus===void 0&&e.toolStatus!==void 0?{toolStatus:e.toolStatus}:{},...t.truncated===void 0&&e.truncated!==void 0?{truncated:e.truncated}:{},...t.inputEstimatedTokens===void 0&&e.inputEstimatedTokens!==void 0?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...t.outputEstimatedTokens===void 0&&e.outputEstimatedTokens!==void 0?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...t.outputChars===void 0&&e.outputChars!==void 0?{outputChars:e.outputChars}:{},...t.failure===void 0&&e.failure!==void 0?{failure:e.failure}:{},...t.duplicateCount===void 0&&e.duplicateCount!==void 0?{duplicateCount:e.duplicateCount}:{}}}function Cp(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function hT(e,t){let r=Cp(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...B(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function _T(){return{merged:[],streams:lT(),toolCallIndexById:new Map,agentProgressIndexByKey:new Map,questionIndexById:new Map,narrationIndex:null,malformedSearchBlockedPromptIds:new Set,malformedSearchBlockedWithoutPrompt:!1}}function yT(e){return typeof e=="string"&&e.includes(tT)}function bT(e){return nT.test(e)}function wT(e){return e.malformedSearchBlockedPromptIds.size===0&&!e.malformedSearchBlockedWithoutPrompt?e.merged:e.merged.filter(t=>t.type!=="text"?!0:!((t.promptId?e.malformedSearchBlockedPromptIds.has(t.promptId):e.malformedSearchBlockedWithoutPrompt)&&bT(t.text)))}function Ce(e,t){t&&e.merged.push(t)}function $T(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function xT(e,t){return{type:"compaction_complete",id:`cc-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokensBefore=="number"?{contextTokensBefore:e.contextTokensBefore}:{},...typeof e?.contextTokensAfter=="number"?{contextTokensAfter:e.contextTokensAfter}:{}}}function ST(e,t){return{type:"context_fill_warning",id:`cfw-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},fillPercent:typeof e?.fillPercent=="number"?e.fillPercent:Number(e?.fillPercent??0),...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{},...typeof e?.contextWindow=="number"?{contextWindow:e.contextWindow}:{}}}function IT(e,t){return{type:"tool_truncated",id:typeof e?.callId=="string"?e.callId:String(t),tool:typeof e?.tool=="string"?e.tool:"",...e?.reason==="truncation_marker"||e?.reason==="size_threshold"?{reason:e.reason}:{},...V(e)?{promptId:V(e)}:{}}}function kT(e,t){return{type:"retry_status",id:`rs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},attempt:typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),message:typeof e?.message=="string"?e.message:"Retrying...",...typeof e?.nextRetryAt=="string"?{nextRetryAt:e.nextRetryAt}:{},...typeof e?.provider=="string"?{provider:e.provider}:{},...typeof e?.errorCode=="string"?{errorCode:e.errorCode}:{},...typeof e?.scope=="string"?{scope:e.scope}:{},...typeof e?.maxAttempts=="number"?{maxAttempts:e.maxAttempts}:{},...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.retryAfterMs=="number"?{retryAfterMs:e.retryAfterMs}:{},...typeof e?.fallbackModel=="string"?{fallbackModel:e.fallbackModel}:{}}}function ET(e){return e==="spawn_provider_error"?{message:"Sandbox failed to start; retrying on a fresh sandbox",scope:"sandbox_spawn"}:e==="spawn_deadline_no_object"||e==="spawn_deadline_no_bridge"||e==="spawn_timeout"?{message:"Sandbox did not start in time; retrying on a fresh sandbox",scope:"sandbox_spawn"}:{message:"Sandbox dropped mid-task; retrying on a fresh sandbox",scope:"sandbox_disconnect"}}function TT(e,t){let r=typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),o=typeof e?.cap=="number"?e.cap:void 0,n=typeof e?.retryPromptId=="string"?e.retryPromptId:V(e),i=typeof e?.reason=="string"?e.reason:void 0,{message:a,scope:s}=ET(i);return{type:"retry_status",id:`pr-retry-${n??t}`,...n?{promptId:n}:{},attempt:r,message:a,scope:s,...o!==void 0?{maxAttempts:o}:{},...i?{reason:i}:{}}}function AT(e,t){let r=typeof e?.eventName=="string"?e.eventName:Ap;return{type:Ap,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function PT(e,t){return{type:"agent_timeline",id:`atl-${t}-${typeof e?.eventType=="string"?e.eventType:"unknown"}`,eventType:typeof e?.eventType=="string"?e.eventType:"unknown",source:typeof e?.source=="string"?e.source:"observed",observer:typeof e?.observer=="string"?e.observer:"unknown",summary:typeof e?.summary=="string"?e.summary:"Observed agent timeline event.",...typeof e?.status=="string"?{status:e.status}:{},...B(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function RT(e,t){let r=V(e);return{type:"agent_progress",id:Lt(e,"ap",t),step:typeof e?.step=="string"?e.step:"unknown",label:typeof e?.label=="string"?e.label:"Working",terminal:e?.terminal===!0,...r?{promptId:r}:{}}}function CT(e,t){let r=RT(e,t.merged.length),o=`${r.promptId??""}\0${r.step}`,n=t.agentProgressIndexByKey.get(o);if(n!==void 0){let i=t.merged[n];t.merged[n]=i.type==="agent_progress"?{...r,id:i.id}:r;return}t.agentProgressIndexByKey.set(o,t.merged.length),t.merged.push(r)}function OT(e,t){return{type:"session_error",id:Lt(e,"err",t),error:typeof e?.error=="string"?e.error:"Unknown error",...V(e)?{promptId:V(e)}:{},...typeof e?.code=="string"?{code:e.code}:{},...typeof e?.command=="string"?{command:e.command}:{}}}function NT(e,t){if(e?.code!=="malformed_search_command"&&!yT(e?.error))return;let r=V(e);r?t.malformedSearchBlockedPromptIds.add(r):t.malformedSearchBlockedWithoutPrompt=!0}function DT(e,t){return{type:"session_resumed_cold",id:Lt(e,"rescold",t),...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.lostSnapshotImageId=="string"?{lostSnapshotImageId:e.lostSnapshotImageId}:e?.lostSnapshotImageId===null?{lostSnapshotImageId:null}:{},...V(e)?{promptId:V(e)}:{}}}function zT(e,t){let r=typeof e?.partType=="string"?e.partType:void 0,o=typeof e?.eventType=="string"?e.eventType:void 0;return r==="text"||o&&iT.has(o)?null:{type:"raw_agent_runtime",id:Lt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function UT(e,t){let r=Array.isArray(e?.files)?e.files.filter(o=>typeof o=="string"):[];return r.length===0?null:{type:"patch",id:`patch-${t}`,files:r,...V(e)?{promptId:V(e)}:{}}}function py(e,t,r,o){gT(r.merged,r.streams,e,Lt(t,e,r.merged.length),pT(t),V(t),o)}function LT(e,t){let r=Lt(e,"tool",t.merged.length),o=t.toolCallIndexById.get(r);if(o!==void 0){let n=t.merged[o];if(n.type==="tool_call"){let i=Cp(e?.toolStatus),a=B(e?.input)?e.input:void 0,s={type:"tool_call",id:r,...typeof e?.tool=="string"?{tool:e.tool}:typeof e?.toolName=="string"?{tool:e.toolName}:{},...typeof e?.summary=="string"&&e.summary.length>0?{summary:e.summary}:{},...V(e)?{promptId:V(e)}:{},...a&&Object.keys(a).length>0?{input:a}:{},...i?{toolStatus:i}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...B(e?.failure)?{failure:e.failure}:{}};t.merged[o]=vT(n,s)}}else{let n=Cp(e?.toolStatus),i={type:"tool_call",id:r,tool:typeof e?.tool=="string"?e.tool:typeof e?.toolName=="string"?e.toolName:"unknown",summary:typeof e?.summary=="string"?e.summary:"",...V(e)?{promptId:V(e)}:{},...B(e?.input)?{input:e.input}:{},...n?{toolStatus:n}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...B(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function jT(e,t){let r=typeof e?.id=="string"?e.id:"",o=t.toolCallIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n.type==="tool_call"&&(t.merged[o]=hT(n,e))}function MT(e,t){let r={type:"question",id:Lt(e,"question",t.merged.length),question:typeof e?.question=="string"?e.question:"",answer:e?.answer==null?null:String(e.answer),...V(e)?{promptId:V(e)}:{},...Array.isArray(e?.options)?{options:e.options}:{}};t.questionIndexById.set(r.id,t.merged.length),t.merged.push(r)}function FT(e,t){let r=typeof e?.id=="string"?e.id:void 0;if(!r)return;let o=t.questionIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n?.type==="question"&&(t.merged[o]={...n,answer:e?.answer==null?null:String(e.answer)})}function ZT(e,t){let r=Array.isArray(e?.todos)?e.todos:[];if(r.length!==0)for(let o=t.merged.length-1;o>=0;o--){let n=t.merged[o];if(n.type==="tool_call"&&n.tool.toLowerCase()==="todowrite"){t.merged[o]={...n,input:{...n.input,todos:r}};break}}}function BT(e,t){let r=uy(e);if(!r)return;let o=V(e);t.merged.push({type:"onboarding_status",id:`onboarding_status:${t.merged.length}`,stage:r.stage,status:r.status,...r.detail?{detail:r.detail}:{},...o?{promptId:o}:{}})}function VT(e,t){let r=typeof e?.text=="string"?e.text.trim():"";if(!r)return;let o=V(e),n={type:"narration",id:"narration",text:r,...o?{promptId:o}:{}};t.narrationIndex===null?(t.narrationIndex=t.merged.length,t.merged.push(n)):t.merged[t.narrationIndex]=n}function _y(e){let t=_T();for(let r of e){let o=hy(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Ce(t,$T(i,t.merged.length));break;case"sandbox_compaction_complete":Ce(t,xT(i,t.merged.length));break;case"sandbox_context_fill_warning":Ce(t,ST(i,t.merged.length));break;case"sandbox_tool_truncated":Ce(t,IT(i,t.merged.length));break;case"retry_status":Ce(t,kT(i,t.merged.length));break;case"prompt_retrying":Ce(t,TT(i,t.merged.length));break;case"zeus_telemetry":Ce(t,AT(i,t.merged.length));break;case"agent_timeline":Ce(t,PT(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":CT(i,t);break;case"session_error":NT(i,t),Ce(t,OT(i,t.merged.length));break;case"session_resumed_cold":Ce(t,DT(i,t.merged.length));break;case"raw_agent_runtime":Ce(t,zT(i,t.merged.length));break;case"reasoning":py("reasoning",i,t,uT(o.raw));break;case"text":py("text",i,t);break;case"patch":Ce(t,UT(i,t.merged.length));break;case"todo_update":ZT(i,t);break;case"answer":FT(i,t);break;case"tool_call":LT(i,t);break;case"tool_update":jT(i,t);break;case"question":MT(i,t);break;case"narration":VT(i,t);break;case"onboarding_status":BT(i,t);break}}return wT(t)}function yy(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Br(i),s=typeof a=="string"&&r.has(a)?a:null;An(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function GT(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="prompt_completed"&&r.type!=="prompt_failed")continue;let o=r.data?.history;return!Array.isArray(o)||o.length===0?null:o}return null}function my(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function fy(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function by(e){let t=ly(e),r=GT(t),o=t.filter(E=>E.type==="prompt_activity"),n=t.filter(E=>E.type==="agent_progress");if(!r)return{events:e,diagnostics:{embeddedHistoryPresent:!1,durablePromptActivityCount:o.length,embeddedPromptActivityCount:0,mergedDurablePromptActivityCount:0,duplicateDurablePromptActivityCount:0,durableAgentProgressCount:n.length,embeddedAgentProgressCount:0,mergedDurableAgentProgressCount:0,duplicateDurableAgentProgressCount:0}};let i=ly(r),a=i.filter(E=>E.type==="prompt_activity"),s=i.filter(E=>E.type==="agent_progress"),u=new Set(a.map(my)),c=new Set(s.map(fy)),l=a.length,d=s.length,m=0,p=0,v=o.filter(E=>{let k=my(E);return u.has(k)?(m+=1,!1):(u.add(k),!0)}),_=n.filter(E=>{let k=fy(E);return c.has(k)?(p+=1,!1):(c.add(k),!0)}),x=[...v,..._].map(E=>E.raw);return{events:x.length>0?[...x,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:v.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var wy=1e3;async function $y(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>wy)throw new y("user",`${e} exceeded ${wy} pages without reaching the end.`);let u=await o(i);n.push(...u.items),a=u.nextCursor,i=a??void 0}while(t&&a);return{items:n,nextCursor:t?null:a}}import{createParser as sA}from"eventsource-parser";function ya(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function xy(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function ba(e){switch(e){case"no_diff":return{state:"no_changes",tone:"info",title:"Completed without code changes.",detail:null};case"no_staged_files":return{state:"no_changes",tone:"info",title:"Completed without publishable code changes.",detail:null};case"prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed before changes could be prepared.",detail:null};case"post_prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed after changes were prepared.",detail:null};default:return{state:"no_change_abnormal",tone:"error",title:"Completed without code changes, but finalization did not report a clean no-op reason.",detail:null}}}var qT="## Previously declined findings on this repository (calibration)",HT="## Findings already reported by other reviewers",WT="## Graphite stack neighbours",KT="## Whole-stack review",Sy=[qT,HT,WT,KT,"## Independent review suggestions"];var ky=/\r?\n/,JT=/\n{3,}/g,YT=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,XT=[/^IMPORTANT: The content above is /i,/^Previous Slack message\b/i,/^Current Slack message author:/i,/^Current Slack channel:/i,/^Thread context(?:\s*\([^)]*\))?\s*[.:]/i,/^Repository:\s+\S+$/i,/^Issue (?:title|body|description|metadata)\s*:/i,/^Triggering comment\s*:/i,/^Review body\s*:/i,/^Recent comments\s*:/i,/^<\/?(?:user_content|instruction_content)\b/i],QT=[/<\/?(?:user_content|instruction_content)\b/i,/^IMPORTANT: The content above is /im,/^Previous Slack message\b/im,/^Current Slack message author:/im,/^Current Slack channel:/im,/^Repository:\s+\S+$/im],eA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function tA(e){let t=e.split(ky),r=[],o=[];if(t.forEach((a,s)=>{let u=Sy.findIndex(c=>a.trim()===c);u!==-1&&(r.push(u),o.push(s))}),o.length===0||!r.every((a,s)=>s===0||a>(r[s-1]??-1)))return e.trim();let i=o[0]??0;return t.slice(0,i).join(`
89
- `).trim()}function Iy(e){return QT.some(t=>t.test(e))}function nA(e){return e.replace(YT,"").split(ky).filter(o=>!XT.some(n=>n.test(o.trim()))).join(`
90
- `).replace(JT,`
88
+ `);c=u();let _=(S,O,z=c)=>{D(r,t,{status:"github_approval_required",authorizationUrl:S,command:z,resumeCommand:c,message:O},G=>{console.log(G.message),console.log(G.authorizationUrl),console.log(`Then run: ${G.command}`)})},x;try{x=await ft(l,a)}catch(S){if(!(S instanceof ae)||S.data?.serverCode!=="github_not_connected")throw S;let O=new URL("/auth/github/connect",l.apiUrl);O.searchParams.set("returnTo","/cli/onboarding"),_(O.toString(),"Connect your GitHub account, then resume onboarding.");return}let E=`Approve Arcanist access to ${a} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(x.nextAction==="prepare"){let[S]=await vp(l,{repositories:[i]});if(!S)throw new y("server","Environment setup returned no repository result.");if(S.status==="failed"&&S.reason==="installation_github_permissions_required"){if(p.businessRole!=="admin")throw new y("auth",zr);E=zr,x={...x,nextAction:"authorize_github"}}else if(S.status==="forbidden"){if(S.reason==="repository_limit"||p.businessRole!=="admin")throw new y("auth",`Cannot prepare ${a}: ${S.reason??"repository access required"}.`);x={...x,nextAction:"authorize_github"}}else{if(S.status==="failed"&&S.reason==="installation_github_check_failed")throw new y("server",sa);if(S.status==="failed")throw new y("server",`Could not start setup for ${a}.`);x=await ft(l,a)}}if(x.nextAction==="authorize_github"){let S=await R(l,P("/api/onboarding/github-installation"));_(S.authorizationUrl,E,x.status==="failed"?`arcanist environments retry ${a}${o.apiUrl?` --api-url ${pt(l.apiUrl)}`:""} --json`:c);return}if(x.command&&o.apiUrl&&(x={...x,command:`${x.command} --api-url ${pt(l.apiUrl)}`}),x.nextAction==="review"&&s){let S=await F_(l,{businessId:p.businessId,userId:p.userId,prUrl:s.prUrl},t.restartReview===!0);if(S.status==="cancelled"||S.status==="admission_rejected")throw new y("user",S.terminalReason??`First review ${S.status}.`);let O=S.status==="completed"&&(S.verdict==="clear"||S.verdict==="issues_found")&&!!S.headSha,z=O?`You're set. Arcanist has completed its first review of ${a}. ${S.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:S.status==="completed"?"The first review needs attention before setup can be verified. Your agent can inspect the result and help with the next step.":`Arcanist is reviewing ${a}. Your agent can follow its progress; nothing is needed from you right now.`;D(r,t,{message:z,status:O?"complete":S.status==="completed"?"review_needs_attention":"review_pending",repository:x,reviewVerified:O,review:S,pullRequestUrl:s.prUrl,command:S.status==="completed"?null:c},G=>{console.log(G.message),console.log(s.prUrl),G.command&&console.log(`Continue with: ${G.command}`)});return}let A={review:`${a} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${j_({...x,status:x.status==="not_started"?"pending":x.status})??"Configuring the environment"} for ${a}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${a}. Your agent will share the question and continue with your answer.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${a}. Your progress is saved.`,retry:`Setup for ${a} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${a}.`,authorize_github:`GitHub access is needed for ${a}.`}[x.nextAction];D(r,t,{message:A,status:x.nextAction==="review"?"repository_ready":x.nextAction==="wait"?"setup_pending":"action_required",repository:x,reviewVerified:!1,command:x.nextAction==="wait"?c:x.command,resumeCommand:c},S=>{console.log(S.message),S.command&&console.log(`Continue with: ${S.command}`)})}async function Z_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await jt();if(!o)throw new y("user","The answer must not be empty.");let n=mt(e),{config:i}=Y(r,t);if((await ft(i,`${n.owner}/${n.repo}`)).question?.id!==t.question)throw new y("conflict","That question is no longer pending. Run arcanist onboard again.");let s=await R(i,P("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});D(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function B_(e={},t){let{config:r}=Y(t,e),o=await R(r,P("/api/repos"));D(t,e,{repos:o.repos,ssoOrgs:o.ssoOrgs},n=>{for(let i of n.repos)console.log(`${String(i.fullName??i.name??i.repo??"")} ${String(i.defaultBranch??"")}`);n.ssoOrgs.length>0&&console.log(`SSO withheld orgs: ${n.ssoOrgs.length}`)})}async function V_(e,t,r){let o=ee(r,t),n=he(o),[i,a]=await Promise.all([R(n,P("/api/pr-reviews/requests/:requestId",{requestId:e})),R(n,P("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);D(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(Oe(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of Ut(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=F(l);console.log(`Next: arcanist sessions view ${d}`)}})}var G_=["published","publish_failed","gate_rejected"],q_=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var H_=["bundle","ledger","disposition","lineage"];var DE=/^\d{1,3}$/,zE=/^fe[89ab]/,UE=/^f[cd]/,LE=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,jE=/^\[/,ME=/\]$/;var W_=300,Zr=500,Ep=3,FE=6e3;var K_=/^dl-[0-9a-f]{8}$/,ZE=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function kp(e){let t=e.split(".");if(t.length===4&&t.every(r=>DE.test(r)&&Number(r)<=255)){let[r,o]=t.map(Number);return r===0||r===10||r===127||r===169&&o===254||r===172&&o>=16&&o<=31||r===192&&o===168||r===100&&o>=64&&o<=127||r===198&&(o===18||o===19)}if(e.includes(":")){let r=e.toLowerCase();if(r==="::"||r==="::1"||zE.test(r)||UE.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(LE);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return kp(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return kp(o)}return!1}return!1}function BE(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(jE,"").replace(ME,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!ZE.has(r)&&!kp(r)}catch{return!1}}var VE=f.object({kind:f.literal("fetch"),url:f.string().url().max(Zr).refine(BE,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(W_).optional(),offset:f.number().int().min(0).optional()}).strict(),uj=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(W_)}).strict(),VE]),GE=f.object({url:f.string().max(Zr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(FE)}).strict(),cj=f.object({results:f.array(GE).max(Ep)}).strict();var J_=f.string().regex(/^q-[1-9][0-9]*$/).max(16);var Tp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],vj=f.object({lookupId:f.string().regex(K_),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(Zr),status:f.enum(Tp),resultUrls:f.array(f.string().max(Zr)).max(Ep),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:J_.optional()}).strict();function B(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var Ap="zeus_telemetry";var Y_=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],X_={state:{kind:"string_enum",values:["no_notification","turn_completed","command_running","tool_running","model_output_open","awaiting_model_output"]},lastNotificationMethod:"string",maxNotificationGapMs:"number",modelResponseCount:"number",streamRetryCount:"number",itemsInFlight:"number",oldestItemInFlight:{kind:"object",fields:{type:"string",tool:"string",msSinceStarted:"number"}},recentNotifications:"string_array"},qE={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},Rj={"zeus.publish_rejected":{reason:"string",checkCount:"number",findingCount:"number",verdict:"string",firstAttempt:"boolean",attemptOrdinal:"number",contractVersion:"string",schemaPath:"string",schemaIssue:"string",schemaValue:"string"},"zeus.publish_secret_value_redacted":{count:"number"},"zeus.publish_notes_unverified":{attemptOrdinal:"number",findingCount:"number",contractVersion:"string"},"zeus.publish_empty_review_unattested":{attemptOrdinal:"number",noteCount:"number",contractVersion:"string"},"zeus.publish_blocking_downgraded":{detail:{kind:"string_enum",values:["no_base_run","no_matched_pair"]},blockingCount:"number",attemptOrdinal:"number"},"zeus.scout.health":{health:{kind:"string_enum",values:q_},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:G_},candidateTotal:"number",expectedScoutCount:"number",observedScoutCount:"number",statuses:"string_array"},"zeus.scout.agreement":{candidateCount:"number",publishedCandidateCount:"number",examinedRejectedCount:"number",notExaminedCount:"number",notExaminedEnvironmentCount:"number",notExaminedExternalCount:"number",notExaminedNoneCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",verifierReportedPublishedCount:"number"},"zeus.candidate_ledger":{conserved:"boolean",candidateCount:"number",droppedCount:"number",publishedCandidateCount:"number",rejectedCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",violationStage:{kind:"string_enum",values:["none",...H_]}},"zeus.stage.peer_triage_completed":{reason:"string",threads:"number",stageStatus:{kind:"string_enum",values:["ok","failed","skipped"]}},"zeus.verifier.terminal":{verifierStatus:{kind:"string_enum",values:Y_},effort:"string",stall:{kind:"object",fields:X_},codexTcpSockets:{kind:"object",fields:qE}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:Y_},stall:{kind:"object",fields:X_},investigationId:"string",effort:"string",theme:"string"},"zeus.scout.completion":{role:"string",status:"string",durationMs:"number",inputTokens:"number",outputTokens:"number",candidateCount:"number"},"zeus.scout.bundle_omitted":{omittedCandidateCount:"number",droppedExcerptCount:"number"},"zeus.scout.patch_truncated":{role:"string",sampleIndex:"number",investigationId:"string",ownedFileCount:"number",truncatedFileCount:"number",omittedFileCount:"number",withheldChars:"number"},"zeus.scout.patch_unavailable":{role:"string",sampleIndex:"number",reason:"string",ownedFileCount:"number",patchedFileCount:"number"},"zeus.doc_lookup":{kind:{kind:"string_enum",values:["search","fetch"]},status:{kind:"string_enum",values:Tp},thread:{kind:"string_enum",values:["primary","scout"]},investigationId:"string",durationMs:"number",resultCount:"number"},"zeus.review.prompt_budget_truncated":{excessChars:"number",reviewContextPacketTruncated:"boolean",droppedSectionNames:"string_array",truncatedSectionNames:"string_array",beforeChars:"number",afterChars:"number"},"zeus.review.prompt_budget_externalized":{beforeChars:"number",afterChars:"number",budgetChars:"number",externalizedSectionNames:"string_array"},"zeus.scout.investigations_completed":{dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},aggregate_outcome:"string",candidate_total:"number",rate_limited_scout_count:"number",duration_ms:"number",prompt_id:"string",session_id:"string"}};var Q_=["prompt.started","context.selected","files.inspected","tools.run","files.edited","commands.run","publish_gate.result","verification.result","git.commit","git.push","pr.open","onboarding.discovery_delivered","onboarding.discovery_tool_blocked"],ey=["observed"],ty=["sandbox_bridge","control_plane"],ny=["started","completed","failed","skipped","blocked"];var HE=["session.create","sandbox.spawn","bridge.connect","bridge.event","prompt.enqueue","prompt.context","prompt.dispatch","agent.session.create","tool.call","tool.update","tool.result","text.delta","prompt.complete","git.push","pr.open","timeline","error","user_question","idle"],Pp=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Ee(e){return typeof e=="number"&&Number.isFinite(e)}function Q(e){return e===void 0||typeof e=="string"}function ry(e){return e===void 0||B(e)}function fa(e){return e==null||typeof e=="string"}function Ue(e,t){return typeof e=="string"&&t.includes(e)}function WE(e){return typeof e=="string"||B(e)&&typeof e.label=="string"&&Q(e.description)}function ce(e){return B(e)?Q(e.bridgeEventType)&&!iy(e)&&ry(e.bridgeData):!1}function iy(e){return B(e)?typeof e.bridgeEventType=="string"&&Pp.has(e.bridgeEventType):!1}function ga(e,t){if(!B(t))return!1;switch(e){case"session.create":return ce(t)&&Ue(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||Ue(t.sessionKind,["repo"]));case"sandbox.spawn":return ce(t)&&Ue(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Ee(t.attempt))&&Q(t.reason);case"bridge.connect":return ce(t)&&Ue(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!iy(t)&&ry(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ce(t)&&fa(t.actorUserId)&&Q(t.agent)&&fa(t.model);case"prompt.context":return ce(t);case"prompt.dispatch":return ce(t)&&fa(t.startupAttemptId);case"agent.session.create":return ce(t)&&Ue(t.status,["started","complete","failed"])&&Q(t.agentSessionId)&&Q(t.agent);case"tool.call":return ce(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&Q(t.summary)&&(t.args===void 0||B(t.args));case"tool.result":return ce(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&Q(t.error);case"text.delta":return ce(t)&&Ue(t.channel,["output","reasoning"])&&typeof t.text=="string"&&Q(t.partId);case"prompt.complete":return ce(t)&&typeof t.success=="boolean"&&Q(t.error)&&Q(t.errorCode);case"git.push":return ce(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&Q(t.error);case"pr.open":return ce(t)&&typeof t.success=="boolean"&&Q(t.prUrl)&&(t.prNumber===void 0||Ee(t.prNumber))&&Q(t.error);case"timeline":return ce(t)&&Ue(t.eventType,Q_)&&Ue(t.source,ey)&&Ue(t.observer,ty)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||Ue(t.status,ny))&&(t.metadata===void 0||B(t.metadata));case"error":return ce(t)&&typeof t.message=="string"&&Q(t.code);case"user_question":return ce(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(WE));case"idle":return ce(t)&&(t.sessionEditCount===void 0||Ee(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Ee(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function KE(e){return typeof e=="string"&&HE.includes(e)}function oy(e){if(!B(e))throw new Error("Invalid ArcanistEvent");if(!KE(e.phase))throw new Error("Invalid phase");if(typeof e.timestampMs!="number"||!Number.isFinite(e.timestampMs))throw new Error("Invalid timestampMs");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("Invalid sessionId");if(e.promptId!==void 0&&typeof e.promptId!="string")throw new Error("Invalid promptId");if(e.sandboxId!==void 0&&typeof e.sandboxId!="string")throw new Error("Invalid sandboxId");if(!B(e.payload))throw new Error("Invalid payload");if(e.formatVersion!==void 0&&e.formatVersion!==2)throw new Error("Invalid formatVersion");if(e.formatVersion===2&&["type","timestamp","content","messageId","bridgeData","bridgeEventType"].some(r=>r in e))throw new Error("Legacy fields in version 2 envelope");if(!(e.formatVersion===2||!("bridgeData"in e.payload||"bridgeEventType"in e.payload)?JE(e.phase,e.payload):ga(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function JE(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Ee(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Ee(t[o]))return!1;if(!Q(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return YE(t);case"tool.update":return typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.status=="string";case"bridge.connect":return typeof t.status=="string"&&(t.kind===void 0||t.kind==="heartbeat")&&Q(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return fa(t.startupAttemptId);case"prompt_accepted":return Q(t.startupAttemptId);case"agent_prompt_sent":return Q(t.startupAttemptId)&&Q(t.agentSessionId)&&Q(t.agentRuntimeBackend);case"prompt_activity":return Ue(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&Q(t.detail)&&(t.childWorkActive===void 0||t.childWorkActive===!0);case"agent_progress":return typeof t.step=="string"&&typeof t.label=="string"&&(t.terminal===void 0||typeof t.terminal=="boolean");default:return!1}case"text.delta":return ga(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return ga(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&Q(t.btSpanId);default:return ga(e,t)}}function YE(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return Q(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return B(e.runtime);case"sandbox_undersized":return Ee(e.oomKills);case"sandbox_enospc":return typeof e.source=="string";case"sandbox_resource_sample":return["memoryUsedBytes","memoryLimitBytes","memoryUsedPercent","swapUsedBytes","cpuUsedPercent","pidsCurrent","pidsLimit"].every(t=>e[t]===void 0||Ee(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Ee(e[t]));case"estimated_input_composition":return B(e.components);case"retry_status":return Ee(e.attempt)&&typeof e.message=="string";case"tool_truncated":return typeof e.callId=="string"&&typeof e.tool=="string";case"compaction_start":return e.contextTokens===void 0||Ee(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Ee(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Ee(e[t]));case"prompt_result":return!0;case"raw_agent_runtime":return!0;case"todo_update":return Array.isArray(e.todos)&&e.todos.every(t=>B(t)&&typeof t.id=="string"&&typeof t.content=="string"&&typeof t.status=="string");case"zeus_telemetry":return typeof e.eventName=="string";default:return!1}}function ay(e){switch(e.phase){case"bridge.event":return e.payload.kind==="raw_agent_runtime"&&e.payload.runtimeEventType==="codex_event"?"codex_event":e.payload.kind;case"bridge.connect":return e.payload.kind==="heartbeat"?"heartbeat":e.phase;case"prompt.dispatch":return e.payload.kind??"prompt_accepted";case"text.delta":return e.payload.finalAnswer?"final_answer":e.payload.channel==="reasoning"?"reasoning":"token";case"tool.call":return"tool_call";case"tool.update":return"tool_update";case"tool.result":return"tool_result";case"prompt.complete":return"execution_complete";case"user_question":return"question";case"error":return"error";case"idle":return"session_idle";case"agent.session.create":return"agent_session_created";case"timeline":return"agent_timeline";case"git.push":return e.payload.success?"push_complete":"push_error";default:return e.phase}}function Rp(e,t){if(!B(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return oy(e);if(typeof e.phase=="string"&&B(e.payload)){let m=e,p=e.payload;if(!B(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let v=B(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:x,...E}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...v,...E}};let k=typeof p.bridgeEventType=="string"?p.bridgeEventType:ay(m),A=m.phase==="text.delta"&&k==="text"?"token":m.phase==="prompt.dispatch"&&k==="prompt_processing"?"prompt_accepted":k,S=Rp({...v,type:A,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??v.messageId,promptId:m.promptId??v.promptId,ackId:e.ackId},m.sessionId??"");return S.phase==="bridge.connect"&&S.payload.kind==="heartbeat"&&delete E.status,E.startupAttemptId===null&&delete E.startupAttemptId,{...S,payload:{...S.payload,...E}}}if(typeof e.type!="string"||Pp.has(e.type))throw new Error("Removed or invalid bridge event");if(t===void 0)throw new Error("Missing sessionId for legacy event");let{type:r,timestamp:o,messageId:n,promptId:i,sandboxId:a,ackId:s,...u}=e,c={sessionId:t,timestampMs:typeof o=="number"?o:Number.isFinite(Date.parse(String(o)))?Date.parse(String(o)):Date.now(),...typeof i=="string"?{promptId:i}:typeof n=="string"?{promptId:n}:{},...typeof a=="string"?{sandboxId:a}:{},...typeof s=="string"?{ackId:s}:{}},l,d;switch(r){case"heartbeat":l="bridge.connect",d={...u,kind:"heartbeat"};break;case"prompt_activity":{let{phase:m,...p}=u;l="prompt.dispatch",d={...p,kind:r,activityPhase:m};break}case"prompt_accepted":case"agent_progress":case"agent_prompt_sent":l="prompt.dispatch",d={...u,kind:r};break;case"token":case"reasoning":case"final_answer":{let{content:m,...p}=u;l="text.delta",d={...p,channel:r==="reasoning"?"reasoning":"output",text:m,...r==="final_answer"?{finalAnswer:!0,partId:u.partId??`${n}:final_answer`}:{}};break}case"tool_call":{let{args:m,...p}=u;l="tool.call",d=B(m)?{...p,args:m}:p;break}case"tool_update":l="tool.update",d=u;break;case"tool_result":l="tool.result",d={...u,ok:u.error===void 0};break;case"execution_complete":l="prompt.complete",d=u;break;case"error":case"session_error":{let{error:m,errorDetails:p,...v}=u;l="error",d={...v,message:m,...p!==void 0?{details:p}:{}};break}case"question":l="user_question",d=u;break;case"session_idle":l="idle",d=u;break;case"agent_session_created":l="agent.session.create",d={...u,status:"complete"};break;case"agent_timeline":l="timeline",d=u;break;case"codex_event":l="bridge.event",d={kind:"raw_agent_runtime",runtimeEventType:r,...u};break;case"zeus_telemetry":{let{kind:m,...p}=u;l="bridge.event",d={...p,kind:r,...m!==void 0?{lookupKind:m}:{}};break}case"patch":case"prompt_telemetry_start":case"post_execution":case"runtime_info":case"sandbox_undersized":case"sandbox_enospc":case"sandbox_resource_sample":case"usage":case"estimated_input_composition":case"retry_status":case"tool_truncated":case"compaction_start":case"compaction_complete":case"context_fill_warning":case"prompt_result":case"raw_agent_runtime":case"todo_update":l="bridge.event",d={...u,kind:r};break;default:l="bridge.event",d={...u,kind:"raw_agent_runtime",runtimeEventType:r}}return{...c,phase:l,payload:d}}var sy=["repo_scan_started","stack_detected","dependencies_resolved","setup_authored","runtime_profile_authored","boot_attempt_started","boot_verified","environment_saved","build_started","smoke_started","smoke_passed","smoke_failed","escalated_to_engineer","engineer_unblocked","escalated_to_customer","question_for_customer","customer_unblocked","completed","failed"],Gj=sy.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),XE=["started","succeeded","failed"],QE=200;function eT(e){return typeof e=="string"&&sy.includes(e)}function tT(e){return typeof e=="string"&&XE.includes(e)}function uy(e){if(!B(e))return null;let t=e;if(!eT(t.stage))return null;let r=tT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,QE);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var nT="Arcanist blocked this malformed search command before execution.",rT=/\/bin\/bash:\s+-c:\s+line\s+\d+:\s+unexpected EOF while looking for matching [`'\"][`'\"]?/i,iT=24,oT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function va(e){return"phase"in e&&typeof e.phase=="string"}var cy=new WeakMap;function ha(e){let t=cy.get(e);return t||(t=Rp(e),cy.set(e,t)),t}function _a(e){return ha(e).payload}function aT(e){let t=_a(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function gy(e){return _a(e).kind}function vy(e){return ha(e).promptId}function de(e,t){let r=vy(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function sT(e,t,r){switch(t){case"tool_call":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{},...B(r.args)&&r.input===void 0?{input:r.args}:{}});case"tool_update":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{}});default:return de(e,r)}}function Br(e){return va(e)?vy(e):B(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function An(e){if(!va(e))return e.type;let t=_a(e),r=gy(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(ha(e).phase){case"text.delta":return t.channel==="reasoning"?"reasoning":"text";case"tool.call":return"tool_call";case"tool.update":case"tool.result":return"tool_update";case"prompt.enqueue":return"prompt_enqueued";case"prompt.dispatch":return"prompt_processing";case"prompt.complete":return t.success===!1?"prompt_failed":"prompt_completed";case"user_question":return"question";case"error":return"session_error";case"bridge.event":return r??e.phase;case"timeline":return r??"agent_timeline";case"idle":return r??"session_idle";default:return r??e.phase}}function uT(e){if(va(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=B(e.data)?e.data.timestamp:void 0;if(typeof t=="string"&&t.length>0||typeof t=="number"){let o=new Date(t);if(Number.isFinite(o.getTime()))return o.toISOString()}let r=e.timestamp;if(typeof r=="string"&&r.length>0||typeof r=="number"){let o=new Date(r);if(Number.isFinite(o.getTime()))return o.toISOString()}}function cT(e){let t=uT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function Op(e){if(!va(e))return B(e.data)?e.data:void 0;let t=_a(e),r=gy(e),o=de(e,aT(e));switch(ha(e).phase){case"text.delta":return de(e,{...o,...typeof t.partId=="string"&&t.partId.length>0?{id:t.partId}:{},text:t.text});case"tool.call":return de(e,{...o,id:t.callId,tool:t.tool,input:B(t.args)?t.args:{},summary:typeof t.summary=="string"?t.summary:""});case"tool.update":return de(e,{...o,id:t.callId,status:t.status});case"tool.result":return de(e,{...o,id:t.callId,status:typeof o.status=="string"?o.status:t.ok?"completed":"error"});case"prompt.enqueue":return de(e,{...o,source:t.source,...t.actorUserId!==void 0?{actorUserId:t.actorUserId}:{},...typeof t.agent=="string"?{agent:t.agent}:{},...t.model!==void 0?{model:t.model}:{}});case"prompt.dispatch":return de(e,{...o,...t.startupAttemptId!==void 0?{startupAttemptId:t.startupAttemptId}:{}});case"prompt.complete":return de(e,{...o,success:t.success,...typeof t.error=="string"?{error:t.error}:{},...typeof t.errorCode=="string"?{code:t.errorCode}:{},...t.errorDetails!==void 0?{errorDetails:t.errorDetails}:{}});case"user_question":return de(e,{...o,id:t.questionId,question:t.question,...Array.isArray(t.options)?{options:t.options}:{}});case"error":return de(e,{...o,error:t.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.command=="string"?{command:t.command}:{},...t.details!==void 0?{errorDetails:t.details}:{}});case"bridge.event":return sT(e,r,o);case"timeline":return de(e,{...o,...typeof t.eventType=="string"?{eventType:t.eventType}:{},...typeof t.source=="string"?{source:t.source}:{},...typeof t.observer=="string"?{observer:t.observer}:{},...typeof t.summary=="string"?{summary:t.summary}:{},...typeof t.status=="string"?{status:t.status}:{},...B(t.metadata)?{metadata:t.metadata}:{}});case"idle":return de(e,{...o,...typeof t.sessionEditCount=="number"?{sessionEditCount:t.sessionEditCount}:{},...typeof t.sessionPromptCount=="number"?{sessionPromptCount:t.sessionPromptCount}:{}});default:return de(e,o)}}function hy(e){let t=Op(e);return{raw:e,type:An(e),data:t,promptId:Br(e)}}function ly(e){return e.map(t=>hy(t))}function lT(e,t){return t?t.length<iT?!0:!e.endsWith(t):!1}function dT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function pT(e,t){return`${e}:${t}`}function dy(e,t){return t===0?e:`${e}#${t}`}function Lt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function mT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function fT(e){switch(e.type){case"agent_progress":case"retry_status":case"zeus_telemetry":case"agent_timeline":return!0;default:return!1}}function gT(e,t,r,o){if(o===e.length-1)return!0;let n=Math.max(o+1,t.interstitialScanEndByStreamId.get(r)??o+1);for(let i=n;i<e.length;i++)if(!fT(e[i]))return!1;return t.interstitialScanEndByStreamId.set(r,e.length),!0}function V(e){return typeof e?.promptId=="string"?e.promptId:void 0}function vT(e,t,r,o,n,i,a){let s=pT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=lT(u,n);if(c!==void 0){let p=e[c];if(p.type===r&&l&&gT(e,t,s,c))return p.text+=n,t.concatByStreamId.set(s,u+n),!p.promptId&&i&&(p.promptId=i),p.type==="reasoning"&&a!==void 0&&(p.startedAtMs===void 0&&(p.startedAtMs=a),p.endedAtMs=a),!0;if(c===e.length-1||!l)return!1}if(u&&!l)return!1;let d=t.segmentOrdinalByStreamId.get(s),m=d===void 0?0:d+1;return t.segmentOrdinalByStreamId.set(s,m),t.streamableIndexById.set(s,e.length),t.concatByStreamId.set(s,u+n),t.interstitialScanEndByStreamId.set(s,e.length+1),r==="text"?e.push({type:"text",id:dy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:dy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{},...a!==void 0?{startedAtMs:a,endedAtMs:a}:{}}),!0}function hT(e,t){return{...e,...t,tool:t.tool??e.tool,summary:t.summary??e.summary,...t.promptId===void 0&&e.promptId!==void 0?{promptId:e.promptId}:{},...t.input===void 0&&e.input!==void 0?{input:e.input}:{},...t.toolStatus===void 0&&e.toolStatus!==void 0?{toolStatus:e.toolStatus}:{},...t.truncated===void 0&&e.truncated!==void 0?{truncated:e.truncated}:{},...t.inputEstimatedTokens===void 0&&e.inputEstimatedTokens!==void 0?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...t.outputEstimatedTokens===void 0&&e.outputEstimatedTokens!==void 0?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...t.outputChars===void 0&&e.outputChars!==void 0?{outputChars:e.outputChars}:{},...t.failure===void 0&&e.failure!==void 0?{failure:e.failure}:{},...t.duplicateCount===void 0&&e.duplicateCount!==void 0?{duplicateCount:e.duplicateCount}:{}}}function Cp(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function _T(e,t){let r=Cp(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...B(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function yT(){return{merged:[],streams:dT(),toolCallIndexById:new Map,agentProgressIndexByKey:new Map,questionIndexById:new Map,narrationIndex:null,malformedSearchBlockedPromptIds:new Set,malformedSearchBlockedWithoutPrompt:!1}}function bT(e){return typeof e=="string"&&e.includes(nT)}function wT(e){return rT.test(e)}function $T(e){return e.malformedSearchBlockedPromptIds.size===0&&!e.malformedSearchBlockedWithoutPrompt?e.merged:e.merged.filter(t=>t.type!=="text"?!0:!((t.promptId?e.malformedSearchBlockedPromptIds.has(t.promptId):e.malformedSearchBlockedWithoutPrompt)&&wT(t.text)))}function Ce(e,t){t&&e.merged.push(t)}function xT(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function ST(e,t){return{type:"compaction_complete",id:`cc-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokensBefore=="number"?{contextTokensBefore:e.contextTokensBefore}:{},...typeof e?.contextTokensAfter=="number"?{contextTokensAfter:e.contextTokensAfter}:{}}}function IT(e,t){return{type:"context_fill_warning",id:`cfw-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},fillPercent:typeof e?.fillPercent=="number"?e.fillPercent:Number(e?.fillPercent??0),...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{},...typeof e?.contextWindow=="number"?{contextWindow:e.contextWindow}:{}}}function kT(e,t){return{type:"tool_truncated",id:typeof e?.callId=="string"?e.callId:String(t),tool:typeof e?.tool=="string"?e.tool:"",...e?.reason==="truncation_marker"||e?.reason==="size_threshold"?{reason:e.reason}:{},...V(e)?{promptId:V(e)}:{}}}function ET(e,t){return{type:"retry_status",id:`rs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},attempt:typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),message:typeof e?.message=="string"?e.message:"Retrying...",...typeof e?.nextRetryAt=="string"?{nextRetryAt:e.nextRetryAt}:{},...typeof e?.provider=="string"?{provider:e.provider}:{},...typeof e?.errorCode=="string"?{errorCode:e.errorCode}:{},...typeof e?.scope=="string"?{scope:e.scope}:{},...typeof e?.maxAttempts=="number"?{maxAttempts:e.maxAttempts}:{},...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.retryAfterMs=="number"?{retryAfterMs:e.retryAfterMs}:{},...typeof e?.fallbackModel=="string"?{fallbackModel:e.fallbackModel}:{}}}function TT(e){return e==="spawn_provider_error"?{message:"Sandbox failed to start; retrying on a fresh sandbox",scope:"sandbox_spawn"}:e==="spawn_deadline_no_object"||e==="spawn_deadline_no_bridge"||e==="spawn_timeout"?{message:"Sandbox did not start in time; retrying on a fresh sandbox",scope:"sandbox_spawn"}:{message:"Sandbox dropped mid-task; retrying on a fresh sandbox",scope:"sandbox_disconnect"}}function AT(e,t){let r=typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),o=typeof e?.cap=="number"?e.cap:void 0,n=typeof e?.retryPromptId=="string"?e.retryPromptId:V(e),i=typeof e?.reason=="string"?e.reason:void 0,{message:a,scope:s}=TT(i);return{type:"retry_status",id:`pr-retry-${n??t}`,...n?{promptId:n}:{},attempt:r,message:a,scope:s,...o!==void 0?{maxAttempts:o}:{},...i?{reason:i}:{}}}function PT(e,t){let r=typeof e?.eventName=="string"?e.eventName:Ap;return{type:Ap,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function RT(e,t){return{type:"agent_timeline",id:`atl-${t}-${typeof e?.eventType=="string"?e.eventType:"unknown"}`,eventType:typeof e?.eventType=="string"?e.eventType:"unknown",source:typeof e?.source=="string"?e.source:"observed",observer:typeof e?.observer=="string"?e.observer:"unknown",summary:typeof e?.summary=="string"?e.summary:"Observed agent timeline event.",...typeof e?.status=="string"?{status:e.status}:{},...B(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function CT(e,t){let r=V(e);return{type:"agent_progress",id:Lt(e,"ap",t),step:typeof e?.step=="string"?e.step:"unknown",label:typeof e?.label=="string"?e.label:"Working",terminal:e?.terminal===!0,...r?{promptId:r}:{}}}function OT(e,t){let r=CT(e,t.merged.length),o=`${r.promptId??""}\0${r.step}`,n=t.agentProgressIndexByKey.get(o);if(n!==void 0){let i=t.merged[n];t.merged[n]=i.type==="agent_progress"?{...r,id:i.id}:r;return}t.agentProgressIndexByKey.set(o,t.merged.length),t.merged.push(r)}function NT(e,t){return{type:"session_error",id:Lt(e,"err",t),error:typeof e?.error=="string"?e.error:"Unknown error",...V(e)?{promptId:V(e)}:{},...typeof e?.code=="string"?{code:e.code}:{},...typeof e?.command=="string"?{command:e.command}:{}}}function DT(e,t){if(e?.code!=="malformed_search_command"&&!bT(e?.error))return;let r=V(e);r?t.malformedSearchBlockedPromptIds.add(r):t.malformedSearchBlockedWithoutPrompt=!0}function zT(e,t){return{type:"session_resumed_cold",id:Lt(e,"rescold",t),...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.lostSnapshotImageId=="string"?{lostSnapshotImageId:e.lostSnapshotImageId}:e?.lostSnapshotImageId===null?{lostSnapshotImageId:null}:{},...V(e)?{promptId:V(e)}:{}}}function UT(e,t){let r=typeof e?.partType=="string"?e.partType:void 0,o=typeof e?.eventType=="string"?e.eventType:void 0;return r==="text"||o&&oT.has(o)?null:{type:"raw_agent_runtime",id:Lt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function LT(e,t){let r=Array.isArray(e?.files)?e.files.filter(o=>typeof o=="string"):[];return r.length===0?null:{type:"patch",id:`patch-${t}`,files:r,...V(e)?{promptId:V(e)}:{}}}function py(e,t,r,o){vT(r.merged,r.streams,e,Lt(t,e,r.merged.length),mT(t),V(t),o)}function jT(e,t){let r=Lt(e,"tool",t.merged.length),o=t.toolCallIndexById.get(r);if(o!==void 0){let n=t.merged[o];if(n.type==="tool_call"){let i=Cp(e?.toolStatus),a=B(e?.input)?e.input:void 0,s={type:"tool_call",id:r,...typeof e?.tool=="string"?{tool:e.tool}:typeof e?.toolName=="string"?{tool:e.toolName}:{},...typeof e?.summary=="string"&&e.summary.length>0?{summary:e.summary}:{},...V(e)?{promptId:V(e)}:{},...a&&Object.keys(a).length>0?{input:a}:{},...i?{toolStatus:i}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...B(e?.failure)?{failure:e.failure}:{}};t.merged[o]=hT(n,s)}}else{let n=Cp(e?.toolStatus),i={type:"tool_call",id:r,tool:typeof e?.tool=="string"?e.tool:typeof e?.toolName=="string"?e.toolName:"unknown",summary:typeof e?.summary=="string"?e.summary:"",...V(e)?{promptId:V(e)}:{},...B(e?.input)?{input:e.input}:{},...n?{toolStatus:n}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...B(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function MT(e,t){let r=typeof e?.id=="string"?e.id:"",o=t.toolCallIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n.type==="tool_call"&&(t.merged[o]=_T(n,e))}function FT(e,t){let r={type:"question",id:Lt(e,"question",t.merged.length),question:typeof e?.question=="string"?e.question:"",answer:e?.answer==null?null:String(e.answer),...V(e)?{promptId:V(e)}:{},...Array.isArray(e?.options)?{options:e.options}:{}};t.questionIndexById.set(r.id,t.merged.length),t.merged.push(r)}function ZT(e,t){let r=typeof e?.id=="string"?e.id:void 0;if(!r)return;let o=t.questionIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n?.type==="question"&&(t.merged[o]={...n,answer:e?.answer==null?null:String(e.answer)})}function BT(e,t){let r=Array.isArray(e?.todos)?e.todos:[];if(r.length!==0)for(let o=t.merged.length-1;o>=0;o--){let n=t.merged[o];if(n.type==="tool_call"&&n.tool.toLowerCase()==="todowrite"){t.merged[o]={...n,input:{...n.input,todos:r}};break}}}function VT(e,t){let r=uy(e);if(!r)return;let o=V(e);t.merged.push({type:"onboarding_status",id:`onboarding_status:${t.merged.length}`,stage:r.stage,status:r.status,...r.detail?{detail:r.detail}:{},...o?{promptId:o}:{}})}function GT(e,t){let r=typeof e?.text=="string"?e.text.trim():"";if(!r)return;let o=V(e),n={type:"narration",id:"narration",text:r,...o?{promptId:o}:{}};t.narrationIndex===null?(t.narrationIndex=t.merged.length,t.merged.push(n)):t.merged[t.narrationIndex]=n}function _y(e){let t=yT();for(let r of e){let o=hy(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Ce(t,xT(i,t.merged.length));break;case"sandbox_compaction_complete":Ce(t,ST(i,t.merged.length));break;case"sandbox_context_fill_warning":Ce(t,IT(i,t.merged.length));break;case"sandbox_tool_truncated":Ce(t,kT(i,t.merged.length));break;case"retry_status":Ce(t,ET(i,t.merged.length));break;case"prompt_retrying":Ce(t,AT(i,t.merged.length));break;case"zeus_telemetry":Ce(t,PT(i,t.merged.length));break;case"agent_timeline":Ce(t,RT(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":OT(i,t);break;case"session_error":DT(i,t),Ce(t,NT(i,t.merged.length));break;case"session_resumed_cold":Ce(t,zT(i,t.merged.length));break;case"raw_agent_runtime":Ce(t,UT(i,t.merged.length));break;case"reasoning":py("reasoning",i,t,cT(o.raw));break;case"text":py("text",i,t);break;case"patch":Ce(t,LT(i,t.merged.length));break;case"todo_update":BT(i,t);break;case"answer":ZT(i,t);break;case"tool_call":jT(i,t);break;case"tool_update":MT(i,t);break;case"question":FT(i,t);break;case"narration":GT(i,t);break;case"onboarding_status":VT(i,t);break}}return $T(t)}function yy(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Br(i),s=typeof a=="string"&&r.has(a)?a:null;An(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function qT(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="prompt_completed"&&r.type!=="prompt_failed")continue;let o=r.data?.history;return!Array.isArray(o)||o.length===0?null:o}return null}function my(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function fy(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function by(e){let t=ly(e),r=qT(t),o=t.filter(E=>E.type==="prompt_activity"),n=t.filter(E=>E.type==="agent_progress");if(!r)return{events:e,diagnostics:{embeddedHistoryPresent:!1,durablePromptActivityCount:o.length,embeddedPromptActivityCount:0,mergedDurablePromptActivityCount:0,duplicateDurablePromptActivityCount:0,durableAgentProgressCount:n.length,embeddedAgentProgressCount:0,mergedDurableAgentProgressCount:0,duplicateDurableAgentProgressCount:0}};let i=ly(r),a=i.filter(E=>E.type==="prompt_activity"),s=i.filter(E=>E.type==="agent_progress"),u=new Set(a.map(my)),c=new Set(s.map(fy)),l=a.length,d=s.length,m=0,p=0,v=o.filter(E=>{let k=my(E);return u.has(k)?(m+=1,!1):(u.add(k),!0)}),_=n.filter(E=>{let k=fy(E);return c.has(k)?(p+=1,!1):(c.add(k),!0)}),x=[...v,..._].map(E=>E.raw);return{events:x.length>0?[...x,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:v.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var wy=1e3;async function $y(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>wy)throw new y("user",`${e} exceeded ${wy} pages without reaching the end.`);let u=await o(i);n.push(...u.items),a=u.nextCursor,i=a??void 0}while(t&&a);return{items:n,nextCursor:t?null:a}}import{createParser as uA}from"eventsource-parser";function ya(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function xy(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function ba(e){switch(e){case"no_diff":return{state:"no_changes",tone:"info",title:"Completed without code changes.",detail:null};case"no_staged_files":return{state:"no_changes",tone:"info",title:"Completed without publishable code changes.",detail:null};case"prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed before changes could be prepared.",detail:null};case"post_prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed after changes were prepared.",detail:null};default:return{state:"no_change_abnormal",tone:"error",title:"Completed without code changes, but finalization did not report a clean no-op reason.",detail:null}}}var HT="## Previously declined findings on this repository (calibration)",WT="## Findings already reported by other reviewers",KT="## Graphite stack neighbours",JT="## Whole-stack review",Sy=[HT,WT,KT,JT,"## Independent review suggestions"];var ky=/\r?\n/,YT=/\n{3,}/g,XT=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,QT=[/^IMPORTANT: The content above is /i,/^Previous Slack message\b/i,/^Current Slack message author:/i,/^Current Slack channel:/i,/^Thread context(?:\s*\([^)]*\))?\s*[.:]/i,/^Repository:\s+\S+$/i,/^Issue (?:title|body|description|metadata)\s*:/i,/^Triggering comment\s*:/i,/^Review body\s*:/i,/^Recent comments\s*:/i,/^<\/?(?:user_content|instruction_content)\b/i],eA=[/<\/?(?:user_content|instruction_content)\b/i,/^IMPORTANT: The content above is /im,/^Previous Slack message\b/im,/^Current Slack message author:/im,/^Current Slack channel:/im,/^Repository:\s+\S+$/im],tA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function nA(e){let t=e.split(ky),r=[],o=[];if(t.forEach((a,s)=>{let u=Sy.findIndex(c=>a.trim()===c);u!==-1&&(r.push(u),o.push(s))}),o.length===0||!r.every((a,s)=>s===0||a>(r[s-1]??-1)))return e.trim();let i=o[0]??0;return t.slice(0,i).join(`
89
+ `).trim()}function Iy(e){return eA.some(t=>t.test(e))}function rA(e){return e.replace(XT,"").split(ky).filter(o=>!QT.some(n=>n.test(o.trim()))).join(`
90
+ `).replace(YT,`
91
91
 
92
- `).trim()}function Np(e){let t=e.replyToText?.trim();if(t&&!Iy(t))return t;if(eA.test(e.prompt.trimStart()))return tA(e.prompt.trim());if(Iy(e.prompt)){let r=nA(e.prompt);if(r)return r}return t||e.prompt.trim()}var rA=["auth","policy_block","handled_automatically","review_publish_blocked","review_finalization_failed","output_length","context_overflow","aborted","rate_limit","api_error","model_overloaded","config_error","github_pr_context","review_admission_mismatch","github_app_permission","failed_edits","memory_enforcement_failed","failure_loop_suspected","empty_completion","followup_not_started","stale_prompt","max_duration_exceeded","spawn_timeout","spawn_modal_error","spawn_provider_error","spawn_deadline_no_object","spawn_deadline_no_bridge","spawn_preconnect","sandbox_terminated","sandbox_disconnected","sandbox_disconnected_exhausted","sandbox_never_started","session_archived","sandbox_callback","codex_startup_timeout","codex_api_readiness_timeout","codex_session_create_timeout","codex_prompt_dispatch_timeout","codex_not_ready","codex_transport_closed","codex_unrecoverable","question_delivery_failed","malformed_search_command","review_preflight_input_rejected","review_checkout_failed","review_planner_failed","review_planner_timed_out","review_scouts_failed","unknown"],iA=new Set(rA);var Ey={auth:"Authentication failed",policy_block:"A command was blocked by the safety policy",handled_automatically:"Handled automatically",review_publish_blocked:"The review could not be posted",review_finalization_failed:"The review could not be prepared for posting",output_length:"Output was too long",context_overflow:"The request exceeded the model's input limit",aborted:"Stopped by user",rate_limit:"Too many requests. Please retry shortly",api_error:"Model service error",model_overloaded:"The selected model is too busy to accept the request",config_error:"Configuration error",github_pr_context:"The PR details could not be read from GitHub",review_admission_mismatch:"The running review does not match the saved review request",github_app_permission:"The Arcanist GitHub App needs more permissions",failed_edits:"The agent could not apply its file edits",memory_enforcement_failed:"The agent could not confirm that it followed the saved coding rules",failure_loop_suspected:"The same error kept repeating",empty_completion:"The model returned no answer",followup_not_started:"The next task did not start",stale_prompt:"The request was no longer active",max_duration_exceeded:"The task exceeded its time limit",spawn_timeout:"The sandbox did not start before the time limit",spawn_modal_error:"The sandbox provider could not start the sandbox",spawn_provider_error:"The sandbox provider could not start the sandbox",spawn_deadline_no_object:"The sandbox provider did not respond before the time limit",spawn_deadline_no_bridge:"The sandbox did not connect before the startup time limit",spawn_preconnect:"Sandbox failed before connecting",sandbox_terminated:"The sandbox stopped",sandbox_disconnected:"Sandbox disconnected",sandbox_disconnected_exhausted:"Sandbox kept disconnecting",sandbox_never_started:"The sandbox never started the task",session_archived:"The session was archived while the task was running",sandbox_callback:"The sandbox could not report its progress",codex_startup_timeout:"The agent did not start before the time limit",codex_api_readiness_timeout:"The agent was not ready to accept a task",codex_session_create_timeout:"The agent session could not be created",codex_prompt_dispatch_timeout:"The task could not be sent to the agent",codex_not_ready:"The agent was not ready to accept a task",codex_transport_closed:"The connection to the agent closed",codex_unrecoverable:"The agent stopped unexpectedly",question_delivery_failed:"Answer could not be delivered to the agent",malformed_search_command:"A search command with invalid syntax was blocked",review_preflight_input_rejected:"The review could not read a changed file at the PR head",review_checkout_failed:"The PR checkout could not be prepared",review_planner_failed:"The review could not plan its checks",review_planner_timed_out:"The review planner reached its time limit",review_scouts_failed:"The review could not answer its questions",unknown:"Unknown failure"},oA={policy_block:"Policy block",review_publish_blocked:"Review publication blocked",review_finalization_failed:"Review finalization failed",context_overflow:"Context window exceeded",rate_limit:"Rate limited - please retry shortly",model_overloaded:"Model at capacity",github_pr_context:"GitHub pull request context unavailable",review_admission_mismatch:"Review execution admission facts disagree with the request row",github_app_permission:"GitHub App permissions missing",failed_edits:"Edit failure",memory_enforcement_failed:"Memory enforcement failed",failure_loop_suspected:"Suspected failure loop",empty_completion:"Empty completion",followup_not_started:"Follow-up did not start",stale_prompt:"Prompt became inactive",max_duration_exceeded:"Prompt exceeded maximum duration",spawn_timeout:"Sandbox spawn timed out",spawn_modal_error:"Sandbox spawn failed (legacy provider error)",spawn_provider_error:"Sandbox spawn failed (provider API error)",spawn_deadline_no_object:"Sandbox spawn timed out before provider responded",spawn_deadline_no_bridge:"Sandbox startup timed out before the runtime became reachable",sandbox_terminated:"Sandbox terminated",sandbox_never_started:"Sandbox never started the prompt",session_archived:"Session archived while processing",sandbox_callback:"Sandbox callback failed",codex_startup_timeout:"Agent runtime startup timed out",codex_api_readiness_timeout:"Agent runtime did not become ready",codex_session_create_timeout:"Agent runtime session could not be created",codex_prompt_dispatch_timeout:"Prompt could not be delivered to the agent runtime",codex_not_ready:"Agent runtime did not become ready",codex_transport_closed:"Agent runtime connection closed",codex_unrecoverable:"Agent runtime stopped unexpectedly",malformed_search_command:"Malformed search command blocked"};function Ty(e){return typeof e=="string"&&iA.has(e)}function aA(e){return Ty(e)?Ey[e]:Ey.unknown}function Dp(e,t){if(!t||!Ty(t)||t==="unknown")return e;let r=aA(t),o=oA[t];return o&&(e===o||e.startsWith(`${o}:`))?`${r}${e.slice(o.length)}`:e.includes(r)?e:`${r}: ${e}`}var uA=/\.\d+Z$/,cA=/\s+/g,lA=8,dA=80,pA=new Set(Zp),mA=new Set(["creating","reconnecting","stopping","none"]),fA=new Set(["user","resumable","none"]),gA=new Set(["post_execution","publishing","none"]);function vA(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().replace("T"," ").replace(uA," UTC")}function hA(e){switch(e.type){case"text":return e.text;case"tool_call":return`**Tool call:** ${e.tool}${e.summary?` - ${e.summary}`:""}${e.toolStatus?` (${e.toolStatus})`:""}
92
+ `).trim()}function Np(e){let t=e.replyToText?.trim();if(t&&!Iy(t))return t;if(tA.test(e.prompt.trimStart()))return nA(e.prompt.trim());if(Iy(e.prompt)){let r=rA(e.prompt);if(r)return r}return t||e.prompt.trim()}var iA=["auth","policy_block","handled_automatically","review_publish_blocked","review_finalization_failed","output_length","context_overflow","aborted","rate_limit","api_error","model_overloaded","config_error","github_pr_context","review_admission_mismatch","github_app_permission","failed_edits","memory_enforcement_failed","failure_loop_suspected","empty_completion","followup_not_started","stale_prompt","max_duration_exceeded","spawn_timeout","spawn_modal_error","spawn_provider_error","spawn_deadline_no_object","spawn_deadline_no_bridge","spawn_preconnect","sandbox_terminated","sandbox_disconnected","sandbox_disconnected_exhausted","sandbox_never_started","session_archived","sandbox_callback","codex_startup_timeout","codex_api_readiness_timeout","codex_session_create_timeout","codex_prompt_dispatch_timeout","codex_not_ready","codex_transport_closed","codex_unrecoverable","question_delivery_failed","malformed_search_command","review_preflight_input_rejected","review_checkout_failed","review_planner_failed","review_planner_timed_out","review_scouts_failed","unknown"],oA=new Set(iA);var Ey={auth:"Authentication failed",policy_block:"A command was blocked by the safety policy",handled_automatically:"Handled automatically",review_publish_blocked:"The review could not be posted",review_finalization_failed:"The review could not be prepared for posting",output_length:"Output was too long",context_overflow:"The request exceeded the model's input limit",aborted:"Stopped by user",rate_limit:"Too many requests. Please retry shortly",api_error:"Model service error",model_overloaded:"The selected model is too busy to accept the request",config_error:"Configuration error",github_pr_context:"The PR details could not be read from GitHub",review_admission_mismatch:"The running review does not match the saved review request",github_app_permission:"The Arcanist GitHub App needs more permissions",failed_edits:"The agent could not apply its file edits",memory_enforcement_failed:"The agent could not confirm that it followed the saved coding rules",failure_loop_suspected:"The same error kept repeating",empty_completion:"The model returned no answer",followup_not_started:"The next task did not start",stale_prompt:"The request was no longer active",max_duration_exceeded:"The task exceeded its time limit",spawn_timeout:"The sandbox did not start before the time limit",spawn_modal_error:"The sandbox provider could not start the sandbox",spawn_provider_error:"The sandbox provider could not start the sandbox",spawn_deadline_no_object:"The sandbox provider did not respond before the time limit",spawn_deadline_no_bridge:"The sandbox did not connect before the startup time limit",spawn_preconnect:"Sandbox failed before connecting",sandbox_terminated:"The sandbox stopped",sandbox_disconnected:"Sandbox disconnected",sandbox_disconnected_exhausted:"Sandbox kept disconnecting",sandbox_never_started:"The sandbox never started the task",session_archived:"The session was archived while the task was running",sandbox_callback:"The sandbox could not report its progress",codex_startup_timeout:"The agent did not start before the time limit",codex_api_readiness_timeout:"The agent was not ready to accept a task",codex_session_create_timeout:"The agent session could not be created",codex_prompt_dispatch_timeout:"The task could not be sent to the agent",codex_not_ready:"The agent was not ready to accept a task",codex_transport_closed:"The connection to the agent closed",codex_unrecoverable:"The agent stopped unexpectedly",question_delivery_failed:"Answer could not be delivered to the agent",malformed_search_command:"A search command with invalid syntax was blocked",review_preflight_input_rejected:"The review could not read a changed file at the PR head",review_checkout_failed:"The PR checkout could not be prepared",review_planner_failed:"The review could not plan its checks",review_planner_timed_out:"The review planner reached its time limit",review_scouts_failed:"The review could not answer its questions",unknown:"Unknown failure"},aA={policy_block:"Policy block",review_publish_blocked:"Review publication blocked",review_finalization_failed:"Review finalization failed",context_overflow:"Context window exceeded",rate_limit:"Rate limited - please retry shortly",model_overloaded:"Model at capacity",github_pr_context:"GitHub pull request context unavailable",review_admission_mismatch:"Review execution admission facts disagree with the request row",github_app_permission:"GitHub App permissions missing",failed_edits:"Edit failure",memory_enforcement_failed:"Memory enforcement failed",failure_loop_suspected:"Suspected failure loop",empty_completion:"Empty completion",followup_not_started:"Follow-up did not start",stale_prompt:"Prompt became inactive",max_duration_exceeded:"Prompt exceeded maximum duration",spawn_timeout:"Sandbox spawn timed out",spawn_modal_error:"Sandbox spawn failed (legacy provider error)",spawn_provider_error:"Sandbox spawn failed (provider API error)",spawn_deadline_no_object:"Sandbox spawn timed out before provider responded",spawn_deadline_no_bridge:"Sandbox startup timed out before the runtime became reachable",sandbox_terminated:"Sandbox terminated",sandbox_never_started:"Sandbox never started the prompt",session_archived:"Session archived while processing",sandbox_callback:"Sandbox callback failed",codex_startup_timeout:"Agent runtime startup timed out",codex_api_readiness_timeout:"Agent runtime did not become ready",codex_session_create_timeout:"Agent runtime session could not be created",codex_prompt_dispatch_timeout:"Prompt could not be delivered to the agent runtime",codex_not_ready:"Agent runtime did not become ready",codex_transport_closed:"Agent runtime connection closed",codex_unrecoverable:"Agent runtime stopped unexpectedly",malformed_search_command:"Malformed search command blocked"};function Ty(e){return typeof e=="string"&&oA.has(e)}function sA(e){return Ty(e)?Ey[e]:Ey.unknown}function Dp(e,t){if(!t||!Ty(t)||t==="unknown")return e;let r=sA(t),o=aA[t];return o&&(e===o||e.startsWith(`${o}:`))?`${r}${e.slice(o.length)}`:e.includes(r)?e:`${r}: ${e}`}var cA=/\.\d+Z$/,lA=/\s+/g,dA=8,pA=80,mA=new Set(Zp),fA=new Set(["creating","reconnecting","stopping","none"]),gA=new Set(["user","resumable","none"]),vA=new Set(["post_execution","publishing","none"]);function hA(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().replace("T"," ").replace(cA," UTC")}function _A(e){switch(e.type){case"text":return e.text;case"tool_call":return`**Tool call:** ${e.tool}${e.summary?` - ${e.summary}`:""}${e.toolStatus?` (${e.toolStatus})`:""}
93
93
  `;case"reasoning":return`<details><summary>Reasoning</summary>
94
94
  <br>
95
95
 
@@ -113,25 +113,25 @@ ${e.answer?`**Answer:** ${e.answer}
113
113
  `;case"prompt_activity":return"";case"agent_progress":return`*[${e.label}]*
114
114
  `;case"narration":return`*[Currently: ${e.text}]*
115
115
  `;case"onboarding_status":return`*[${e.stage}: ${e.status}]*
116
- `;case"raw_agent_runtime":return""}}function zp(e){return e.toLocaleString()}function wa(e){return typeof e=="string"&&e.trim()?e:null}function Py(e){let{prUrl:t,publishedBranch:r,lastBranch:o}=_A(e),n=wa(e.baseBranch),i=r??(o&&o!==n?o:null);return t?`PR: ${t}${i?` (${i})`:""}`:i?`Branch: ${i}`:null}function _A(e){let t={},r=wa(e.prUrl),o=wa(e.publishedBranch),n=wa(e.lastBranch);return r&&(t.prUrl=r),o&&(t.publishedBranch=o),n&&(t.lastBranch=n),t}function Ry(e){let t=[],r=e.prompts.map(i=>i.id),o=yy(e.events,r);t.push(`# Session transcript
117
- `),e.session.repoUrl&&t.push(`**Repo:** ${e.session.repoUrl} `),t.push(`**Session:** ${e.session.id.slice(0,lA)} `),t.push(`**Created:** ${vA(e.session.createdAt)} `),t.push(`**Status:** ${e.session.status} `);let n=xy(e.prompts);if(!e.pr?.url&&ya(n)){let i=ba(n.noChangeReason);i.state!=="no_changes"&&t.push(`**Outcome:** ${i.title} `)}t.push(`**Tokens:** ${zp(e.tokens.inputTokens)} in / ${zp(e.tokens.outputTokens)} out / ${zp(e.tokens.totalTokens)} total`),e.pr?.url&&t.push(`**PR:** ${e.pr.url}${e.pr.branch?` (${e.pr.branch})`:""}`),t.push("");for(let i=0;i<e.prompts.length;i++){let a=e.prompts[i],s=o.get(a.id)??[],{events:u,diagnostics:c}=by(s);c.mergedDurablePromptActivityCount>0&&console.error("[transcript] merged durable prompt_activity events missing from embedded terminal history",{sessionId:e.session.id,promptId:a.id,mergedDurablePromptActivityCount:c.mergedDurablePromptActivityCount,durablePromptActivityCount:c.durablePromptActivityCount,embeddedPromptActivityCount:c.embeddedPromptActivityCount,duplicateDurablePromptActivityCount:c.duplicateDurablePromptActivityCount}),c.mergedDurableAgentProgressCount>0&&console.error("[transcript] merged durable agent_progress events missing from embedded terminal history",{sessionId:e.session.id,promptId:a.id,mergedDurableAgentProgressCount:c.mergedDurableAgentProgressCount,durableAgentProgressCount:c.durableAgentProgressCount,embeddedAgentProgressCount:c.embeddedAgentProgressCount,duplicateDurableAgentProgressCount:c.duplicateDurableAgentProgressCount});let l=_y(u);if(t.push(`---
116
+ `;case"raw_agent_runtime":return""}}function zp(e){return e.toLocaleString()}function wa(e){return typeof e=="string"&&e.trim()?e:null}function Py(e){let{prUrl:t,publishedBranch:r,lastBranch:o}=yA(e),n=wa(e.baseBranch),i=r??(o&&o!==n?o:null);return t?`PR: ${t}${i?` (${i})`:""}`:i?`Branch: ${i}`:null}function yA(e){let t={},r=wa(e.prUrl),o=wa(e.publishedBranch),n=wa(e.lastBranch);return r&&(t.prUrl=r),o&&(t.publishedBranch=o),n&&(t.lastBranch=n),t}function Ry(e){let t=[],r=e.prompts.map(i=>i.id),o=yy(e.events,r);t.push(`# Session transcript
117
+ `),e.session.repoUrl&&t.push(`**Repo:** ${e.session.repoUrl} `),t.push(`**Session:** ${e.session.id.slice(0,dA)} `),t.push(`**Created:** ${hA(e.session.createdAt)} `),t.push(`**Status:** ${e.session.status} `);let n=xy(e.prompts);if(!e.pr?.url&&ya(n)){let i=ba(n.noChangeReason);i.state!=="no_changes"&&t.push(`**Outcome:** ${i.title} `)}t.push(`**Tokens:** ${zp(e.tokens.inputTokens)} in / ${zp(e.tokens.outputTokens)} out / ${zp(e.tokens.totalTokens)} total`),e.pr?.url&&t.push(`**PR:** ${e.pr.url}${e.pr.branch?` (${e.pr.branch})`:""}`),t.push("");for(let i=0;i<e.prompts.length;i++){let a=e.prompts[i],s=o.get(a.id)??[],{events:u,diagnostics:c}=by(s);c.mergedDurablePromptActivityCount>0&&console.error("[transcript] merged durable prompt_activity events missing from embedded terminal history",{sessionId:e.session.id,promptId:a.id,mergedDurablePromptActivityCount:c.mergedDurablePromptActivityCount,durablePromptActivityCount:c.durablePromptActivityCount,embeddedPromptActivityCount:c.embeddedPromptActivityCount,duplicateDurablePromptActivityCount:c.duplicateDurablePromptActivityCount}),c.mergedDurableAgentProgressCount>0&&console.error("[transcript] merged durable agent_progress events missing from embedded terminal history",{sessionId:e.session.id,promptId:a.id,mergedDurableAgentProgressCount:c.mergedDurableAgentProgressCount,durableAgentProgressCount:c.durableAgentProgressCount,embeddedAgentProgressCount:c.embeddedAgentProgressCount,duplicateDurableAgentProgressCount:c.duplicateDurableAgentProgressCount});let l=_y(u);if(t.push(`---
118
118
  `),t.push(`## Turn ${i+1}
119
119
  `),t.push(`**Prompt ID:** ${a.id} `),t.push(`**Prompt status:** ${a.status}${a.error?` | ${a.error}`:""}`),t.push(""),t.push(`**User:**
120
120
  `),t.push(Np({prompt:a.prompt,replyToText:a.replyToText})),t.push(""),l.length>0){t.push(`**Assistant:**
121
- `);let d="";for(let m of l){let p=hA(m);p&&(m.type==="text"?d+=p:(d&&(t.push(d.trimEnd()),t.push(""),d=""),t.push(p)))}d&&(t.push(d.trimEnd()),t.push(""))}else a.error&&(t.push(`**Assistant:**
121
+ `);let d="";for(let m of l){let p=_A(m);p&&(m.type==="text"?d+=p:(d&&(t.push(d.trimEnd()),t.push(""),d=""),t.push(p)))}d&&(t.push(d.trimEnd()),t.push(""))}else a.error&&(t.push(`**Assistant:**
122
122
  `),t.push(`**Error:** ${a.error}`),t.push(""))}return t.join(`
123
- `)}function Cy(e){let t=[],r=sA({onEvent:i=>{let a=i.id===void 0?void 0:Number.parseInt(i.id,10);t.push({event:i.event?.trim()??"message",...a!==void 0&&Number.isFinite(a)?{id:a}:{},data:i.data.trim()})}});r.feed(e),r.feed(`
123
+ `)}function Cy(e){let t=[],r=uA({onEvent:i=>{let a=i.id===void 0?void 0:Number.parseInt(i.id,10);t.push({event:i.event?.trim()??"message",...a!==void 0&&Number.isFinite(a)?{id:a}:{},data:i.data.trim()})}});r.feed(e),r.feed(`
124
124
 
125
- `);let o=null,n=[];for(let i of t){let a=i.data?yA(i.data):{},s=B(a)?a:{};if(i.event==="status"){let u=s.phase,l={phase:typeof u=="string"&&pA.has(u)?u:null},d=Up(s.sandboxSubstate,mA);d!==void 0&&(l.sandboxSubstate=d);let m=Up(s.stopMode,fA);m!==void 0&&(l.stopMode=m);let p=Up(s.finalizingStep,gA);p!==void 0&&(l.finalizingStep=p),typeof s.title=="string"&&(l.title=s.title),(typeof s.spawnDurationMs=="number"||s.spawnDurationMs===null)&&(l.spawnDurationMs=s.spawnDurationMs),o=l;continue}n.push({type:i.event,...i.id!==void 0?{id:i.id}:{},data:s})}return{status:o,events:n}}function Up(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function yA(e){try{return JSON.parse(e)}catch(t){throw new Error(`Malformed SSE JSON payload: ${xe(t)}`)}}function Ay(e,t){if(!e)return"";let r=t.get(e);return r?` - ${r}`:""}function Oy(e){let t=new Map;for(let r of e){let o=Np({prompt:r.prompt,replyToText:r.replyToText});t.set(r.promptId,o.replace(cA," ").trim().slice(0,dA))}return t}function $a(e,t){let r=B(e.data)?e.data:{};switch(e.type){case"text":return{kind:"text",text:String(r.text??"")};case"prompt_enqueued":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[queued] ${o??"unknown"}${Ay(o,t.promptLabels)}`}}case"prompt_processing":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[prompt] ${o??"unknown"} started${Ay(o,t.promptLabels)}`}}case"prompt_completed":return{kind:"line",line:`[prompt] ${(typeof r.promptId=="string"?r.promptId:void 0)??"unknown"} completed`};case"prompt_failed":{let o=typeof r.promptId=="string"?r.promptId:void 0,n=typeof r.error=="string"?r.error:"unknown error";return{kind:"line",line:`[prompt] ${o??"unknown"} failed: ${n}`}}case"tool_call":{let o=String(r.id??""),n=String(r.tool??"unknown"),i=String(r.summary??"");return t.toolCalls.set(o,{tool:n,summary:i}),{kind:"line",line:`[tool] ${n}${i?` - ${i}`:""}`}}case"tool_update":{let o=String(r.id??""),n=typeof r.status=="string"?r.status:null;if(!n)return null;let i=t.toolCalls.get(o);return i?{kind:"line",line:`[tool ${n}] ${i.tool}${i.summary?` - ${i.summary}`:""}`}:{kind:"line",line:`[tool] ${o} ${n}`}}case"question":return{kind:"line",line:`[question] ${String(r.question??"")}`};case"patch":return{kind:"line",line:`[patch] ${(Array.isArray(r.files)?r.files.filter(n=>typeof n=="string"):[]).join(", ")}`};case"agent_timeline":{let o=String(r.eventType??"timeline"),n=typeof r.status=="string"?` ${r.status}`:"";return{kind:"line",line:`[agent] ${o}${n}: ${String(r.summary??"")}`}}case"session_error":return{kind:"line",line:`[error] ${Dp(String(r.error??"Unknown error"),typeof r.code=="string"?r.code:null)}`};case"pr_created":case"pr_updated":return{kind:"line",line:`[pr] ${String(r.prUrl??"")}`};case"pr_failed":return{kind:"line",line:`[pr error] ${String(r.error??"Unknown error")}`};case"session_idle":return{kind:"line",line:"[idle] waiting for next prompt"};default:return null}}function Ny(e,t,r,o){return!r||r.sandboxSubstate!=="reconnecting"?null:e||(!t||t.sandboxSubstate==="reconnecting"?null:{since:o,heldPhase:t.phase,heldSubstate:t.sandboxSubstate??"none"})}function bA(e,t){return e!==null&&t-e.since<15e3}function Dy(e,t,r){return bA(t,r)?{...e,phase:t.heldPhase,sandboxSubstate:t.heldSubstate}:e}var wA=/^\d+$/;function Lp(e,t,r){if(!e)return r;if(!wA.test(e))throw new y("user",`${t} must be a non-negative integer.`);let o=Number(e);if(!Number.isSafeInteger(o))throw new y("user",`${t} must be a non-negative integer.`);return o}function Vr(e){if(e!==null&&Date.now()>=e)throw new y("server","Timed out waiting for session events.")}function zy(e){if(e!==null)return Math.max(0,e-Date.now())}function $A(e){let t=e.phase??"unknown",r=[];e.sandboxSubstate&&e.sandboxSubstate!=="none"&&r.push(e.sandboxSubstate),e.stopMode&&e.stopMode!=="none"&&r.push(e.stopMode),e.finalizingStep&&e.finalizingStep!=="none"&&r.push(e.finalizingStep==="post_execution"?"finishing":e.finalizingStep);let o=r.length>0?`${t}/${r.join("/")}`:t,n=[];return e.title&&n.push(e.title),e.spawnDurationMs!=null&&n.push(`spawn ${(e.spawnDurationMs/1e3).toFixed(1)}s`),n.length>0?`[status] ${o} | ${n.join(" | ")}`:`[status] ${o}`}function xA(e,t,r,o){let n=e.phase?{phase:e.phase,sandboxSubstate:e.sandboxSubstate}:null,i=Ny(t,r,n,o);return{displayStatus:n?{...e,...Dy(n,i,o)}:e,mask:i,view:n}}async function SA(e,t){try{let o=(await R(e,P("/api/sessions/:sessionId/prompts",{sessionId:t}))).prompts??[];for(let n=o.length-1;n>=0;n--){if(o[n].status!=="completed")continue;let i=o[n].result;if(ya(i)){let a=ba(i.noChangeReason);a.state!=="no_changes"&&console.log(`[outcome] ${a.title}`)}break}}catch{}}async function jp(e,t){let r=await R(e,P("/api/sessions/:sessionId/prompts",{sessionId:t}));return Oy(r.prompts)}async function Uy(e,t,r){let o=ee(r,t),n=he(o),i=Ze(t.pollInterval),a=Lp(t.afterSequence,"--after-sequence",0),s=Lp(t.limit,"--limit",Yh),u=Lp(t.timeout,"--timeout",0),c=u>0?Date.now()+u:null;if(s===0)throw new y("user","--limit must be greater than 0.");let l=Se(r,t),d=new Map;if(!l)try{d=await jp(n,e)}catch(k){console.error(`Warning: failed to fetch prompt labels for session ${e}: ${xe(k)}`)}let m={promptLabels:d,toolCalls:new Map},p=a,v=null,_=!1,x=null,E=null;l||console.log(`Watching session ${e}...`);try{for(;;){Vr(c);let k=new URLSearchParams({afterSequence:String(p),limit:String(s)}),A=zy(c),S;try{S=await tm(n,`${P("/api/sessions/:sessionId/events",{sessionId:e})}?${k}`,A===void 0?void 0:{timeoutMs:A})}catch(ne){throw Vr(c),ne}let O=Cy(S),z=O.events.length>=s;if(!l&&O.status){let ne=xA(O.status,x,E,Date.now());x=ne.mask,E=ne.view;let Te=$A(ne.displayStatus);Te!==v&&(_&&(process.stdout.write(`
125
+ `);let o=null,n=[];for(let i of t){let a=i.data?bA(i.data):{},s=B(a)?a:{};if(i.event==="status"){let u=s.phase,l={phase:typeof u=="string"&&mA.has(u)?u:null},d=Up(s.sandboxSubstate,fA);d!==void 0&&(l.sandboxSubstate=d);let m=Up(s.stopMode,gA);m!==void 0&&(l.stopMode=m);let p=Up(s.finalizingStep,vA);p!==void 0&&(l.finalizingStep=p),typeof s.title=="string"&&(l.title=s.title),(typeof s.spawnDurationMs=="number"||s.spawnDurationMs===null)&&(l.spawnDurationMs=s.spawnDurationMs),o=l;continue}n.push({type:i.event,...i.id!==void 0?{id:i.id}:{},data:s})}return{status:o,events:n}}function Up(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function bA(e){try{return JSON.parse(e)}catch(t){throw new Error(`Malformed SSE JSON payload: ${xe(t)}`)}}function Ay(e,t){if(!e)return"";let r=t.get(e);return r?` - ${r}`:""}function Oy(e){let t=new Map;for(let r of e){let o=Np({prompt:r.prompt,replyToText:r.replyToText});t.set(r.promptId,o.replace(lA," ").trim().slice(0,pA))}return t}function $a(e,t){let r=B(e.data)?e.data:{};switch(e.type){case"text":return{kind:"text",text:String(r.text??"")};case"prompt_enqueued":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[queued] ${o??"unknown"}${Ay(o,t.promptLabels)}`}}case"prompt_processing":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[prompt] ${o??"unknown"} started${Ay(o,t.promptLabels)}`}}case"prompt_completed":return{kind:"line",line:`[prompt] ${(typeof r.promptId=="string"?r.promptId:void 0)??"unknown"} completed`};case"prompt_failed":{let o=typeof r.promptId=="string"?r.promptId:void 0,n=typeof r.error=="string"?r.error:"unknown error";return{kind:"line",line:`[prompt] ${o??"unknown"} failed: ${n}`}}case"tool_call":{let o=String(r.id??""),n=String(r.tool??"unknown"),i=String(r.summary??"");return t.toolCalls.set(o,{tool:n,summary:i}),{kind:"line",line:`[tool] ${n}${i?` - ${i}`:""}`}}case"tool_update":{let o=String(r.id??""),n=typeof r.status=="string"?r.status:null;if(!n)return null;let i=t.toolCalls.get(o);return i?{kind:"line",line:`[tool ${n}] ${i.tool}${i.summary?` - ${i.summary}`:""}`}:{kind:"line",line:`[tool] ${o} ${n}`}}case"question":return{kind:"line",line:`[question] ${String(r.question??"")}`};case"patch":return{kind:"line",line:`[patch] ${(Array.isArray(r.files)?r.files.filter(n=>typeof n=="string"):[]).join(", ")}`};case"agent_timeline":{let o=String(r.eventType??"timeline"),n=typeof r.status=="string"?` ${r.status}`:"";return{kind:"line",line:`[agent] ${o}${n}: ${String(r.summary??"")}`}}case"session_error":return{kind:"line",line:`[error] ${Dp(String(r.error??"Unknown error"),typeof r.code=="string"?r.code:null)}`};case"pr_created":case"pr_updated":return{kind:"line",line:`[pr] ${String(r.prUrl??"")}`};case"pr_failed":return{kind:"line",line:`[pr error] ${String(r.error??"Unknown error")}`};case"session_idle":return{kind:"line",line:"[idle] waiting for next prompt"};default:return null}}function Ny(e,t,r,o){return!r||r.sandboxSubstate!=="reconnecting"?null:e||(!t||t.sandboxSubstate==="reconnecting"?null:{since:o,heldPhase:t.phase,heldSubstate:t.sandboxSubstate??"none"})}function wA(e,t){return e!==null&&t-e.since<15e3}function Dy(e,t,r){return wA(t,r)?{...e,phase:t.heldPhase,sandboxSubstate:t.heldSubstate}:e}var $A=/^\d+$/;function Lp(e,t,r){if(!e)return r;if(!$A.test(e))throw new y("user",`${t} must be a non-negative integer.`);let o=Number(e);if(!Number.isSafeInteger(o))throw new y("user",`${t} must be a non-negative integer.`);return o}function Vr(e){if(e!==null&&Date.now()>=e)throw new y("server","Timed out waiting for session events.")}function zy(e){if(e!==null)return Math.max(0,e-Date.now())}function xA(e){let t=e.phase??"unknown",r=[];e.sandboxSubstate&&e.sandboxSubstate!=="none"&&r.push(e.sandboxSubstate),e.stopMode&&e.stopMode!=="none"&&r.push(e.stopMode),e.finalizingStep&&e.finalizingStep!=="none"&&r.push(e.finalizingStep==="post_execution"?"finishing":e.finalizingStep);let o=r.length>0?`${t}/${r.join("/")}`:t,n=[];return e.title&&n.push(e.title),e.spawnDurationMs!=null&&n.push(`spawn ${(e.spawnDurationMs/1e3).toFixed(1)}s`),n.length>0?`[status] ${o} | ${n.join(" | ")}`:`[status] ${o}`}function SA(e,t,r,o){let n=e.phase?{phase:e.phase,sandboxSubstate:e.sandboxSubstate}:null,i=Ny(t,r,n,o);return{displayStatus:n?{...e,...Dy(n,i,o)}:e,mask:i,view:n}}async function IA(e,t){try{let o=(await R(e,P("/api/sessions/:sessionId/prompts",{sessionId:t}))).prompts??[];for(let n=o.length-1;n>=0;n--){if(o[n].status!=="completed")continue;let i=o[n].result;if(ya(i)){let a=ba(i.noChangeReason);a.state!=="no_changes"&&console.log(`[outcome] ${a.title}`)}break}}catch{}}async function jp(e,t){let r=await R(e,P("/api/sessions/:sessionId/prompts",{sessionId:t}));return Oy(r.prompts)}async function Uy(e,t,r){let o=ee(r,t),n=he(o),i=Ze(t.pollInterval),a=Lp(t.afterSequence,"--after-sequence",0),s=Lp(t.limit,"--limit",Yh),u=Lp(t.timeout,"--timeout",0),c=u>0?Date.now()+u:null;if(s===0)throw new y("user","--limit must be greater than 0.");let l=Se(r,t),d=new Map;if(!l)try{d=await jp(n,e)}catch(k){console.error(`Warning: failed to fetch prompt labels for session ${e}: ${xe(k)}`)}let m={promptLabels:d,toolCalls:new Map},p=a,v=null,_=!1,x=null,E=null;l||console.log(`Watching session ${e}...`);try{for(;;){Vr(c);let k=new URLSearchParams({afterSequence:String(p),limit:String(s)}),A=zy(c),S;try{S=await tm(n,`${P("/api/sessions/:sessionId/events",{sessionId:e})}?${k}`,A===void 0?void 0:{timeoutMs:A})}catch(ne){throw Vr(c),ne}let O=Cy(S),z=O.events.length>=s;if(!l&&O.status){let ne=SA(O.status,x,E,Date.now());x=ne.mask,E=ne.view;let Te=xA(ne.displayStatus);Te!==v&&(_&&(process.stdout.write(`
126
126
  `),_=!1),console.log(Te),v=Te)}for(let ne of O.events){if(typeof ne.id=="number"&&ne.id>p&&(p=ne.id),l){process.stdout.write(`${JSON.stringify({sequence:ne.id,type:ne.type,data:ne.data})}
127
127
  `);continue}let Te=$a(ne,m);if(Te){if(Te.kind==="text"){if(!Te.text)continue;_||(process.stdout.write("assistant> "),_=!0),process.stdout.write(Te.text);continue}_&&(process.stdout.write(`
128
128
  `),_=!1),console.log(Te.line)}}if(z){Vr(c);continue}if(O.status?.phase&&Xh(O.status.phase)){!l&&O.status.phase==="completed"&&(_&&(process.stdout.write(`
129
- `),_=!1),await SA(n,e));break}Vr(c);let G=zy(c);await Gr(G===void 0?i:Math.min(i,G)),Vr(c)}}finally{_&&process.stdout.write(`
129
+ `),_=!1),await IA(n,e));break}Vr(c);let G=zy(c);await Gr(G===void 0?i:Math.min(i,G)),Vr(c)}}finally{_&&process.stdout.write(`
130
130
  `)}}async function Ly(e,t){let r=ee(t,e),o=he(r),{items:n,nextCursor:i}=await $y("sessions list --all",e.all===!0,e.cursor,async s=>{let u=new URLSearchParams;e.status&&u.set("status",e.status),e.scope&&u.set("scope",e.scope),e.scope==="business"&&u.set("includeSelf","true"),e.search&&u.set("q",e.search),e.repo&&u.set("repo",e.repo),e.limit&&u.set("limit",e.limit),s&&u.set("cursor",s);let c=await R(o,`${P("/api/sessions")}${u.size?`?${u.toString()}`:""}`);return{items:c.sessions,nextCursor:c.nextCursor}}),a={sessions:n,nextCursor:i};if(Se(t,e)){Ve(a);return}if(a.sessions.length===0){console.log("No sessions found.");return}for(let s of a.sessions){let u=F(String(s.id??s.sessionId??"")),c=F(String(s.status??"")),l=typeof s.title=="string"?` ${F(s.title)}`:"";console.log(`${u} ${c}${l}`)}a.nextCursor&&console.log(`Next cursor: ${F(a.nextCursor)}`)}async function jy(e,t,r){let o=ee(r,t),n=he(o),i=await R(n,P("/api/sessions/:sessionId",{sessionId:e}));if(Se(r,t)){Ve(i);return}let a=i.session&&typeof i.session=="object"&&!Array.isArray(i.session)?i.session:i;console.log(`Session: ${F(String(a.sessionId??a.id??e))}`),console.log(`Status: ${F(String(a.phase??a.status??"unknown"))}`),a.repoUrl&&console.log(`Repo: ${F(String(a.repoUrl))}`),a.title&&console.log(`Title: ${F(String(a.title))}`);let s=Py(a);s&&console.log(F(s))}async function My(e,t,r){let o=ee(r,t),n=he(o),i=await R(n,`${P("/api/sessions/:sessionId/view",{sessionId:e})}?promptLimit=1`);D(r,o,i,a=>{o.quiet||console.log(Oe(JSON.stringify(a,null,2)))})}async function Fy(e,t,r){let o=t.afterSequence,n=t.beforeSequence;if(t.follow){if(n)throw new y("user","--before-sequence cannot be used with --follow.");if(t.promptId)throw new y("user","--prompt-id cannot be used with --follow because the follow endpoint does not support prompt filtering.");await Uy(e,{...t,pollInterval:t.pollInterval,afterSequence:o,limit:t.limit},r);return}let i=ee(r,t),a=he(i),s=new URLSearchParams;o&&s.set("after_sequence",o),n&&s.set("before_sequence",n),t.promptId&&s.set("prompt_id",t.promptId),t.limit&&s.set("limit",t.limit);let u=await R(a,`${P("/api/sessions/:sessionId/events/history",{sessionId:e})}${s.size?`?${s.toString()}`:""}`);if(Se(r,t)){Ve(u);return}let l={promptLabels:await jp(a,e).catch(m=>(console.error(`Warning: failed to fetch prompt labels for session ${e}: ${xe(m)}`),new Map)),toolCalls:new Map},d=!1;for(let m of u.events){let p=$a({type:An(m),data:Op(m)??{}},l);p?.kind==="line"&&(d&&(process.stdout.write(`
131
131
  `),d=!1),console.log(p.line)),p?.kind==="text"&&p.text&&(process.stdout.write(p.text),d=!0)}d&&process.stdout.write(`
132
- `)}import{execFile as IA}from"node:child_process";import{constants as kA}from"node:fs";import{access as EA}from"node:fs/promises";import{basename as TA,delimiter as AA,join as Mp,resolve as xa}from"node:path";import{promisify as PA}from"node:util";var Sa=PA(IA);async function Zy(e,t,r){let o=ee(r,t);Ip(t.automaticReview);let n=process.env.npm_execpath,i=n&&TA(n)==="npm-cli.js"?process.execPath:"npm",a=i===process.execPath?[n]:[],s={shell:process.platform==="win32"&&i==="npm"},u=`@tryarcanist/cli@${Ye}`,c;try{c=(await Sa(i,[...a,"prefix","--global"],s)).stdout.trim()}catch{throw new y("user","Could not find npm's global install directory.",{hint:"Install Node.js 22 or newer with npm, then run setup again."})}let l=process.platform==="win32",d=Mp(c,...l?[]:["lib"],"node_modules/@tryarcanist/cli/dist/index.js"),m;try{m=(await Sa(process.execPath,[d,"--version"])).stdout.trim()}catch{}if(m!==Ye){!o.json&&!o.quiet&&process.stderr.write(`Installing Arcanist for future reviews\u2026
133
- `);try{await Sa(i,[...a,"install","--global",u,"--no-fund","--no-audit"],s)}catch{throw new y("user","Could not install the Arcanist CLI globally.",{hint:`Run npm install --global ${u} to see npm's error. Use a writable npm prefix, then run setup again.`})}try{m=(await Sa(process.execPath,[d,"--version"])).stdout.trim()}catch{throw new y("user","Arcanist was installed, but the installed command could not start.",{hint:`Run npm install --global ${u}, then run setup again.`})}if(m!==Ye)throw new y("user","The installed Arcanist version does not match this setup command.",{hint:`Run npm install --global ${u}, then run setup again.`})}let p=l?c:Mp(c,"bin");try{await EA(Mp(p,l?"arcanist.cmd":"arcanist"),kA.X_OK)}catch{throw new y("user","Arcanist is installed, but npm did not create an executable command.",{hint:`Run npm install --global ${u} --bin-links, then run setup again.`})}if(!((l?process.env.Path??process.env.PATH:process.env.PATH)??"").split(AA).some(_=>l?xa(_).toLowerCase()===xa(p).toLowerCase():xa(_)===xa(p)))throw new y("user","Arcanist is installed, but its directory is not on PATH.",{hint:l?`Add ${p} to your user PATH, open a new terminal, then run arcanist onboard.`:`Run export PATH=${pt(p)}:"$PATH", add it to your shell profile, then run arcanist onboard.`});!o.json&&!o.quiet&&process.stderr.write(`Arcanist is installed. After setup, run arcanist review.
134
- `),await ma(e,t,r)}async function By(e,t,r){let{config:o}=Y(r,t),n=RA(t.last),i=await R(o,P("/api/sessions/:sessionId/export",{sessionId:e})),a=n==null?i:CA(i,n,{includeBoundaryEvent:!Se(r,t)});D(r,t,a,s=>console.log(Ry(s)))}function RA(e){if(e===void 0)return null;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new y("user","--last must be a positive integer.");return t}function CA(e,t,r){let o=Math.max(0,e.events.length-t),n=OA(e.events,o),i=e.events.slice(o),a=r.includeBoundaryEvent&&n!==null&&n<o?[e.events[n],...i]:i,s=NA(a);if(n!==null){let c=Br(e.events[n]);c&&s.add(c)}let u=e.prompts.filter(c=>s.has(c.id));return{...e,prompts:u,events:a}}function OA(e,t){for(let r=t;r>=0;r--){let o=e[r];if(o&&An(o)==="prompt_processing")return r}return null}function NA(e){let t=new Set;for(let r of e){let o=Br(r);o&&t.add(o)}return t}function Vy(){let e=new DA().name("arcanist").description("Arcanist CLI").version(Ye).option("--json","Output machine-readable JSON").option("--quiet","Suppress non-essential stderr output").option("--api-url <url>","Override API URL. Prefer ARCANIST_API_URL for persistent use").option("--token <token>","Override API token. Prefer ARCANIST_TOKEN because flags can be visible in shell history and process lists").option("--no-color","Disable color output").configureHelp({showGlobalOptions:!0}).addHelpCommand(!1).exitOverride().addHelpText("after",`
132
+ `)}import{execFile as kA}from"node:child_process";import{constants as EA}from"node:fs";import{access as TA}from"node:fs/promises";import{basename as AA,delimiter as PA,join as Mp,resolve as xa}from"node:path";import{promisify as RA}from"node:util";var Sa=RA(kA);async function Zy(e,t,r){let o=ee(r,t);Ip(t.automaticReview);let n=process.env.npm_execpath,i=n&&AA(n)==="npm-cli.js"?process.execPath:"npm",a=i===process.execPath?[n]:[],s={shell:process.platform==="win32"&&i==="npm"},u=`@tryarcanist/cli@${Ye}`,c;try{c=(await Sa(i,[...a,"prefix","--global"],s)).stdout.trim()}catch{throw new y("user","Could not find npm's global install directory.",{hint:"Install Node.js 22 or newer with npm, then run setup again."})}let l=process.platform==="win32",d=Mp(c,...l?[]:["lib"],"node_modules/@tryarcanist/cli/dist/index.js"),m;try{m=(await Sa(process.execPath,[d,"--version"])).stdout.trim()}catch{}if(m!==Ye){!o.json&&!o.quiet&&process.stderr.write(`Installing Arcanist for future reviews\u2026
133
+ `);try{await Sa(i,[...a,"install","--global",u,"--no-fund","--no-audit"],s)}catch{throw new y("user","Could not install the Arcanist CLI globally.",{hint:`Run npm install --global ${u} to see npm's error. Use a writable npm prefix, then run setup again.`})}try{m=(await Sa(process.execPath,[d,"--version"])).stdout.trim()}catch{throw new y("user","Arcanist was installed, but the installed command could not start.",{hint:`Run npm install --global ${u}, then run setup again.`})}if(m!==Ye)throw new y("user","The installed Arcanist version does not match this setup command.",{hint:`Run npm install --global ${u}, then run setup again.`})}let p=l?c:Mp(c,"bin");try{await TA(Mp(p,l?"arcanist.cmd":"arcanist"),EA.X_OK)}catch{throw new y("user","Arcanist is installed, but npm did not create an executable command.",{hint:`Run npm install --global ${u} --bin-links, then run setup again.`})}if(!((l?process.env.Path??process.env.PATH:process.env.PATH)??"").split(PA).some(_=>l?xa(_).toLowerCase()===xa(p).toLowerCase():xa(_)===xa(p)))throw new y("user","Arcanist is installed, but its directory is not on PATH.",{hint:l?`Add ${p} to your user PATH, open a new terminal, then run arcanist onboard.`:`Run export PATH=${pt(p)}:"$PATH", add it to your shell profile, then run arcanist onboard.`});!o.json&&!o.quiet&&process.stderr.write(`Arcanist is installed. After setup, run arcanist review.
134
+ `),await ma(e,t,r)}async function By(e,t,r){let{config:o}=Y(r,t),n=CA(t.last),i=await R(o,P("/api/sessions/:sessionId/export",{sessionId:e})),a=n==null?i:OA(i,n,{includeBoundaryEvent:!Se(r,t)});D(r,t,a,s=>console.log(Ry(s)))}function CA(e){if(e===void 0)return null;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new y("user","--last must be a positive integer.");return t}function OA(e,t,r){let o=Math.max(0,e.events.length-t),n=NA(e.events,o),i=e.events.slice(o),a=r.includeBoundaryEvent&&n!==null&&n<o?[e.events[n],...i]:i,s=DA(a);if(n!==null){let c=Br(e.events[n]);c&&s.add(c)}let u=e.prompts.filter(c=>s.has(c.id));return{...e,prompts:u,events:a}}function NA(e,t){for(let r=t;r>=0;r--){let o=e[r];if(o&&An(o)==="prompt_processing")return r}return null}function DA(e){let t=new Set;for(let r of e){let o=Br(r);o&&t.add(o)}return t}function Vy(){let e=new zA().name("arcanist").description("Arcanist CLI").version(Ye).option("--json","Output machine-readable JSON").option("--quiet","Suppress non-essential stderr output").option("--api-url <url>","Override API URL. Prefer ARCANIST_API_URL for persistent use").option("--token <token>","Override API token. Prefer ARCANIST_TOKEN because flags can be visible in shell history and process lists").option("--no-color","Disable color output").configureHelp({showGlobalOptions:!0}).addHelpCommand(!1).exitOverride().addHelpText("after",`
135
135
  Examples:
136
136
  arcanist auth login --token-stdin
137
137
  arcanist sessions list --json
@@ -188,7 +188,7 @@ Examples:
188
188
  JSON: {review, requestStatus} preserves the result and status-batch envelopes, including unavailableRequestIds.
189
189
  A successful read exits 0 for active reviews and blocking findings. This command starts no model run.
190
190
  For local requests use arcanist review --request <id> --no-wait --json.
191
- `).action((s,u,c)=>V_(s,u,c)),e.command("review").description("Review your local commits before you open a pull request").argument("[pr-url]","Review this GitHub pull request instead").option("--base <ref>","Compare against this ref (default: the default branch on origin)").option("--include <path>","Upload this held-back path (a secret-looking or git-ignored file); repeat for more",(s,u=[])=>[...u,s]).option("--request <id>","Get the result of a review that is already running or finished").option("--poll-interval <ms>","Polling interval in milliseconds while waiting (default 10000)").option("--wait","With a pull request URL: wait for the result").option("--no-wait","Local review: start or check a review and return at once instead of waiting").addOption(new zA("--sandbox-runtime <runtime>","Force the sandbox runtime: modal or e2b").hideHelp()).addHelpText("after",`
191
+ `).action((s,u,c)=>V_(s,u,c)),e.command("review").description("Review your local commits before you open a pull request").argument("[pr-url]","Review this GitHub pull request instead").option("--base <ref>","Compare against this ref (default: the default branch on origin)").option("--include <path>","Upload this held-back path (a secret-looking or git-ignored file); repeat for more",(s,u=[])=>[...u,s]).option("--request <id>","Get the result of a review that is already running or finished").option("--poll-interval <ms>","Polling interval in milliseconds while waiting (default 10000)").option("--wait","With a pull request URL: wait for the result").option("--no-wait","Local review: start or check a review and return at once instead of waiting").addOption(new UA("--sandbox-runtime <runtime>","Force the sandbox runtime: modal or e2b").hideHelp()).addHelpText("after",`
192
192
  Examples:
193
193
  arcanist review
194
194
  arcanist review --base origin/release --json
@@ -236,7 +236,7 @@ Examples:
236
236
 
237
237
  JSON:
238
238
  JSON mode without --follow returns one JSON object from /events/history: {events: [...], ...}; canonical events carry phase.
239
- --follow --json emits NDJSON, one {sequence, type, data} object per line, until a terminal phase: ${LA(Pn)}.
239
+ --follow --json emits NDJSON, one {sequence, type, data} object per line, until a terminal phase: ${jA(Pn)}.
240
240
  --timeout bounds follow; 0 or omitted means unbounded. Process exit is a terminal phase, not session_idle.
241
241
  Actionable follow types are NDJSON signals, not process-exit conditions: pr_created/pr_updated use data.prUrl; question uses data.question; prompt_completed, prompt_failed, and session_idle do not exit the process.
242
242
  `).action((s,u,c)=>Fy(s,u,c)),r.command("transcript").description("Render a session transcript").argument("<session-id>","Session ID").option("--last <n>","Render only the last n transcript entries").addHelpText("after",`
@@ -298,7 +298,7 @@ review doc, and its first build is scheduled by the server. With --create, --dry
298
298
  JSON:
299
299
  JSON mode returns {environmentId, name, changedFields, applied, configurationGeneration: {before, after?}, rebuildScheduled?}.
300
300
  A create returns {environmentId, name, created, applied, configurationGeneration: {after}, buildScheduled}.
301
- `).action((s,u,c,l)=>Wh(s,u,c,l)),e.command("help").description("Show help for a command; with --json, print its command tree as JSON").argument("[path...]","Command path to explain").action((s,u,c)=>{let l=jA(e,s);if(Se(c,u)){Ve(Vp(l));return}l.help({error:!1})}),{program:e,auth:t,reviews:o,environments:a}}async function Gy(e,t=r=>r){let r="";e.hook("preAction",(o,n)=>{let i=[];for(let a=n;a?.parent;a=a.parent)i.unshift(a.name());r=i.join(" ")});try{await e.parseAsync(process.argv)}catch(o){UA(o)&&process.exit(0),Ia(o,"commander.help")&&process.exit(1),o instanceof y&&o.exitCode===vt&&MA();let n=t(Qp(o),r);e.opts().json?process.stderr.write(`${qr(n)}
301
+ `).action((s,u,c,l)=>Wh(s,u,c,l)),e.command("help").description("Show help for a command; with --json, print its command tree as JSON").argument("[path...]","Command path to explain").action((s,u,c)=>{let l=MA(e,s);if(Se(c,u)){Ve(Vp(l));return}l.help({error:!1})}),{program:e,auth:t,reviews:o,environments:a}}async function Gy(e,t=r=>r){let r="";e.hook("preAction",(o,n)=>{let i=[];for(let a=n;a?.parent;a=a.parent)i.unshift(a.name());r=i.join(" ")});try{await e.parseAsync(process.argv)}catch(o){LA(o)&&process.exit(0),Ia(o,"commander.help")&&process.exit(1),o instanceof y&&o.exitCode===vt&&FA();let n=t(Qp(o),r);e.opts().json?process.stderr.write(`${qr(n)}
302
302
  `):(process.stderr.write(`Error: ${n.message}
303
303
  `),n.hint&&process.stderr.write(`Hint: ${n.hint}
304
- `)),process.exit(n.exitCode)}}function Ia(e,t){return!!e&&typeof e=="object"&&"code"in e&&e.code===t}function UA(e){return Ia(e,"commander.helpDisplayed")||Ia(e,"commander.version")?!0:Ia(e,"commander.help")&&"exitCode"in e&&e.exitCode===0}function LA(e){let t=e.at(-1);return t===void 0?"":e.length===1?t:`${e.slice(0,-1).join(", ")}, or ${t}`}function jA(e,t){let r=e;for(let o of t){let n=r.commands.find(i=>i.name()===o||i.aliases().includes(o));if(!n)throw new y("user",`Unknown help topic: ${t.join(" ")}`);r=n}return r}function MA(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h")}var{program:FA}=Vy();Gy(FA);
304
+ `)),process.exit(n.exitCode)}}function Ia(e,t){return!!e&&typeof e=="object"&&"code"in e&&e.code===t}function LA(e){return Ia(e,"commander.helpDisplayed")||Ia(e,"commander.version")?!0:Ia(e,"commander.help")&&"exitCode"in e&&e.exitCode===0}function jA(e){let t=e.at(-1);return t===void 0?"":e.length===1?t:`${e.slice(0,-1).join(", ")}, or ${t}`}function MA(e,t){let r=e;for(let o of t){let n=r.commands.find(i=>i.name()===o||i.aliases().includes(o));if(!n)throw new y("user",`Unknown help topic: ${t.join(" ")}`);r=n}return r}function FA(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h")}var{program:ZA}=Vy();Gy(ZA);