@tryarcanist/cli 0.1.500 → 0.1.502

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 +22 -22
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
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 ob=Object.defineProperty;var Ge=(e,t)=>{for(var r in t)ob(e,r,{get:t[r],enumerable:!0})};import{Command as dP,Option as pP}from"commander";var qp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Cn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],ab=new Set(Cn),yP=new Set(Cn.filter(e=>e!=="completed")),bP=Cn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Hp(e,t){return ab.has(e)}function Wp(e){let t=e.createHelp().visibleGlobalOptions(e).map(Jp);return{...Kp(e),...t.length>0?{globalOptions:t}:{}}}function Kp(e){let t=sb(e);return{path:Oa(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(Jp),...t?{notes:t}:{},subcommands:e.commands.map(Kp)}}function Jp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Oa(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function sb(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Yb,mkdirSync as Xb,writeFileSync as Qb}from"node:fs";import{basename as ew,join as fm,resolve as tw}from"node:path";var ub="en-US";function Yp(e,t){let r=new Intl.DateTimeFormat(ub,{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 IP=Date.parse("2026-09-26T15:00:00Z"),kP=60*1e3,EP=5*6e4;var TP=6*36e5;var AP=2*6e4,PP=5*6e4,RP=20*6e4,CP=5*6e4,OP=10*1e3,NP=60*1e3,DP=5*6e4;var zP=48*36e5,UP=6*36e5,LP=7*864e5,jP=5*6e4;var MP=168*36e5,FP=30*864e5,ZP=168*36e5,BP=30*1e3,VP=90*1e3;var GP=6*36e5,qP=30*6e4,cb=15*6e4,lb=90*6e4,HP=15*6e4,WP=cb+2*lb,KP=2*6e4,JP=14*864e5,YP=30*864e5;var XP=30*6e4;var QP=15*6e4;var eR=10*1e3,tR=15*1e3;var nR=60*6e4,rR=5*6e4,iR=2*6e4;var oR=3*6e4,aR=10*6e4,sR=10*6e4,uR=24*36e5,cR=24*36e5,lR=2*6e4;function Kr(e){return new Promise(t=>setTimeout(t,e))}var db=/\/+$/;function tt(e){return e.replace(db,"")}var Xp="Setup and reviews are paused for this workspace. Contact team@tryarcanist.com to resume them.";function Qp(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 Na(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=Qp(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 pb=/^error: /,mb=/^\((.*)\)$/,Ne=130,Da=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??em(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},Ft=class extends y{},ce=class extends y{status;body;constructor(t,r,o,n){let i=tm(t),a=Na(r);super(i,gb(t,r,a),{exitCode:fb(t),hint:hb(t,n,a),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 em(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function tm(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function fb(e){return em(tm(e))}function gb(e,t,r=Na(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function hb(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&r?.message===Xp)){if(e===403&&r?.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 t==="repo"?"Check accessible repositories with `arcanist repos list`.":t==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&r?.repository){if(r.serverCode==="environment_required")return`Run \`arcanist environments prepare ${r.repository} --wait\`, then retry the review.`;if(r.serverCode==="environment_preparing"||r.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${r.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 vb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function _b(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(pb,"").split(`
5
- `);return new y("user",t,{hint:r?r.replace(mb,"$1"):vb})}function nm(e){if(e instanceof y)return e;if(e instanceof Error){let t=_b(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Jr(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 rm={name:"@tryarcanist/cli",version:"0.1.500",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","playwright-core":"^1.65.0","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var nt=`${rm.version}`;var bb=/^\d+$/,wb=`arcanist-cli/${nt}`,$b=3e4,Sb=1e3,xb=6e5,Yr="ARCANIST_HTTP_TIMEOUT_MS";function Ib(e=process.env){let t=e[Yr];if(!t)return $b;if(!bb.test(t))throw new y("user",`${Yr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<Sb||r>xb)throw new y("user",`${Yr} must be between 1000 and 600000 milliseconds.`);return r}function za(e){return e instanceof DOMException&&e.name==="AbortError"}function kb(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 Ua(e){return new Ft("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Yr} for slow links, or check the API connection.`})}function Eb(e){let t=Ib();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 La(e,t,r,o){let{fetchInit:n,timeoutMs:i}=Eb(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",wb),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${tt(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw za(l)?Ua(i):new Ft("server",`Network error: could not reach ${tt(e.apiUrl)} (${kb(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(za(d))throw Ua(i);return""});throw new ce(c.status,l,c.headers.get("x-request-id")??void 0,Tb(t))}return await o(c)}catch(u){throw u instanceof y?u:za(u)?Ua(i):u instanceof TypeError?new Ft("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 Tb(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function P(e,t,r){return La(e,t,r,o=>o.json())}async function im(e,t,r){return La(e,t,r,o=>o.text())}async function om(e,t,r){return La(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}var Ab=/:([A-Za-z]+)/g,U={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"},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"},answerEnvironmentSecretRequest:{method:"POST",pattern:"/api/environments/:id/secret-requests/:requestId"},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"},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"},getEnvironmentBrowserState:{method:"GET",pattern:"/api/environments/:id/browser-state"},setEnvironmentBrowserState:{method:"PUT",pattern:"/api/environments/:id/browser-state"},deleteEnvironmentBrowserState:{method:"DELETE",pattern:"/api/environments/:id/browser-state"}};function A(e,t={}){return am(e,t)}function am(e,t){return e.replace(Ab,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var MR=[{...U.getInferenceApiKeys,command:"inference keys list"},{...U.createInferenceApiKey,command:"inference keys create"},{...U.revokeInferenceApiKey,command:"inference keys revoke"},{...U.getInferenceProviders,command:"inference providers list"},{...U.setInferenceKey,command:"inference providers set-key"},{...U.removeInferenceKey,command:"inference providers remove-key"},{...U.setInferenceFallback,command:"inference providers fallback"},{...U.getInferenceUsage,command:"inference usage"},{...U.getCurrentUser,command:"auth whoami"},{...U.exchangeCliLogin,command:"auth login",public:!0},{...U.getGithubInstallation,command:"onboard"},{...U.answerOnboardingQuestion,command:"environments answer"},{...U.answerEnvironmentSecretRequest,command:"environments secrets"},{...U.listRepositories,command:"repos list"},{...U.listSessions,command:"sessions list"},{...U.getSession,command:"sessions get"},{...U.getSessionView,command:"sessions view"},{...U.getSessionPrompts,command:"sessions events --follow"},{...U.getSessionEvents,command:"sessions events --follow"},{...U.getSessionEventHistory,command:"sessions events"},{...U.exportSession,command:"sessions transcript"},{...U.listSessionArtifacts,command:"sessions artifacts"},{...U.viewSessionArtifact,command:"sessions artifacts get"},{...U.createReview,command:"review <pr-url>"},{...U.getReviewRequest,command:"review <pr-url>"},{...U.getReviewRequest,command:"reviews get"},{...U.getReviewRequestStatuses,command:"reviews get"},{...U.createLocalReview,command:"review"},{...U.getLocalReview,command:"review --request"},{...U.getRepositoryOnboarding,command:"environments status"},{...U.prepareRepository,command:"environments prepare"},{...U.retryRepositoryOnboarding,command:"environments retry"},{...U.listEnvironments,command:"environments login"},{...U.getEnvironment,command:"environments login"},{...U.updateEnvironment,command:"environments login --validate-path"},{...U.listEnvironments,command:"environments export"},{...U.getEnvironment,command:"environments export"},{...U.listEnvironments,command:"environments import"},{...U.getEnvironment,command:"environments import"},{...U.updateEnvironment,command:"environments import"},{...U.createEnvironment,command:"environments import --create"},{...U.getEnvironmentBrowserState,command:"environments login"},{...U.setEnvironmentBrowserState,command:"environments login"},{...U.deleteEnvironmentBrowserState,command:"environments login --clear"}];import{createHash as um}from"node:crypto";import{existsSync as On,mkdirSync as Nb,readFileSync as ja,statSync as Db}from"node:fs";import{homedir as zb}from"node:os";import{dirname as cm,join as yt,resolve as Ub}from"node:path";import{randomUUID as Pb}from"node:crypto";import{renameSync as Rb,rmSync as Cb,writeFileSync as Ob}from"node:fs";function _t(e,t){let r=`${e}.${Pb()}.tmp`;try{Ob(r,JSON.stringify(t,null,2)+`
4
+ var ob=Object.defineProperty;var Ge=(e,t)=>{for(var r in t)ob(e,r,{get:t[r],enumerable:!0})};import{Command as pP,Option as mP}from"commander";var qp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Cn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],ab=new Set(Cn),bP=new Set(Cn.filter(e=>e!=="completed")),wP=Cn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Hp(e,t){return ab.has(e)}function Wp(e){let t=e.createHelp().visibleGlobalOptions(e).map(Jp);return{...Kp(e),...t.length>0?{globalOptions:t}:{}}}function Kp(e){let t=sb(e);return{path:Oa(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(Jp),...t?{notes:t}:{},subcommands:e.commands.map(Kp)}}function Jp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Oa(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function sb(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Yb,mkdirSync as Xb,writeFileSync as Qb}from"node:fs";import{basename as ew,join as fm,resolve as tw}from"node:path";var ub="en-US";function Yp(e,t){let r=new Intl.DateTimeFormat(ub,{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 kP=Date.parse("2026-09-26T15:00:00Z"),EP=60*1e3,TP=5*6e4;var AP=6*36e5;var PP=2*6e4,RP=5*6e4,CP=20*6e4,OP=5*6e4,NP=10*1e3,DP=60*1e3,zP=5*6e4;var UP=48*36e5,LP=6*36e5,jP=7*864e5,MP=5*6e4;var FP=168*36e5,ZP=30*864e5,BP=168*36e5,VP=30*1e3,GP=90*1e3;var qP=6*36e5,HP=30*6e4,cb=15*6e4,lb=90*6e4,WP=15*6e4,KP=cb+2*lb,JP=2*6e4,YP=14*864e5,XP=30*864e5;var QP=30*6e4;var eR=15*6e4;var tR=10*1e3,nR=15*1e3;var rR=60*6e4,iR=5*6e4,oR=2*6e4;var aR=3*6e4,sR=10*6e4,uR=10*6e4,cR=24*36e5,lR=24*36e5,dR=2*6e4;function Kr(e){return new Promise(t=>setTimeout(t,e))}var db=/\/+$/;function tt(e){return e.replace(db,"")}var Xp="Setup and reviews are paused for this workspace. Contact team@tryarcanist.com to resume them.";function Qp(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 Na(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=Qp(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 pb=/^error: /,mb=/^\((.*)\)$/,Ne=130,Da=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??em(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},Ft=class extends y{},ce=class extends y{status;body;constructor(t,r,o,n){let i=tm(t),a=Na(r);super(i,gb(t,r,a),{exitCode:fb(t),hint:hb(t,n,a),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 em(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function tm(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function fb(e){return em(tm(e))}function gb(e,t,r=Na(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function hb(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&r?.message===Xp)){if(e===403&&r?.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 t==="repo"?"Check accessible repositories with `arcanist repos list`.":t==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&r?.repository){if(r.serverCode==="environment_required")return`Run \`arcanist environments prepare ${r.repository} --wait\`, then retry the review.`;if(r.serverCode==="environment_preparing"||r.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${r.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 vb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function _b(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(pb,"").split(`
5
+ `);return new y("user",t,{hint:r?r.replace(mb,"$1"):vb})}function nm(e){if(e instanceof y)return e;if(e instanceof Error){let t=_b(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Jr(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 rm={name:"@tryarcanist/cli",version:"0.1.502",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","playwright-core":"^1.65.0","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var nt=`${rm.version}`;var bb=/^\d+$/,wb=`arcanist-cli/${nt}`,$b=3e4,Sb=1e3,xb=6e5,Yr="ARCANIST_HTTP_TIMEOUT_MS";function Ib(e=process.env){let t=e[Yr];if(!t)return $b;if(!bb.test(t))throw new y("user",`${Yr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<Sb||r>xb)throw new y("user",`${Yr} must be between 1000 and 600000 milliseconds.`);return r}function za(e){return e instanceof DOMException&&e.name==="AbortError"}function kb(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 Ua(e){return new Ft("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Yr} for slow links, or check the API connection.`})}function Eb(e){let t=Ib();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 La(e,t,r,o){let{fetchInit:n,timeoutMs:i}=Eb(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",wb),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${tt(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw za(l)?Ua(i):new Ft("server",`Network error: could not reach ${tt(e.apiUrl)} (${kb(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(za(d))throw Ua(i);return""});throw new ce(c.status,l,c.headers.get("x-request-id")??void 0,Tb(t))}return await o(c)}catch(u){throw u instanceof y?u:za(u)?Ua(i):u instanceof TypeError?new Ft("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 Tb(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function P(e,t,r){return La(e,t,r,o=>o.json())}async function im(e,t,r){return La(e,t,r,o=>o.text())}async function om(e,t,r){return La(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}var Ab=/:([A-Za-z]+)/g,U={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"},getInferenceTraceSettings:{method:"GET",pattern:"/api/inference/trace-settings"},setInferenceTraceSettings:{method:"PUT",pattern:"/api/inference/trace-settings"},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"},answerEnvironmentSecretRequest:{method:"POST",pattern:"/api/environments/:id/secret-requests/:requestId"},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"},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"},getEnvironmentBrowserState:{method:"GET",pattern:"/api/environments/:id/browser-state"},setEnvironmentBrowserState:{method:"PUT",pattern:"/api/environments/:id/browser-state"},deleteEnvironmentBrowserState:{method:"DELETE",pattern:"/api/environments/:id/browser-state"}};function A(e,t={}){return am(e,t)}function am(e,t){return e.replace(Ab,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var FR=[{...U.getInferenceApiKeys,command:"inference keys list"},{...U.createInferenceApiKey,command:"inference keys create"},{...U.revokeInferenceApiKey,command:"inference keys revoke"},{...U.getInferenceProviders,command:"inference providers list"},{...U.setInferenceKey,command:"inference providers set-key"},{...U.removeInferenceKey,command:"inference providers remove-key"},{...U.setInferenceFallback,command:"inference providers fallback"},{...U.getInferenceUsage,command:"inference usage"},{...U.getCurrentUser,command:"auth whoami"},{...U.exchangeCliLogin,command:"auth login",public:!0},{...U.getGithubInstallation,command:"onboard"},{...U.answerOnboardingQuestion,command:"environments answer"},{...U.answerEnvironmentSecretRequest,command:"environments secrets"},{...U.listRepositories,command:"repos list"},{...U.listSessions,command:"sessions list"},{...U.getSession,command:"sessions get"},{...U.getSessionView,command:"sessions view"},{...U.getSessionPrompts,command:"sessions events --follow"},{...U.getSessionEvents,command:"sessions events --follow"},{...U.getSessionEventHistory,command:"sessions events"},{...U.exportSession,command:"sessions transcript"},{...U.listSessionArtifacts,command:"sessions artifacts"},{...U.viewSessionArtifact,command:"sessions artifacts get"},{...U.createReview,command:"review <pr-url>"},{...U.getReviewRequest,command:"review <pr-url>"},{...U.getReviewRequest,command:"reviews get"},{...U.getReviewRequestStatuses,command:"reviews get"},{...U.createLocalReview,command:"review"},{...U.getLocalReview,command:"review --request"},{...U.getRepositoryOnboarding,command:"environments status"},{...U.prepareRepository,command:"environments prepare"},{...U.retryRepositoryOnboarding,command:"environments retry"},{...U.listEnvironments,command:"environments login"},{...U.getEnvironment,command:"environments login"},{...U.updateEnvironment,command:"environments login --validate-path"},{...U.listEnvironments,command:"environments export"},{...U.getEnvironment,command:"environments export"},{...U.listEnvironments,command:"environments import"},{...U.getEnvironment,command:"environments import"},{...U.updateEnvironment,command:"environments import"},{...U.createEnvironment,command:"environments import --create"},{...U.getEnvironmentBrowserState,command:"environments login"},{...U.setEnvironmentBrowserState,command:"environments login"},{...U.deleteEnvironmentBrowserState,command:"environments login --clear"}];import{createHash as um}from"node:crypto";import{existsSync as On,mkdirSync as Nb,readFileSync as ja,statSync as Db}from"node:fs";import{homedir as zb}from"node:os";import{dirname as cm,join as yt,resolve as Ub}from"node:path";import{randomUUID as Pb}from"node:crypto";import{renameSync as Rb,rmSync as Cb,writeFileSync as Ob}from"node:fs";function _t(e,t){let r=`${e}.${Pb()}.tmp`;try{Ob(r,JSON.stringify(t,null,2)+`
6
6
  `,{mode:384,flag:"wx"}),Rb(r,e)}finally{Cb(r,{force:!0})}}var Lb=/\r?\n/,jb=/^\[|\]$/g,lm=yt(zb(),".arcanist"),dm=yt(lm,"config.json"),rt=".arcanist-cli.json",Mb="https://app.tryarcanist.com";function Ma(){try{return JSON.parse(ja(dm,"utf-8"))}catch{return null}}function Nn(e={}){let t=Fb(e);if(t)return sm(t);let r=Fa(),o=Za(e,r!==null),n=Ma(),i=o?.apiUrl??r?.apiUrl??n?.apiUrl,a=r&&n?.apiUrl===r.apiUrl&&n.token&&n.supersededProjectTokenHash===um("sha256").update(r.token).digest("hex")?n.token:r?.token,s=o?.token??a??n?.token;if(!i||!s)return null;let u=sm({apiUrl:i,token:s});return r&&!o&&!e.json&&process.stderr.write(`using ${rt} -> ${u.apiUrl}
7
7
  `),u}function Xr(e,t){let r=ei(e.apiUrl);if(r)throw new y("user",r);Nb(lm,{recursive:!0,mode:448});let o=tt(e.apiUrl),n=Ma(),i=t?um("sha256").update(t).digest("hex"):n?.apiUrl===o?n.supersededProjectTokenHash:void 0,a={...e,apiUrl:o,...i?{supersededProjectTokenHash:i}:{}};_t(dm,a)}function _e(e){let t=Nn(e);if(!t)throw new y("auth","Not logged in.",{hint:"Run `arcanist auth login` or set `ARCANIST_TOKEN`."});return t}function Qr(e){let t=e??process.env.ARCANIST_API_URL??Ma()?.apiUrl??Mb,r=ei(t);if(r)throw new y("user",r);return tt(t)}function Fa(e=process.cwd()){let t=Zb(e);if(!t)return null;let r=e;for(;;){let o=yt(r,rt);if(On(o))return Gb(o);if(r===t)return null;let n=cm(r);if(n===r)return null;r=n}}function ei(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:"&&!pm(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",`${rt} 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 Fb(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 sm(e){let t=ei(e.apiUrl);if(t)throw new y("user",t);return{apiUrl:tt(e.apiUrl),token:e.token}}function Zb(e){let t=e;for(;;){if(Bb(t))return t;let r=cm(t);if(r===t)return null;t=r}}function Bb(e){let t=yt(e,".git");if(!On(t))return!1;try{let r=Db(t);if(r.isDirectory())return On(yt(t,"HEAD"))&&On(yt(t,"config"));if(!r.isFile())return!1;let o=Vb(t);return o?On(yt(Ub(e,o),"HEAD")):!1}catch{return!1}}function Vb(e){let t=ja(e,"utf-8").split(Lb).find(o=>o.startsWith("gitdir:"));return t&&t.slice(7).trim()||null}function Gb(e){let t;try{t=JSON.parse(ja(e,"utf-8"))}catch{throw new y("user",`${rt} is not valid JSON.`)}if(!t||typeof t!="object")throw new y("user",`${rt} 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",`${rt} must contain both apiUrl and token.`);let o;try{o=new URL(r.apiUrl)}catch{throw new y("user",`${rt} apiUrl must be a valid URL.`)}if(!pm(o))throw new y("user",`${rt} apiUrl must be a loopback host.`);let n=ei(r.apiUrl);if(n)throw new y("user",n);return{apiUrl:tt(r.apiUrl),token:r.token}}function pm(e){let t=e.hostname.replace(jb,"");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 Ie(e,t={}){return ee(e,t).json===!0}function qe(e){process.stdout.write(`${JSON.stringify(e)}
8
8
  `)}function O(e,t,r,o){if(Ie(e,t)){qe(r);return}o(r)}function G(e,t={}){let r=ee(e,t);return{runtime:r,config:_e(r)}}async function qb(){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 bt(){return(await qb()).trim()}function mm(e){(e.noColor===!0||!process.stdout.isTTY)&&(process.env.NO_COLOR="1")}var Hb=/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,Wb=/\u001b\[[0-?]*[ -\/]*[@-~]/g,Kb=/[\u0000-\u001f\u007f]/g,Jb=/\r?\n/;function N(e){return e.replace(Hb,"").replace(Wb,"").replace(Kb,"")}function De(e){return e.split(Jb).map(N).join(`
@@ -67,8 +67,8 @@ ${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 D(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 Tt(e,t){return e.definite=!1,D(e,t)}function R(e){return`v${e.varCounter++}`}function Ix(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return ge;let o=r;return o.issues.length===0?o.value:ge}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 Y(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,kx(e,t,r,o)}}function kx(e,t,r,o){t.definite=!1;let n=D(t,r),i=D(t,Ix),a=R(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var Ex=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Tx(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&&!Ex.has(s.check))throw new Z('check with a custom "when" condition');switch(s.check){case"greater_than":Ax(e,t,s,i);break;case"less_than":Px(e,t,s,i);break;case"multiple_of":Rx(e,t,s,i);break;case"number_format":Vg(e,s,i);break;case"min_length":{let u=ut(s.minimum,"min_length"),c=Pc(e,t,i,`${i}.length >= ${u} && ${i}.length < ${s.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{let u=ut(s.maximum,"max_length"),c=Pc(e,t,i,`${i}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{let u=ut(s.length,"length_equals"),c=Pc(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 < ${ut(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${ut(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${ut(s.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Gg(e,t,s,i);break;case"custom":i=Ux(e,t,a,i);break;case"bigint_format":Cx(e,s,i);break;case"mime_type":Ox(e,t,s,i);break;case"property":Dx(e,t,s,i);break;case"properties":Nx(e,t,s,i);break;case"overwrite":{let u=R(t);zx(e,t,a,i,u),i=u;break}default:throw new Z(`check type ${s.check}`)}}return i}function Pc(e,t,r,o){let n=D(t,St),i=R(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function ut(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Z(`${t} bound of type ${typeof e}`);return`${e}`}function Bg(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 D(e,t)}throw new Z(`comparison check bound of type ${typeof t}`)}function Ax(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${Bg(t,r.value)}) return INVALID;`)}function Px(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${Bg(t,r.value)}) return INVALID;`)}function Rx(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=D(t,Mn);e.write(`if (${n}(${o}, ${ut(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Vg(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 Cx(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 Ox(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=D(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Nx(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"?D(t,i):me(i),s=R(t);e.write(`const ${s} = ${o}[${a}];`),le(e,t,n[i],s,!1)}}function Dx(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Y(e,t,r.schema,n)}function zx(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new Z("overwrite check without a transform function");if(At(i))throw new Ue("z.compile: async overwrite transforms are not supported");let a=D(t,i);e.write(`const ${n} = ${a}(${o});`)}function Rc(){throw new we}function Nc(e){this.issues.push(e)}function Ux(e,t,r,o){let n=r._zod.def;if(n.fn){if(At(n.fn))throw new Ue("z.compile: async .refine() predicates are not supported");let i=Tt(t,n.fn),a=D(t,Rc),s=R(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(At(r._zod.check))throw new Ue("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,s=Tt(t,c=>{let l={value:c,issues:[],addIssue:Nc};return i(l)instanceof Promise&&Rc(),l.issues.length===0?l.value:ge}),u=R(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 Lx=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 Gg(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let c=D(t,ar);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="base64url"){let c=D(t,Ni);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="jwt"){let c=D(t,Ui),l=D(t,r.alg??null);return e.write(`if (!${c}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let c=D(t,or);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="cidrv6"){let c=D(t,Ci);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="credit_card"){let c=D(t,Di);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(i==="iban"){let c=D(t,zi);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=D(t,Ai),l=D(t,r),d=R(t),m=R(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 _=D(t,Pi);e.write(`if (!${_}(${m}, ${l}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let _=D(t,Ri);e.write(`if (!${_}(${m}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=R(t),g=a.normalize?`${m}.href`:`${D(t,ir)}(${d})`;return e.write(`const ${p} = ${g};`),p}let s=r.fn;if(s){if(At(s))throw new Z(`async string format ${i}`);let c=D(t,s);return e.write(`if (!${c}(${o})) return INVALID;`),o}if(Lx.has(i)&&r.pattern){let c=D(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(${me(r.includes)})) return INVALID;`);break;case"starts_with":{let c=r.prefix;e.write(`if (${o}.slice(0, ${c.length}) !== ${me(c)}) return INVALID;`);break}case"ends_with":{let c=r.suffix;e.write(`if (${o}.slice(-${c.length}) !== ${me(c)}) return INVALID;`);break}default:throw new Z(`string format ${u}`)}return o}function Y(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=jx(e,t,r,o,s);break;case"number":u=Mx(e,r,o);break;case"boolean":u=Fx(e,o);break;case"bigint":u=Zx(e,r,o);break;case"symbol":u=Bx(e,o);break;case"undefined":u=Vx(e,o);break;case"null":u=Gx(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=qx(e,o);break;case"nan":u=Hx(e,o);break;case"date":u=Wx(e,o);break;case"object":u=Kx(e,t,r,o,s);break;case"optional":u=Jx(e,t,r,o,s);break;case"nullable":u=Qx(e,t,r,o,s);break;case"array":u=eI(e,t,r,o,s);break;case"literal":u=tI(e,t,r,o);break;case"enum":u=nI(e,t,r,o);break;case"readonly":{let c=Mg(e,t,r,o),l=R(t);e.write(`const ${l} = Object.freeze(${c});`),u=l;break}case"success":Mg(e,t,r,o),u="true";break;case"default":case"prefault":u=rI(e,t,r,o);break;case"nonoptional":u=iI(e,t,r,o);break;case"tuple":u=oI(e,t,r,o);break;case"union":u=aI(e,t,r,o);break;case"intersection":u=cI(e,t,r,o);break;case"record":u=lI(e,t,r,o);break;case"map":u=pI(e,t,r,o);break;case"set":u=mI(e,t,r,o);break;case"file":u=fI(e,o);break;case"template_literal":u=gI(e,t,r,o);break;case"lazy":u=hI(e,t,r,o);break;case"pipe":u=vI(e,t,r,o);break;case"custom":u=_I(e,t,r,o);break;case"transform":u=wI(e,t,r,o);break;case"catch":u=bI(e,t,r,o);break;default:throw new Z(`schema type ${a}`)}return u===null?null:Tx(e,t,r,u)}function jx(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:Gg(e,t,i,o,n)}function Mx(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&&Vg(e,{format:o.format},r),r}function Fx(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function Zx(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 Bx(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function Vx(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Gx(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function qx(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Hx(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function Wx(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function Kx(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=x=>typeof x=="symbol"?D(t,x):me(x),d=x=>typeof x=="symbol"?`[${l(x)}]`:me(x),m=a;if(s.includes("__proto__"))throw new Z('object shape key "__proto__"');let p=new Map;for(let x of c){let E=m[x],C=l(x),F=R(t);if(e.write(`const ${F} = ${o}[${C}];`),E._zod.optin!==void 0){let B=R(t);e.write(`let ${B} = (() => {`),e.indented(Q=>{let ne=le(Q,t,E,F);Q.write(`return ${ne};`)}),e.write("})();"),E._zod.optout==="optional"?(e.write(`if (${B} === INVALID) {`),e.indented(Q=>{Q.write(`if (${C} in ${o}) return INVALID;`),Q.write(`${B} = undefined;`)}),e.write("}")):e.write(`if (${B} === INVALID) return INVALID;`),p.set(x,B)}else{Xx(E)&&e.write(`if (!(${C} in ${o})) return INVALID;`);let B=le(e,t,E,F,n);B!==null&&p.set(x,B)}}let g=i.catchall,_="none";if(g){let x=g._zod.def.type;if(x==="never"){let E=s.map(C=>`k !== ${me(C)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(C=>{C.write(`if (${E}) return INVALID;`)}),e.write("}")}else(x==="unknown"||x==="any")&&!g._zod.def.checks?.length?_="passthrough":_="schema"}let I=R(t),b=c.some(x=>jg(m[x])||Cc(m[x]));if(!n){if(_==="schema"){let x=s.length>0?D(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(E=>{E.write('if (k === "__proto__") continue;'),x&&E.write(`if (${x}.has(k)) continue;`);let C=R(t);E.write(`const ${C} = ${o}[k];`),le(E,t,g,C,!1)}),e.write("}")}return null}if(b){e.write(`const ${I} = {};`);for(let x of c){let E=l(x),C=p.get(x);Cc(m[x])?e.write(`if (${E} in ${o}) ${I}[${E}] = ${C};`):jg(m[x])?e.write(`if (${C} !== undefined || ${E} in ${o}) ${I}[${E}] = ${C};`):e.write(`${I}[${E}] = ${C};`)}}else{let x=c.map(E=>`${d(E)}: ${p.get(E)}`).join(", ");e.write(`const ${I} = { ${x} };`)}if(_!=="none"){let x=s.length>0?D(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(E=>{if(E.write('if (k === "__proto__") continue;'),x&&E.write(`if (${x}.has(k)) continue;`),_==="passthrough")E.write(`${I}[k] = ${o}[k];`);else{let C=R(t);E.write(`const ${C} = ${o}[k];`);let F=le(E,t,g,C);E.write(`${I}[k] = ${F};`)}}),e.write("}")}return I}function Jx(e,t,r,o,n=!0){let i=r._zod.def;if(Yx(r))return Y(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let s=R(t),u=R(t);return e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(l=>{let d=Y(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=Y(c,t,i.innerType,o);c.write(`${s} = ${l};`)}),e.write("}"),s}let a=n?R(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function Yx(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function Xx(e){return e._zod.optin===void 0&&Et(e)}function Et(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?Et(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?Et(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Et):!0;case"intersection":return!t.left||!t.right?!0:Et(t.left)&&Et(t.right);case"pipe":return t.in?Et(t.in):!0;default:return!0}}function Cc(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function jg(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&rn(e)}function rn(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?rn(t.innerType):!0;case"union":return t.options?t.options.some(rn):!0;case"intersection":return!t.left||!t.right||rn(t.left)||rn(t.right);case"pipe":return t.out?rn(t.out):!0;default:return!0}}function Qx(e,t,r,o,n=!0){let i=r._zod.def,a=n?R(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function Dc(e,t,r){for(let[o,n]of Ht(t._zod.def.checks))e.write(`if (${r} > ${ut(o,n._zod.def.check)}) return INVALID;`)}function eI(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),Dc(e,r,`${o}.length`);let a=n?R(t):null,s=R(t),u=R(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 tI(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let s=D(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=D(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${me(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 nI(e,t,r,o){let n=r._zod.values;if(!n)throw new Z("enum schema without enumerated values");let i=D(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function Mg(e,t,r,o){let n=r._zod.def;return Y(e,t,n.innerType,o)}function rI(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 Y(e,t,n.innerType,o);let u=D(t,a),c=R(t);return e.write(`let ${c} = ${o};`),e.write(`if (${o} === undefined) ${c} = ${u}();`),Y(e,t,n.innerType,c)}let s=R(t);if(a){let u=D(t,a),c=D(t,Fn);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=Y(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=Y(u,t,n.innerType,o);u.write(`${s} = ${c};`)}),e.write("}");return s}function iI(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.innerType,o),a=R(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function oI(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=Fg(i,"optin"),u=Fg(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=R(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 g=R(t);p.write(`const ${g} = ${o}[${l}];`);let _=le(p,t,d,g);p.write(`${c}[${l}] = ${_};`)}),m.write("} else {"),m.indented(p=>{if(Cc(d)){p.write(`${c}.length = ${l};`);return}let g=R(t),_=R(t);p.write(`const ${g} = undefined;`),p.write(`const ${_} = (() => {`),p.indented(I=>{let b=le(I,t,d,g);I.write(`return ${b};`)}),p.write("})();"),p.write(`if (${_} === INVALID || ${_} === undefined) ${c}.length = ${l};`),p.write(`else ${c}[${l}] = ${_};`)}),m.write("}")}),e.write("}");else{let m=R(t);e.write(`const ${m} = ${o}[${l}];`);let p=le(e,t,d,m);e.write(`${c}[${l}] = ${p};`)}}if(a){let l=R(t),d=R(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 Fg(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 aI(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return sI(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 Y(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=D(t,u);return e.write(`if (!${c}.has(${o})) return INVALID;`),o}let s=R(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=Y(l,t,c,o);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function sI(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=R(t),i=R(t);e.write(`const ${n} = ${o}?.[${me(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=>uI(t,n,m)),d=a?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(m=>{let p=Y(m,t,u,o);m.write(`${i} = ${p};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function uI(e,t,r){if(typeof r=="string")return`${t} === ${me(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=D(e,r);return`${t} === ${o}`}throw new Z(`literal discriminator value ${String(r)}`)}function cI(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=D(t,en),u=R(t);return e.write(`const ${u} = ${s}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function lI(e,t,r,o){let n=r._zod.def,i=D(t,Pe);e.write(`if (!${i}(${o})) return INVALID;`);let a=R(t),s=R(t),u=R(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 I=typeof _=="number"?_.toString():_;if(I==="__proto__")throw new Z('record key "__proto__"');p.push(I);let b=D(t,_),x=Y(e,t,n.keyType,b),E=R(t);e.write(`const ${E} = ${o}[${dI(t,I)}];`);let C=le(e,t,n.valueType,E);e.write(`${a}[${x}] = ${C};`)}let g=D(t,new Set(p));return e.write(`for (const ${s} in ${o}) {`),e.indented(_=>{_.write(`if (${g}.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",g=to(n.keyType);g.definite===!1&&(t.definite=!1);let _=D(t,g),I=D(t,Je),b=R(t);return Zg(e,t,o,s,x=>{x.write(`let ${b} = ${_}(${s});`),x.write(`if (${b} === INVALID && typeof ${s} === "string" && ${I}.test(${s})) ${b} = ${_}(Number(${s}));`),p?x.write(`if (${b} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):x.write(`if (${b} === INVALID) return INVALID;`),x.write(`if (${b} === "__proto__") continue;`);let E=R(t);x.write(`const ${E} = ${o}[${s}];`);let C=le(x,t,n.valueType,E);x.write(`${a}[${b}] = ${C};`)}),a}return Zg(e,t,o,s,p=>{p.write(`const ${u} = ${o}[${s}];`);let g=le(p,t,n.valueType,u);p.write(`${a}[${s}] = ${g};`)},"return INVALID;"),a}function Zg(e,t,r,o,n,i){let a=D(t,Object.prototype.propertyIsEnumerable),s=R(t),u=R(t),c=R(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 dI(e,t){return typeof t=="string"?me(t):D(e,t)}function pI(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Dc(e,r,`${o}.size`);let i=R(t),a=R(t),s=R(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${s}] of ${o}) {`),e.indented(u=>{let c=Y(u,t,n.keyType,a),l=Y(u,t,n.valueType,s);u.write(`${i}.set(${c}, ${l});`)}),e.write("}"),i}function mI(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Dc(e,r,`${o}.size`);let i=R(t),a=R(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(s=>{let u=Y(s,t,n.valueType,a);s.write(`${i}.add(${u});`)}),e.write("}"),i}function fI(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function gI(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=D(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function hI(e,t,r,o){let n=r._zod.def,i=Tt(t,n.getter),a=D(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=R(t);return e.write(`const ${s} = ${a}.parser(${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function vI(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.in,o);if(n.transform){if(At(n.transform))throw new Ue("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Tt(t,l=>{let d={value:l,issues:[],addIssue:Nc},m=a(l,d);return m instanceof Promise?ge:d.issues.length===0?m:ge}),c=R(t);return e.write(`const ${c} = ${u}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),Y(e,t,n.out,c)}else return Y(e,t,n.out,i)}function At(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function _I(e,t,r,o){let n=r._zod.def;if(n.fn){if(At(n.fn))throw new Ue("z.compile: async custom predicates are not supported");let i=Tt(t,n.fn),a=D(t,Rc),s=R(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 yI(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return ge;let n=o;return n.issues.length===0?n.value:t()}function bI(e,t,r,o){let n=r._zod.def;if(!n.catchValue[ai])throw new Z("catch with a callback (only a constant catch value compiles)",!1);let i=R(t);e.write(`let ${i} = (() => {`),e.indented(c=>{let l=le(c,t,n.innerType,o);c.write(`return ${l};`)}),e.write("})();");let a=D(t,n.innerType),s=Tt(t,n.catchValue),u=D(t,yI);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 wI(e,t,r,o){let n=r._zod.def;if(n.transform){if(At(n.transform))throw new Ue("z.compile: async transforms are not supported");let i=n.transform,s=Tt(t,c=>{let l={value:c,issues:[],addIssue:Nc},d=i(c,l);return d instanceof Promise?ge:l.issues.length===0?d:ge}),u=R(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function no(e){return e.checks&&(e.checks=[...e.checks]),e}function zc(e,t){return new e(no({type:"string",...k(t)}))}function Uc(e,t){return new e(no({type:"string",coerce:!0,...k(t)}))}function ro(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...k(t)})}function io(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...k(t)})}function oo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...k(t)})}function ao(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(t)})}function so(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(t)})}function uo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(t)})}function vr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...k(t)})}function co(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...k(t)})}function lo(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(t)})}function po(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...k(t)})}function mo(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(t)})}function fo(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...k(t)})}function go(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...k(t)})}function ho(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(t)})}function vo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(t)})}function _o(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(t)})}function Lc(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...k(t)})}function yo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(t)})}function bo(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(t)})}function wo(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...k(t)})}function $o(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...k(t)})}function So(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...k(t)})}function jc(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...k(t)})}function Mc(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...k(t)})}function xo(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...k(t)})}var Fc={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _r(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(t)})}function yr(e,t){return new e({type:"string",format:"date",check:"string_format",...k(t)})}function br(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...k(t)})}function wr(e,t){return new e({type:"string",format:"duration",check:"string_format",...k(t)})}function Zc(e,t){return new e(no({type:"number",checks:[],...k(t)}))}function Bc(e,t){return new e(no({type:"number",coerce:!0,checks:[],...k(t)}))}function Vc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...k(t)})}function Gc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...k(t)})}function qc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...k(t)})}function Hc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...k(t)})}function Wc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...k(t)})}function Kc(e,t){return new e({type:"boolean",...k(t)})}function Jc(e,t){return new e({type:"boolean",coerce:!0,...k(t)})}function Yc(e,t){return new e({type:"bigint",...k(t)})}function Xc(e,t){return new e({type:"bigint",coerce:!0,...k(t)})}function Qc(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...k(t)})}function el(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...k(t)})}function tl(e,t){return new e({type:"symbol",...k(t)})}function nl(e,t){return new e({type:"undefined",...k(t)})}function rl(e,t){return new e({type:"null",...k(t)})}function il(e){return new e({type:"any"})}function ol(e){return new e({type:"unknown"})}function al(e,t){return new e({type:"never",...k(t)})}function sl(e,t){return new e({type:"void",...k(t)})}function ul(e,t){return new e({type:"date",...k(t)})}function cl(e,t){return new e({type:"date",coerce:!0,...k(t)})}function ll(e,t){return new e({type:"nan",...k(t)})}function Me(e,t){return new $i({check:"less_than",...k(t),value:e,inclusive:!1})}function ke(e,t){return new $i({check:"less_than",...k(t),value:e,inclusive:!0})}function Fe(e,t){return new Si({check:"greater_than",...k(t),value:e,inclusive:!1})}function Ee(e,t){return new Si({check:"greater_than",...k(t),value:e,inclusive:!0})}function Io(e){return Fe(0,e)}function ko(e){return Me(0,e)}function Eo(e){return ke(0,e)}function To(e){return Ee(0,e)}function ct(e,t){return new qs({check:"multiple_of",...k(t),value:e})}function lt(e,t){return new Ks({check:"max_size",...k(t),maximum:e})}function Ze(e,t){return new Js({check:"min_size",...k(t),minimum:e})}function Pt(e,t){return new Ys({check:"size_equals",...k(t),size:e})}function Rt(e,t){return new Xs({check:"max_length",...k(t),maximum:e})}function Ye(e,t){return new Qs({check:"min_length",...k(t),minimum:e})}function Ct(e,t){return new eu({check:"length_equals",...k(t),length:e})}function on(e,t){return new tu({check:"string_format",format:"regex",...k(t),pattern:e})}function an(e){return new nu({check:"string_format",format:"lowercase",...k(e)})}function sn(e){return new ru({check:"string_format",format:"uppercase",...k(e)})}function un(e,t){return new iu({check:"string_format",format:"includes",...k(t),includes:e})}function cn(e,t){return new ou({check:"string_format",format:"starts_with",...k(t),prefix:e})}function ln(e,t){return new au({check:"string_format",format:"ends_with",...k(t),suffix:e})}function Ao(e,t,r){return new su({check:"property",property:e,schema:t,...k(r)})}function dn(e,t){return new uu({check:"properties",shape:e,...k(t)})}function pn(e,t){return new cu({check:"mime_type",mime:e,...k(t)})}function Le(e){return new lu({check:"overwrite",tx:e})}function mn(e){return Le(t=>t.normalize(e))}function fn(){return Le(e=>e.trim())}function gn(){return Le(e=>e.toLowerCase())}function hn(){return Le(e=>e.toUpperCase())}function vn(){return Le(e=>Wa(e))}function dl(e,t,r){return new e({type:"array",element:t,...k(r)})}function $I(e,t,r){return new e({type:"union",options:t,...k(r)})}function SI(e,t,r){return new e({type:"union",options:t,inclusive:!1,...k(r)})}function xI(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...k(o)})}function II(e,t,r){return new e({type:"intersection",left:t,right:r})}function kI(e,t,r,o){let n=r instanceof z,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...k(i)})}function EI(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...k(o)})}function TI(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...k(o)})}function AI(e,t,r){return new e({type:"set",valueType:t,...k(r)})}function PI(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...k(r)})}function RI(e,t,r){return new e({type:"enum",entries:t,...k(r)})}function CI(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...k(r)})}function pl(e,t){return new e({type:"file",...k(t)})}function OI(e,t){return new e({type:"transform",transform:t})}function NI(e,t){return new e({type:"optional",innerType:t})}function DI(e,t){return new e({type:"nullable",innerType:t})}function zI(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Fn(r)}})}function UI(e,t,r){return new e({type:"nonoptional",innerType:t,...k(r)})}function LI(e,t){return new e({type:"success",innerType:t})}function jI(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:es(r)})}function MI(e,t,r){return new e({type:"pipe",in:t,out:r})}function FI(e,t){return new e({type:"readonly",innerType:t})}function ZI(e,t,r){return new e({type:"template_literal",parts:t,...k(r)})}function BI(e,t){return new e({type:"lazy",getter:t})}function VI(e,t){return new e({type:"promise",innerType:t})}function ml(e,t,r){let o=k(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function fl(e,t,r){return new e({type:"custom",check:"custom",fn:t,...k(r)})}function gl(e,t){let r=qg(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Wt(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(Wt(i))}},e(o.value,o)),t);return r}function qg(e,t){let r=new J({check:"custom",...k(t)});return r._zod.check=e,r}function hl(e){let t=new J({check:"describe"});return t._zod.onattach=[r=>{let o=se.get(r)??{};se.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function vl(e){let t=new J({check:"meta"});return t._zod.onattach=[r=>{let o=se.get(r)??{};se.add(r,{...o,...e})}],t._zod.check=()=>{},t}function _l(e,t){let r=k(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??lr,u=e.Boolean??ur,c=e.String??kt,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,g)=>{let _=p;return r.case!=="sensitive"&&(_=_.toLowerCase()),i.has(_)?!0:a.has(_)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((p,g)=>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 Ot(e,t,r,o={}){let n=k(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 $r(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&ae(e,o,r[o]);return e}function dt(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??se,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&&$r(a.schema,u),t.io==="input"&&he(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 Hg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function pt(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??(g=>g);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}/${Hg(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+Hg(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 Jg(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;Jg(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 Yg=new Set(["type","properties","required","additionalProperties"]),Wg=["oneOf","anyOf"];function Kg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function yl(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Yg.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]??Kg(c);l!=null&&(s.some(d=>JSON.stringify(d)===JSON.stringify(l))||s.push(l))}let u=s.length===1?s[0]:yl(s)??{allOf:s};ae(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=Kg(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 GI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Yg)if(n in e)return;let r=t.filter(n=>Wg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=yl(t);else{let n=r[0],i=Wg.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=>yl([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,$r(e,o))}function mt(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),g=p.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(g)):$r(c,g),$r(c,l),s._zod.parent===d)for(let I in c)I==="$ref"||I==="allOf"||I in l||delete c[I];if(g.$ref&&p.def)for(let I in c)I==="$ref"||I==="allOf"||I in p.def&&JSON.stringify(c[I])===JSON.stringify(p.def[I])&&delete c[I]}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 g in c)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(c[g])===JSON.stringify(p.def[g])&&delete c[g]}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())Jg(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)??[])GI(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)}$r(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,ae(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:_n(t,"input",e.processors),output:_n(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function he(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 he(o.element,r);if(o.type==="set")return he(o.valueType,r);if(o.type==="lazy")return he(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 he(o.innerType,r);if(o.type==="intersection")return he(o.left,r)||he(o.right,r);if(o.type==="record"||o.type==="map")return he(o.keyType,r)||he(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:he(o.in,r)||he(o.out,r);if(o.type==="object"){for(let n in o.shape)if(he(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(he(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(he(n,r))return!0;return!!(o.rest&&he(o.rest,r))}return!1}var bl=(e,t={})=>r=>{let o=dt({...r,processors:t});return W(e,o),pt(o,e),mt(o,e)},_n=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=dt({...n??{},target:i,io:t,processors:r});return W(e,a),pt(a,e),mt(a,e)};var yn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},bn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Xg=(e,t)=>{yn(e,"minimum",t),bn(e,"maximum",t)},nh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},rh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ih=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},oh=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Qg=(e,t)=>yn(e,"minimum",t.minimum),eh=(e,t)=>bn(e,"maximum",t.maximum),th=e=>(t,r)=>{oh(t,r.format);let[o,n]=e[r.format];yn(t,"minimum",o),bn(t,"maximum",n)},qI={greater_than:(e,t)=>yn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>bn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>nh(e,t.value),number_format:th(Bn),bigint_format:th(Vn),min_length:Qg,max_length:eh,length_equals:(e,t)=>Xg(e,t.length),min_size:Qg,max_size:eh,size_equals:(e,t)=>Xg(e,t.size),string_format:(e,t)=>{oh(e,t.format),t.pattern&&rh(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)=>ih(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)qI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&yn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&yn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&bn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&bn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&nh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&ih(t,n.mime);for(let i of n.patterns??[])rh(t,i);return t}var HI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},WI=new Map([[Oi,ks],[sr,Es]]),ah=e=>WI.get(e)??e,Sl=(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=HI[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(ah);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}))])}},xl=(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 g=new Set;for(let b of s)Number.isFinite(b)&&b!==0?g.add(Math.abs(b)):re(e,t,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[_,...I]=g;_!==void 0&&(n.multipleOf=_),I.length&&(n.allOf=[...n.allOf??[],...I.map(b=>({multipleOf:b}))])}},Il=(e,t,r,o)=>{r.type="boolean"},kl=(e,t,r,o)=>{re(e,t,r,o,"BigInt cannot be represented in JSON Schema")},El=(e,t,r,o)=>{re(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Al=(e,t,r,o)=>{re(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Pl=(e,t,r,o)=>{re(e,t,r,o,"Void cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{r.not={}},Cl=(e,t,r,o)=>{},Ol=(e,t,r,o)=>{},Nl=(e,t,r,o)=>{re(e,t,r,o,"Date cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{let n=e._zod.def,i=Bt(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},zl=(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},Ul=(e,t,r,o)=>{re(e,t,r,o,"NaN cannot be represented in JSON Schema")},Ll=(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},jl=(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})))},Ml=(e,t,r,o)=>{r.type="boolean"},Fl=(e,t,r,o)=>{re(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{re(e,t,r,o,"Function types cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{re(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Vl=(e,t,r,o)=>{re(e,t,r,o,"Map cannot be represented in JSON Schema")},Gl=(e,t,r,o)=>{re(e,t,r,o,"Set cannot be represented in JSON Schema")},ql=(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 Sr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Sr(t.out):t.type==="catch"?Sr(t.innerType):e._zod.optin}var Hl=(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)ae(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"?Sr(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)},Ro=(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},Wl=(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)},Kl=(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((_,I)=>W(_,t,{...o,path:[...o.path,a,I]})),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"?Sr(_)!==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:g}=ie(e);typeof p=="number"&&(n.minItems=p),typeof g=="number"&&(n.maxItems=g)};function wl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let _=wl(e,g,r);return _===g?t:_}for(let g of["anyOf","oneOf"]){let _=t[g];if(!Array.isArray(_))continue;let I=_.map(b=>wl(e,b,r));I.some((b,x)=>b!==_[x])&&(t={...t,[g]:I})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(g=>g==="number"||g==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(g=>typeof g=="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(g=>typeof g=="number"?String(g):g):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Je:er).source)),p}var $l=new WeakMap;function KI(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 $l.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=wl(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 Jl=(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)ae(n.patternProperties,ah(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=$l.get(t);l||(l=[],$l.set(t,l),t.deferred.push(()=>KI(t))),l.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=t.io==="input"&&Sr(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))}},Yl=(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"}]},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},Ql=Symbol();function sh(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 ed=(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=sh(n.defaultValue,e,t,r,o);a!==Ql&&(r.default=a)},td=(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=sh(n.defaultValue,e,t,r,o);a!==Ql&&(r._prefault=a)},nd=(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},rd=(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},id=(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},od=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Co=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ad=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},Po={string:Sl,number:xl,boolean:Il,bigint:kl,symbol:El,null:Tl,undefined:Al,void:Pl,never:Rl,any:Cl,unknown:Ol,date:Nl,enum:Dl,literal:zl,nan:Ul,template_literal:Ll,file:jl,success:Ml,custom:Fl,function:Zl,transform:Bl,map:Vl,set:Gl,array:ql,object:Hl,union:Ro,intersection:Wl,tuple:Kl,record:Jl,nullable:Yl,nonoptional:Xl,default:ed,prefault:td,catch:nd,pipe:rd,readonly:id,promise:od,optional:Co,lazy:ad};function Oo(e,t){if("_idmap"in e){let o=e,n=dt({...t,processors:Po}),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;pt(n,l),ae(a,c,mt(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=dt({...t,processors:Po});return W(e,r),pt(r,e),mt(r,e)}var No=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=dt({processors:Po,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,pt(this.ctx,t);let o=mt(this.ctx,t),{"~standard":n,...i}=o;return i}};var uh={};var Tn={};Ge(Tn,{ZodAny:()=>Td,ZodArray:()=>Cd,ZodBase64:()=>Qo,ZodBase64URL:()=>ea,ZodBigInt:()=>kn,ZodBigIntFormat:()=>ra,ZodBoolean:()=>In,ZodCIDRv4:()=>Yo,ZodCIDRv6:()=>Xo,ZodCUID:()=>Vo,ZodCUID2:()=>Go,ZodCatch:()=>Qd,ZodCodec:()=>Or,ZodCreditCard:()=>bd,ZodCustom:()=>Nr,ZodCustomStringFormat:()=>Ut,ZodDate:()=>Er,ZodDefault:()=>Hd,ZodDiscriminatedUnion:()=>Nd,ZodE164:()=>ta,ZodEmail:()=>Mo,ZodEmoji:()=>Zo,ZodEnum:()=>$n,ZodExactOptional:()=>sa,ZodFile:()=>Bd,ZodFunction:()=>cp,ZodGUID:()=>Fo,ZodIBAN:()=>wd,ZodIPv4:()=>Ko,ZodIPv6:()=>Jo,ZodISODate:()=>gt,ZodISODateTime:()=>ft,ZodISODuration:()=>vt,ZodISOTime:()=>ht,ZodInstanceOf:()=>pp,ZodIntersection:()=>Dd,ZodJWT:()=>na,ZodKSUID:()=>Wo,ZodLazy:()=>ap,ZodLiteral:()=>Zd,ZodMAC:()=>yd,ZodMap:()=>Md,ZodNaN:()=>tp,ZodNanoID:()=>Bo,ZodNever:()=>Pd,ZodNonOptional:()=>ua,ZodNull:()=>kd,ZodNullable:()=>qd,ZodNumber:()=>xn,ZodNumberFormat:()=>Lt,ZodObject:()=>Ar,ZodOptional:()=>Rr,ZodPipe:()=>Cr,ZodPrefault:()=>Kd,ZodPreprocess:()=>np,ZodPromise:()=>up,ZodReadonly:()=>rp,ZodRecord:()=>wn,ZodSet:()=>Fd,ZodString:()=>Sn,ZodStringFormat:()=>K,ZodSuccess:()=>Xd,ZodSymbol:()=>xd,ZodTemplateLiteral:()=>op,ZodTransform:()=>Vd,ZodTuple:()=>Ud,ZodType:()=>j,ZodULID:()=>qo,ZodURL:()=>kr,ZodUUID:()=>Be,ZodUndefined:()=>Id,ZodUnion:()=>Pr,ZodUnknown:()=>Ad,ZodVoid:()=>Rd,ZodXID:()=>Ho,ZodXor:()=>Od,_ZodString:()=>jo,_default:()=>Wd,_function:()=>bv,any:()=>Yh,array:()=>Tr,base64:()=>Rh,base64url:()=>Ch,bigint:()=>qh,boolean:()=>Sd,catch:()=>ep,check:()=>wv,cidrv4:()=>Ah,cidrv6:()=>Ph,codec:()=>hv,creditCard:()=>Nh,cuid:()=>wh,cuid2:()=>$h,currencyCode:()=>Mh,custom:()=>$v,date:()=>Qh,describe:()=>Sv,discriminatedUnion:()=>ov,e164:()=>Oh,email:()=>dh,emoji:()=>yh,enum:()=>oa,exactOptional:()=>Gd,file:()=>pv,float32:()=>Zh,float64:()=>Bh,function:()=>bv,guid:()=>ph,hash:()=>Fh,hex:()=>jh,hostname:()=>Lh,httpUrl:()=>_h,iban:()=>Dh,instanceof:()=>Iv,int:()=>Uo,int32:()=>Vh,int64:()=>Hh,intersection:()=>zd,invertCodec:()=>vv,ipv4:()=>kh,ipv6:()=>Th,json:()=>Ev,jwt:()=>zh,keyof:()=>ev,ksuid:()=>Ih,lazy:()=>sp,literal:()=>dv,looseObject:()=>rv,looseRecord:()=>sv,mac:()=>Eh,map:()=>uv,meta:()=>xv,nan:()=>gv,nanoid:()=>bh,nativeEnum:()=>lv,never:()=>ia,nonoptional:()=>Yd,null:()=>Ed,nullable:()=>Ir,nullish:()=>mv,number:()=>$d,object:()=>tv,optional:()=>Dt,partialRecord:()=>av,pipe:()=>Lo,prefault:()=>Jd,preprocess:()=>Tv,promise:()=>yv,readonly:()=>ip,record:()=>jd,refine:()=>lp,set:()=>cv,strictObject:()=>nv,string:()=>xr,stringFormat:()=>Uh,stringbool:()=>kv,success:()=>fv,superRefine:()=>dp,symbol:()=>Kh,templateLiteral:()=>_v,transform:()=>aa,tuple:()=>Ld,uint32:()=>Gh,uint64:()=>Wh,ulid:()=>Sh,undefined:()=>Jh,union:()=>En,unknown:()=>Nt,url:()=>vh,uuid:()=>mh,uuidv4:()=>fh,uuidv6:()=>gh,uuidv7:()=>hh,void:()=>Xh,xid:()=>xh,xor:()=>iv});var Do={};Ge(Do,{endsWith:()=>ln,gt:()=>Fe,gte:()=>Ee,includes:()=>un,length:()=>Ct,lowercase:()=>an,lt:()=>Me,lte:()=>ke,maxLength:()=>Rt,maxSize:()=>lt,mime:()=>pn,minLength:()=>Ye,minSize:()=>Ze,multipleOf:()=>ct,negative:()=>ko,nonnegative:()=>To,nonpositive:()=>Eo,normalize:()=>mn,overwrite:()=>Le,positive:()=>Io,properties:()=>dn,property:()=>Ao,regex:()=>on,size:()=>Pt,slugify:()=>vn,startsWith:()=>cn,toLowerCase:()=>gn,toUpperCase:()=>hn,trim:()=>fn,uppercase:()=>sn});var ch=new WeakSet([Object.prototype,Error.prototype]);function zo(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 lh=(e,t)=>{as.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ch.has(r)||(ch.add(r),zo(r,"format",o=>n=>Jn(o,n)),zo(r,"flatten",o=>n=>Kn(o,n)),zo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Vt,2)}),zo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Vt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},YI=h("ZodError",lh),Se=h("ZodError",lh,void 0,{Parent:Error});var sd=Kt(Se),ud=Jt(Se),cd=Yt(Se),ld=Xt(Se),dd=li(Se),pd=di(Se),md=pi(Se),fd=mi(Se),gd=fi(Se),hd=gi(Se),vd=hi(Se),_d=vi(Se);function QI(){oe.localeError||te(Ki())}function zt(){oe.memoizer||te({memoizer:fr()})}var j=h("ZodType",(e,t)=>(QI(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(w.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(lp(e,t))},superRefine(e,t){return this.check(dp(e,t))},overwrite(e){return this.check(Le(e))},optional(){return Dt(this)},exactOptional(){return Gd(this)},nullable(){return Ir(this)},nullish(){return Dt(Ir(this))},nonoptional(e){return Yd(this,e)},array(){return Tr(this)},or(e){return En([this,e])},and(e){return zd(this,e)},transform(e){return Lo(this,aa(e))},default(e){return Wd(this,e)},prefault(e){return Jd(this,e)},catch(e){return ep(this,e)},pipe(e){return Lo(this,e)},readonly(){return ip(this)},describe(e){let t=this.clone();return se.add(t,{description:e}),t},meta(...e){if(e.length===0)return se.get(this);let t=this.clone();return se.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 w.hide(this,"~standard",{...Ti(this),jsonSchema:{input:_n(this,"input"),output:_n(this,"output")}})},set"~standard"(e){w.own(this,"~standard",e)},parse:function e(t,r){return sd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await ud(this,t,r,{callee:e})},safeParse(e,t){return cd(this,e,t)},async safeParseAsync(e,t){return ld(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){w.own(this,"spa",e)},validate(e,t){return Yn(this,e,t)},validateAsync(e,t){return Xn(this,e,t)},encode:function e(t,r){return dd(this,t,r,{callee:e})},decode:function e(t,r){return pd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await md(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await fd(this,t,r,{callee:e})},safeEncode(e,t){return gd(this,e,t)},safeDecode(e,t){return hd(this,e,t)},async safeEncodeAsync(e,t){return vd(this,e,t)},async safeDecodeAsync(e,t){return _d(this,e,t)},toJSONSchema(e){return bl(this,{})(e)},get description(){return se.get(this)?.description},get _def(){return this._zod.def}}),jo=h("_ZodString",(e,t)=>{kt.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sl(e,r,o,n)},w.derived({format:e=>ie(e).format??null,minLength:e=>ie(e).minimum??null,maxLength:e=>ie(e).maximum??null},{regex(...e){return this.check(on(...e))},includes(...e){return this.check(un(...e))},startsWith(...e){return this.check(cn(...e))},endsWith(...e){return this.check(ln(...e))},min(...e){return this.check(Ye(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Ct(...e))},nonempty(...e){return this.check(Ye(1,...e))},lowercase(e){return this.check(an(e))},uppercase(e){return this.check(sn(e))},trim(){return this.check(fn())},normalize(...e){return this.check(mn(...e))},toLowerCase(){return this.check(gn())},toUpperCase(){return this.check(hn())},slugify(){return this.check(vn())}})),Sn=h("ZodString",(e,t)=>{kt.init(e,t),jo.init(e,t)},{email(e){return this.check(ro(Mo,e))},url(e){return this.check(vr(kr,e))},jwt(e){return this.check(xo(na,e))},emoji(e){return this.check(co(Zo,e))},guid(e){return this.check(io(Fo,e))},uuid(e){return this.check(oo(Be,e))},uuidv4(e){return this.check(ao(Be,e))},uuidv6(e){return this.check(so(Be,e))},uuidv7(e){return this.check(uo(Be,e))},nanoid(e){return this.check(lo(Bo,e))},cuid(e){return this.check(po(Vo,e))},cuid2(e){return this.check(mo(Go,e))},ulid(e){return this.check(fo(qo,e))},base64(e){return this.check(wo(Qo,e))},base64url(e){return this.check($o(ea,e))},xid(e){return this.check(go(Ho,e))},ksuid(e){return this.check(ho(Wo,e))},ipv4(e){return this.check(vo(Ko,e))},ipv6(e){return this.check(_o(Jo,e))},cidrv4(e){return this.check(yo(Yo,e))},cidrv6(e){return this.check(bo(Xo,e))},e164(e){return this.check(So(ta,e))},datetime(e){return this.check(_r(ft,e))},date(e){return this.check(yr(gt,e))},time(e){return this.check(br(ht,e))},duration(e){return this.check(wr(vt,e))}});function xr(e){return zc(Sn,e)}var K=h("ZodStringFormat",(e,t)=>{H.init(e,t),jo.init(e,t)}),ft=h("ZodISODateTime",(e,t)=>{ku.init(e,t),K.init(e,t)}),gt=h("ZodISODate",(e,t)=>{Eu.init(e,t),K.init(e,t)}),ht=h("ZodISOTime",(e,t)=>{Tu.init(e,t),K.init(e,t)}),vt=h("ZodISODuration",(e,t)=>{Au.init(e,t),K.init(e,t)}),Mo=h("ZodEmail",(e,t)=>{gu.init(e,t),K.init(e,t)});function dh(e){return ro(Mo,e)}var Fo=h("ZodGUID",(e,t)=>{mu.init(e,t),K.init(e,t)});function ph(e){return io(Fo,e)}var Be=h("ZodUUID",(e,t)=>{fu.init(e,t),K.init(e,t)});function mh(e){return oo(Be,e)}function fh(e){return ao(Be,e)}function gh(e){return so(Be,e)}function hh(e){return uo(Be,e)}var kr=h("ZodURL",(e,t)=>{_u.init(e,t),K.init(e,t)});function vh(e){return vr(kr,e)}function _h(e){return vr(kr,{protocol:Qn,hostname:As,...w.normalizeParams(e)})}var Zo=h("ZodEmoji",(e,t)=>{yu.init(e,t),K.init(e,t)});function yh(e){return co(Zo,e)}var Bo=h("ZodNanoID",(e,t)=>{bu.init(e,t),K.init(e,t)});function bh(e){return lo(Bo,e)}var Vo=h("ZodCUID",(e,t)=>{wu.init(e,t),K.init(e,t)});function wh(e){return po(Vo,e)}var Go=h("ZodCUID2",(e,t)=>{$u.init(e,t),K.init(e,t)});function $h(e){return mo(Go,e)}var qo=h("ZodULID",(e,t)=>{Su.init(e,t),K.init(e,t)});function Sh(e){return fo(qo,e)}var Ho=h("ZodXID",(e,t)=>{xu.init(e,t),K.init(e,t)});function xh(e){return go(Ho,e)}var Wo=h("ZodKSUID",(e,t)=>{Iu.init(e,t),K.init(e,t)});function Ih(e){return ho(Wo,e)}var Ko=h("ZodIPv4",(e,t)=>{Pu.init(e,t),K.init(e,t)});function kh(e){return vo(Ko,e)}var yd=h("ZodMAC",(e,t)=>{Cu.init(e,t),K.init(e,t)});function Eh(e){return Lc(yd,e)}var Jo=h("ZodIPv6",(e,t)=>{Ru.init(e,t),K.init(e,t)});function Th(e){return _o(Jo,e)}var Yo=h("ZodCIDRv4",(e,t)=>{Ou.init(e,t),K.init(e,t)});function Ah(e){return yo(Yo,e)}var Xo=h("ZodCIDRv6",(e,t)=>{Nu.init(e,t),K.init(e,t)});function Ph(e){return bo(Xo,e)}var Qo=h("ZodBase64",(e,t)=>{Du.init(e,t),K.init(e,t)});function Rh(e){return wo(Qo,e)}var ea=h("ZodBase64URL",(e,t)=>{zu.init(e,t),K.init(e,t)});function Ch(e){return $o(ea,e)}var ta=h("ZodE164",(e,t)=>{Uu.init(e,t),K.init(e,t)});function Oh(e){return So(ta,e)}var bd=h("ZodCreditCard",(e,t)=>{Lu.init(e,t),K.init(e,t)});function Nh(e){return jc(bd,e)}var wd=h("ZodIBAN",(e,t)=>{ju.init(e,t),K.init(e,t)});function Dh(e){return Mc(wd,e)}var na=h("ZodJWT",(e,t)=>{Mu.init(e,t),K.init(e,t)});function zh(e){return xo(na,e)}var Ut=h("ZodCustomStringFormat",(e,t)=>{Fu.init(e,t),K.init(e,t)});function Uh(e,t,r={}){return Ot(Ut,e,t,r)}function Lh(e){return Ot(Ut,"hostname",Ts,e)}function jh(e){return Ot(Ut,"hex",Bs,e)}function Mh(e){return Ot(Ut,"currency_code",Rs,e)}function Fh(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ce[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Ot(Ut,o,n,t)}var xn=h("ZodNumber",(e,t)=>{Li.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n),e.isFinite=!0},w.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(Fe(e,t))},gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},lt(e,t){return this.check(Me(e,t))},lte(e,t){return this.check(ke(e,t))},max(e,t){return this.check(ke(e,t))},int(e){return this.check(Uo(e))},safe(e){return this.check(Uo(e))},positive(e){return this.check(Fe(0,e))},nonnegative(e){return this.check(Ee(0,e))},negative(e){return this.check(Me(0,e))},nonpositive(e){return this.check(ke(0,e))},multipleOf(e,t){return this.check(ct(e,t))},step(e,t){return this.check(ct(e,t))},finite(){return this}}));function $d(e){return Zc(xn,e)}var Lt=h("ZodNumberFormat",(e,t)=>{Zu.init(e,t),xn.init(e,t)});function Uo(e){return Vc(Lt,e)}function Zh(e){return Gc(Lt,e)}function Bh(e){return qc(Lt,e)}function Vh(e){return Hc(Lt,e)}function Gh(e){return Wc(Lt,e)}var In=h("ZodBoolean",(e,t)=>{ur.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function Sd(e){return Kc(In,e)}var kn=h("ZodBigInt",(e,t)=>{ji.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)},w.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(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},gt(e,t){return this.check(Fe(e,t))},lt(e,t){return this.check(Me(e,t))},lte(e,t){return this.check(ke(e,t))},max(e,t){return this.check(ke(e,t))},positive(e){return this.check(Fe(BigInt(0),e))},negative(e){return this.check(Me(BigInt(0),e))},nonpositive(e){return this.check(ke(BigInt(0),e))},nonnegative(e){return this.check(Ee(BigInt(0),e))},multipleOf(e,t){return this.check(ct(e,t))}}));function qh(e){return Yc(kn,e)}var ra=h("ZodBigIntFormat",(e,t)=>{Bu.init(e,t),kn.init(e,t)});function Hh(e){return Qc(ra,e)}function Wh(e){return el(ra,e)}var xd=h("ZodSymbol",(e,t)=>{Vu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)});function Kh(e){return tl(xd,e)}var Id=h("ZodUndefined",(e,t)=>{Gu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n)});function Jh(e){return nl(Id,e)}var kd=h("ZodNull",(e,t)=>{qu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n)});function Ed(e){return rl(kd,e)}var Td=h("ZodAny",(e,t)=>{Hu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n)});function Yh(){return il(Td)}var Ad=h("ZodUnknown",(e,t)=>{Wu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function Nt(){return ol(Ad)}var Pd=h("ZodNever",(e,t)=>{Ku.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function ia(e){return al(Pd,e)}var Rd=h("ZodVoid",(e,t)=>{Ju.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Xh(e){return sl(Rd,e)}var Er=h("ZodDate",(e,t)=>{Yu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.min=(r,o)=>e.check(Ee(r,o)),e.max=(r,o)=>e.check(ke(r,o))},w.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 Qh(e){return ul(Er,e)}var Cd=h("ZodArray",(e,t)=>{zt(),Qu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.element=t.element},{min(e,t){return this.check(Ye(e,t))},nonempty(e){return this.check(Ye(1,e))},max(e,t){return this.check(Rt(e,t))},length(e,t){return this.check(Ct(e,t))},unwrap(){return this.element}});function Tr(e,t){return dl(Cd,e,t)}function ev(e){let t=e._zod.def.shape;return oa(Object.keys(t))}var Ar=h("ZodObject",(e,t)=>{zt(),ec.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),w.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return oa(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(w.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(w.mergeDefs(this._zod.def,{catchall:Nt()}))},loose(){return this.clone(w.mergeDefs(this._zod.def,{catchall:Nt()}))},strict(){return this.clone(w.mergeDefs(this._zod.def,{catchall:ia()}))},strip(){return this.clone(w.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return w.extend(this,e)},safeExtend(e){return w.safeExtend(this,e)},merge(e){return w.merge(this,e)},pick(e){return w.pick(this,e)},omit(e){return w.omit(this,e)},partial(...e){return w.partial(Rr,this,e[0])},exactPartial(...e){return w.partial(sa,this,e[0],"exactPartial")},required(...e){return w.required(ua,this,e[0])}});function tv(e,t){let r={type:"object",shape:e??{},...w.normalizeParams(t)};return new Ar(r)}function nv(e,t){return new Ar({type:"object",shape:e,catchall:ia(),...w.normalizeParams(t)})}function rv(e,t){return new Ar({type:"object",shape:e,catchall:Nt(),...w.normalizeParams(t)})}var Pr=h("ZodUnion",(e,t)=>{cr.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ro(e,r,o,n),e.options=t.options});function En(e,t){return new Pr({type:"union",options:e,...w.normalizeParams(t)})}var Od=h("ZodXor",(e,t)=>{Pr.init(e,t),tc.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ro(e,r,o,n),e.options=t.options});function iv(e,t){return new Od({type:"union",options:e,inclusive:!1,...w.normalizeParams(t)})}var Nd=h("ZodDiscriminatedUnion",(e,t)=>{Pr.init(e,t),rc.init(e,t)});function ov(e,t,r){return new Nd({type:"union",options:t,discriminator:e,...w.normalizeParams(r)})}var Dd=h("ZodIntersection",(e,t)=>{ic.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n)});function zd(e,t){return new Dd({type:"intersection",left:e,right:t})}var Ud=h("ZodTuple",(e,t)=>{zt(),Mi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(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 Rr({type:"optional",innerType:t}))})}});function Ld(e,t,r){let o=t instanceof z,n=o?r:t,i=o?t:null;return new Ud({type:"tuple",items:e,rest:i,...w.normalizeParams(n)})}var wn=h("ZodRecord",(e,t)=>{zt(),oc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function jd(e,t,r){return!t||!t._zod?new wn({type:"record",keyType:xr(),valueType:e,...w.normalizeParams(t)}):new wn({type:"record",keyType:e,valueType:t,...w.normalizeParams(r)})}function av(e,t,r){return new wn({type:"record",keyType:e,valueType:t,...w.normalizeParams(r),partial:!0})}function sv(e,t,r){return new wn({type:"record",keyType:e,valueType:t,mode:"loose",...w.normalizeParams(r)})}var Md=h("ZodMap",(e,t)=>{zt(),ac.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ze(...r)),e.nonempty=r=>e.check(Ze(1,r)),e.max=(...r)=>e.check(lt(...r)),e.size=(...r)=>e.check(Pt(...r))});function uv(e,t,r){return new Md({type:"map",keyType:e,valueType:t,...w.normalizeParams(r)})}var Fd=h("ZodSet",(e,t)=>{zt(),sc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.min=(...r)=>e.check(Ze(...r)),e.nonempty=r=>e.check(Ze(1,r)),e.max=(...r)=>e.check(lt(...r)),e.size=(...r)=>e.check(Pt(...r))});function cv(e,t){return new Fd({type:"set",valueType:e,...w.normalizeParams(t)})}var $n=h("ZodEnum",(e,t)=>{uc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Dl(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 $n({...t,checks:[],...w.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 $n({...t,checks:[],...w.normalizeParams(n),entries:i})}});function oa(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new $n({type:"enum",entries:r,...w.normalizeParams(t)})}function lv(e,t){return new $n({type:"enum",entries:e,...w.normalizeParams(t)})}var Zd=h("ZodLiteral",(e,t)=>{cc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(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 dv(e,t){return new Zd({type:"literal",values:Array.isArray(e)?e:[e],...w.normalizeParams(t)})}var Bd=h("ZodFile",(e,t)=>{lc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.min=(r,o)=>e.check(Ze(r,o)),e.max=(r,o)=>e.check(lt(r,o)),e.mime=(r,o)=>e.check(pn(Array.isArray(r)?r:[r],o))});function pv(e){return pl(Bd,e)}var Vd=h("ZodTransform",(e,t)=>{zt(),dc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new st(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(w.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(w.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 aa(e){return new Vd({type:"transform",transform:e})}var Rr=h("ZodOptional",(e,t)=>{Fi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Co(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Dt(e){return new Rr({type:"optional",innerType:e})}var sa=h("ZodExactOptional",(e,t)=>{pc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Co(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Gd(e){return new sa({type:"optional",innerType:e})}var qd=h("ZodNullable",(e,t)=>{mc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ir(e){return new qd({type:"nullable",innerType:e})}function mv(e){return Dt(Ir(e))}var Hd=h("ZodDefault",(e,t)=>{fc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Wd(e,t){return new Hd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():w.shallowClone(t)}})}var Kd=h("ZodPrefault",(e,t)=>{gc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Jd(e,t){return new Kd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():w.shallowClone(t)}})}var ua=h("ZodNonOptional",(e,t)=>{hc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Yd(e,t){return new ua({type:"nonoptional",innerType:e,...w.normalizeParams(t)})}var Xd=h("ZodSuccess",(e,t)=>{vc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fv(e){return new Xd({type:"success",innerType:e})}var Qd=h("ZodCatch",(e,t)=>{_c.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ep(e,t){return new Qd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:w.constantCatch(t)})}var tp=h("ZodNaN",(e,t)=>{yc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n)});function gv(e){return ll(tp,e)}var Cr=h("ZodPipe",(e,t)=>{Zi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.in=t.in,e.out=t.out});function Lo(e,t){return new Cr({type:"pipe",in:e,out:t})}var Or=h("ZodCodec",(e,t)=>{Cr.init(e,t),lr.init(e,t)});function hv(e,t,r){return new Or({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function vv(e){let t=e._zod.def;return new Or({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var np=h("ZodPreprocess",(e,t)=>{Cr.init(e,t),bc.init(e,t)}),rp=h("ZodReadonly",(e,t)=>{wc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ip(e){return new rp({type:"readonly",innerType:e})}var op=h("ZodTemplateLiteral",(e,t)=>{$c.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n)});function _v(e,t){return new op({type:"template_literal",parts:e,...w.normalizeParams(t)})}var ap=h("ZodLazy",(e,t)=>{dr.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function sp(e){return new ap({type:"lazy",getter:e})}var up=h("ZodPromise",(e,t)=>{xc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yv(e){return new up({type:"promise",innerType:e})}var cp=h("ZodFunction",(e,t)=>{Sc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)});function bv(e){return new cp({type:"function",input:Array.isArray(e?.input)?Ld(e?.input):e?.input??Tr(Nt()),output:e?.output??Nt()})}var Nr=h("ZodCustom",(e,t)=>{Ic.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function wv(e){let t=new J({check:"custom"});return t._zod.check=e,t}function $v(e,t){return ml(Nr,e??(()=>!0),t)}function lp(e,t={}){return fl(Nr,e,t)}function dp(e,t){return gl(e,t)}var Sv=hl,xv=vl,pp=h("ZodInstanceOf",(e,t)=>{Nr.init(e,t)},{properties(e,t){return this.check(dn(e,t))}});function Iv(e,t={}){let r=new pp({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...w.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 kv=(...e)=>_l({Codec:Or,Boolean:In,String:Sn},...e);function Ev(e){let t=sp(()=>En([xr(e),$d(),Sd(),Ed(),Tr(t),jd(xr(),t)]));return t}function Tv(e,t){return new np({type:"pipe",in:aa(e),out:t})}var ek={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 tk(e){te({customError:e})}function nk(){return te().customError}var mp;mp||(mp={});var Dr={};Ge(Dr,{ZodISODate:()=>gt,ZodISODateTime:()=>ft,ZodISODuration:()=>vt,ZodISOTime:()=>ht,date:()=>ik,datetime:()=>rk,duration:()=>ak,time:()=>ok});function rk(e){return _r(ft,e)}function ik(e){return yr(gt,e)}function ok(e){return br(ht,e)}function ak(e){return wr(vt,e)}var T={...Tn,...Do,iso:Dr},sk=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 uk(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 Av(e,t){return e.map((r,o)=>o<t?r:r.optional())}function ck(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function lk(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:ck(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 dk(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 fp(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=fp(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=fp(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 pk=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),mk=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function zr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(zr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>pk.has(t)?zr(r):!mk.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(zr))}function Pv(e){return e===1?"element":"elements"}function fk(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=fp(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 ${Pv(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 ${Pv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Rv(e,t){if(e!==!1)return e===void 0||e===!0?T.any():ve(e,t)}var gk=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Cv(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=lk(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 Cv(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(gk)):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);ae(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 I=ve(d[_],t),b=T.string().regex(new RegExp(_));p.push(T.looseRecord(b,I))}let g=[];if(Object.keys(n).length>0&&g.push(T.object(n).passthrough()),g.push(...p),g.length===0)o=T.object({}).passthrough();else if(g.length===1)o=g[0];else{let _=T.intersection(g[0],g[1]);for(let I=2;I<g.length;I++)_=T.intersection(_,g[I]);o=_}if(e.additionalProperties===!1){let _=Object.keys(n),I=m.map(x=>new RegExp(x)),b=o;o=o.check(x=>{if(!Pe(x.value))return;let E=[];for(let C of Object.keys(x.value))_.includes(C)||I.some(F=>F.test(C))||E.push(C);E.length&&x.issues.push({code:"unrecognized_keys",keys:E,input:x.value,inst:b})})}}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=dk(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=Av(s,a),c=Array.isArray(i)?void 0:Rv(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=Av(s,a),c=Rv(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=fk(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=Cv(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&&!zr(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&&!zr(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))sk.has(s)||ae(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function Ov(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=uk(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??se};return ve(r,i)}var Nv=Symbol("z.visit/resolving");function Ur(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===Nv)return new dr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Nv);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 g of l){let _=n(c[g]);_!==c[g]&&(d=!0),m[g]=_}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 g=n(p);g!==p&&(l=!0),d.push(g)}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 Dv(e){return Ur(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:En(r.options)}})}function hk(e,t){if(!t?.length)return e;let r=e._zod.def;return q(e,ze(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function zv(e){return hk(e.out,e.checks)}function vk(e){return e.in._zod.traits.has("$ZodTransform")?zv(e):e.in}function Uv(e){return Ur(e,{pipe:t=>vk(t._zod.def),default:(t,r)=>r?Dt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function Lv(e){return Ur(e,{pipe:t=>zv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var gp={};Ge(gp,{bigint:()=>wk,boolean:()=>bk,date:()=>$k,number:()=>yk,string:()=>_k});function _k(e){return Uc(Sn,e)}function yk(e){return Bc(xn,e)}function bk(e){return Jc(In,e)}function wk(e){return Xc(kn,e)}function $k(e){return cl(Er,e)}var Sk=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(),jv=f.array(Sk).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 hp(e){return new TextEncoder().encode(e).byteLength}var Mv=128*1024,Fv=512*1024,Zv=64,Bv=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"),Vv=f.string().refine(e=>hp(e)<=Mv&&!e.includes("\0"),`File contents must be text without null bytes, at most ${Mv} UTF-8 bytes`),qz=f.record(Bv,Vv.nullable()),vp=f.record(Bv,Vv).superRefine((e,t)=>{let r=Object.keys(e);(r.length>Zv||Object.values(e).reduce((o,n)=>o+hp(n),0)>Fv)&&t.addIssue({code:"custom",message:`Save at most ${Zv} helper files totaling ${Fv} 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 xk=/'/g,Ik=/^[A-Za-z0-9_./:=@,+-]+$/,ca=/^[A-Za-z_][A-Za-z0-9_]*$/;function kk(e){return`'${e.replace(xk,"'\\''")}'`}function Qe(e){return e===""?"''":Ik.test(e)?e:kk(e)}var Ek=12,Tk=10;var Ak=f.object({name:f.string().regex(ca).max(128),description:f.string().trim().min(1).max(300),values:f.array(f.string().min(1).max(200)).min(2).max(Tk).describe("Public non-secret setting values. Sent to QA models and shown in GitHub results.").optional()}).strict(),Gv=f.array(Ak).max(Ek);var Lr={Compose:"compose",Command:"command"};var qv=8,Pk=64,Kv=/^\/workspace\/(?!\.+$)(?!.*\.\.)[A-Za-z0-9._-]+$/,Rk=f.object({repoOwner:f.string().trim().min(1,"repoOwner is required"),repoName:f.string().trim().min(1,"repoName is required"),sandboxPath:f.string().regex(Kv,"sandboxPath must be a single path segment under /workspace").optional()}).strict();function Ck(e){return e.sandboxPath??`/workspace/${e.repoName}`}var uU=f.array(Rk).min(1,"at least one repo is required").max(qv,`at most ${qv} 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=Ck(i);if(!Kv.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)})}),Hv=f.object({name:f.string(),envVar:f.string()}),jr=f.record(f.string().regex(ca,"must be a POSIX-style environment variable name"),f.string()),Jv=f.object({type:f.enum([Lr.Compose]),files:f.array(f.string()).optional(),service:f.string().optional(),profiles:f.array(f.string()).optional()}).strict(),_p=f.object({fixtures:jv.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:Jv.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:jr.optional(),composeEnv:jr.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:jr.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(Pk).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(Hv).optional()}).strict().optional(),e2e:f.object({testCommand:f.string(),seedCommand:f.string().optional(),resetCommand:f.string().optional(),credentials:f.array(Hv).optional()}).strict().optional(),qaSwitches:Gv.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(),Ok="dockerfile",Nk=f.union([f.object({type:f.literal(Lr.Command),command:f.string().optional()}).passthrough(),f.object({type:f.literal(Ok),context:f.string().optional(),dockerfile:f.string().optional(),service:f.string().optional()}).passthrough()]),Yv=_p.extend({entry:f.union([Jv,Nk]).optional()}),Dk=/^[a-z][a-z0-9-]*$/;var Xv=f.object({id:f.string().trim().min(1).regex(Dk),description:f.string().trim().min(1),config:_p}).strict(),zk=Xv.extend({config:Yv}),Uk=f.array(Xv).superRefine((e,t)=>{new Set(e.map(r=>r.id)).size!==e.length&&t.addIssue({code:"custom",message:"App runtime names must be unique"})}),Wv=["defect","walkthrough","edge-case"];var Qv=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(Wv)).min(1).max(Wv.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(),cU=f.object({sandbox:f.object({appRuntime:_p.optional(),appRuntimes:Uk.optional(),helperFiles:vp.optional(),runtimeVariables:jr.optional(),iosApp:Qv.optional()}).strict().refine(e=>e.appRuntime===void 0||e.appRuntimes===void 0,{message:"Supply appRuntimes or legacy appRuntime, not both"}).optional()}).strict(),lU=f.object({sandbox:f.object({appRuntime:Yv.optional(),appRuntimes:f.array(zk).optional(),helperFiles:vp.optional(),runtimeVariables:jr.optional(),iosApp:Qv.optional()}).strict().optional()}).strict();function yp(e){if(!e)return null;let t=e.entry;if(t===void 0||t.type===Lr.Compose)return e;let{entry:r,...o}=e,n=t.type===Lr.Command?t.command?.trim():void 0,i=e.bootScript?.trim()?e.bootScript:n||e.bootScript;return{...o,...i!==void 0?{bootScript:i}:{}}}var la=1,Lk=["name","description","provisioningKind","provisioningConfig","helperFiles","cache","networkPolicy"];function jk(e){let t=e?.sandbox;if(!t)return e;let{appRuntime:r,appRuntimes:o,...n}=t;return{...e,sandbox:{...n,...r?{appRuntime:yp(r)}:{},...o?{appRuntimes:o.map(i=>({...i,config:yp(i.config)}))}:{}}}}function da(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:jk(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 e_(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 t_(e,t){let r={...da(e),repos:e.repos},o={...t.environment,repos:t.repos};return[...Lk,"repos"].filter(n=>e_(r[n]??null)!==e_(o[n]??null))}function n_(e,t){let r=da(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}async function r_(e,t){return(await P(e,A("/api/environments/:id",{id:t}))).data}function Zk(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!==la||!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 ${la}).`,{hint:"Write one with `arcanist environments export owner/repo -o <file>`."});return o}async function i_(e,t={},r){let{config:o}=G(r,t),n=await Ln(o,e),i=await r_(o,n.id),a={version:la,exportedFrom:{apiUrl:o.apiUrl,environmentId:i.id,configurationGeneration:i.cache.configurationGeneration,exportedAt:new Date().toISOString()},repos:i.repos,environment:da(i)},s=`${JSON.stringify(a,null,2)}
71
- `;if(t.output){await Fk(t.output,s,"utf8"),O(r,t,{environmentId:i.id,name:i.name,configurationGeneration:i.cache.configurationGeneration,path:t.output},u=>{console.log(`Exported "${N(u.name)}" (generation ${u.configurationGeneration}) to ${u.path}`)});return}process.stdout.write(s)}async function Bk(e,t,r,o){let n=t.repos[0],i=`${n.repoOwner}/${n.repoName}`,{name:a}=t.environment;if(r.dryRun){O(o,r,{environmentId:null,name:a,created:!1,applied:!1},u=>{console.log(`Would create "${N(u.name)}" for ${i} (dry run; nothing was sent).`)});return}let s=await P(e,A("/api/environments"),{method:"POST",body:JSON.stringify({...t.environment,repos:t.repos,scope:"team"})});O(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 "${N(u.name)}" for ${i} (${u.environmentId}).`),u.buildScheduled&&console.log("A build is scheduled; watch it with `arcanist environments status --wait`.")})}async function o_(e,t,r={},o){let n=Zk(await Mk(e,"utf8"),e),{config:i}=G(o,r),a=n.repos[0],s=t===void 0?await Um(i,{owner:a.repoOwner,repo:a.repoName}):await Ln(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 Bk(i,n,r,o);return}let u=await r_(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=t_(u,n),d=n_(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 P(i,`${A("/api/environments/:id",{id:u.id})}?dryRun=1`,{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),r.dryRun||l.length===0){O(o,r,{...m,applied:!1},_=>{console.log(_.changedFields.length===0?`"${N(_.name)}" already matches ${e}; nothing to apply.`:`Would change ${_.changedFields.join(", ")} on "${N(_.name)}" (dry run).`)});return}let p=await P(i,A("/api/environments/:id",{id:u.id}),{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),g=p.data.cache.configurationGeneration;O(o,r,{...m,applied:!0,configurationGeneration:{before:u.cache.configurationGeneration,after:g},rebuildScheduled:g!==u.cache.configurationGeneration&&p.data.cache.status==="enabled"},_=>{console.log(`Applied ${_.changedFields.join(", ")} to "${N(_.name)}" (generation ${_.configurationGeneration.before} -> ${_.configurationGeneration.after}).`),_.rebuildScheduled&&console.log("A rebuild is scheduled; watch it with `arcanist environments status --wait`.")})}var Mr="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.",pa="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 An(e){let t=Date.now()+e.timeoutMs;for(;Date.now()<t;){let r=await e.fetchStatus();if(r!==null)return r;await Kr(e.pollIntervalMs)}throw new y("server",e.timeoutMessage)}var a_=250,ma=1e3,s_=6e4,u_=200;function c_(e){return Hp(e)}var Vk=/^\d+$/;function Ve(e,t={}){let r=t.defaultMs??ma,o=t.minMs??a_,n=t.maxMs===void 0?s_:t.maxMs;if(!e)return r;if(!Vk.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 Pn=5e3,Gk=7200*1e3;function bp(e){let t=He(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function et(e,t){let o=(await P(e,A("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=Hk(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${Qe(o.question.id)} --answer-stdin --json`:n==="add_credentials"&&o.secretRequest?`arcanist environments secrets ${o.fullName} --request ${Qe(o.secretRequest.id)} --entries-stdin --json`:l_(n,o.fullName);return{...o,nextAction:n,command:i}}function qk(e){return e.nextAction==="wait"}function l_(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"add_credentials":case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function Hk(e){return e.status==="not_started"?"prepare":e.status==="ready"?"review":e.secretRequest?"add_credentials":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 Wk(e,t){return(e.repos?.length?e.repos:[{repoOwner:e.repoOwner,repoName:e.repoName}]).some(o=>o.repoOwner.toLowerCase()===t.owner.toLowerCase()&&o.repoName.toLowerCase()===t.repo.toLowerCase())}async function Kk(e,t){let r;try{r=(await P(e,A("/api/environments"))).data.environments}catch{return null}let o=r.find(a=>a.scope==="team"&&Wk(a,t));if(!o)return null;let n=`arcanist environments login ${o.repoOwner}/${o.repoName}`,i=o.browserState;return i?i.reloginNeeded?{state:"expired",capturedAt:i.capturedAt,command:n}:i.lastVerifiedAt?{state:"ready",capturedAt:i.capturedAt,command:null}:{state:"unverified",capturedAt:i.capturedAt,command:null}:{state:"none",capturedAt:null,command:n}}function Jk(e){if(!e)return;let t={none:"not captured",ready:"ready",expired:"expired",unverified:"captured, not verified yet"}[e.state];console.log(`browser login: ${t}${e.command?` (run: ${N(e.command)})`:""}`)}function fa(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${N(e.fullName)}: ${N(e.status)}${t?` (${N(t)})`:""}`)}async function wp(e,t,r){return An({pollIntervalMs:r,timeoutMs:Gk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await et(e,t);return qk(o)?null:o}})}async function $p(e,t){return(await P(e,A("/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 d_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t);await P(i,A("/api/repos"));let a=t.wait?await wp(i,n.fullName,o??Pn):await et(i,n.fullName),s=await Kk(i,n);O(r,t,{repository:a,browserLogin:s},({repository:u,browserLogin:c})=>{fa(u),Jk(c)})}async function p_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t),[a]=await $p(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",Mr):a.reason==="installation_github_check_failed"?new y("server",pa):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 wp(i,n.fullName,o??Pn);O(r,t,{repository:c},({repository:l})=>fa(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:l_(s,a.fullName)};O(r,t,{repository:u},({repository:c})=>fa(c))}async function m_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t);await P(i,A("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await wp(i,n.fullName,o??Pn):await et(i,n.fullName);O(r,t,{repository:a},({repository:s})=>fa(s))}var Yk=["openai","anthropic","baseten"],f_=f.enum(Yk),g_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),VU=f.object({managedFallback:f.boolean()}).strict(),h_=f.object({name:f.string().trim().min(1).max(80)}).strict();var ga=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}=G(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 P(o,`${A("/api/inference/keys")}?${n}`);O(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=h_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=G(o,r),a=await P(i,A("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});O(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}=G(o,r),i=await P(n,A("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});O(o,r,i,()=>console.log("Inference key revoked. Existing streams may finish."))}};var ha=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");ga.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=f_.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}=G(o,r),a=await P(i,t,n);O(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(A("/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=g_.safeParse({key:await bt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(A("/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(A("/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(A("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async usage(t,r){let{config:o}=G(r,t),n=await P(o,A("/api/inference/usage"));O(r,t,n,()=>console.log("Workflow usage is unavailable until proxy metering is connected. No spend totals are being reported."))}};var v_="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 E_}from"node:child_process";import{basename as uE,extname as cE}from"node:path";function __(e){return e.blocking===!0}var Xk=/[.!]+$/u,y_=["clear","issues_found","inconclusive"];var Qk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},b_="blocks merge";var w_="\u2705 Ruled out";function $_(e){return e.replace(Xk,"")}function S_(e){return Qk[e==="do_not_merge"?"do_not_merge":"merge"]}function eE(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function tE(e){return __(e)?"blocking":"non_blocking"}function nE(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function x_(e){let t=eE(e).prFindings,r=t.map(s=>({finding:s,impact:tE(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=nE(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var xp=3e6,Sp=f.string().regex(/^[0-9a-f]{40}$/),rE=["added","modified","removed","renamed"],iE=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(rE),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),oE=f.object({sha:Sp,subject:f.string(),body:f.string()}),pL=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:Sp,headRef:f.string().min(1),headSha:Sp,files:f.array(iE).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(oE),heldBackPaths:f.array(f.string())});function I_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var aE=["running","completed","failed"],sE=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(aE),verdict:f.enum(y_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),mL=f.object({reviews:f.array(sE),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var lE=/^origin\//,dE=/^new file mode /m,pE=/^deleted file mode /m,mE=/^\.\//,fE=/\/+$/,k_=64*1024*1024,gE=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),hE=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),vE=[".example",".sample",".template"];function T_(e={}){let t=e.cwd;if(Fr(["rev-parse","--is-inside-work-tree"],t)!=="true")throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Fr(["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&&!Fr(["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}:_E(t),n=Un(["rev-parse","HEAD"],{cwd:t}),i=Un(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=yE(Om([...s,"--numstat","-z",a],{cwd:t,maxBuffer:k_})),c=kE(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=bE(zn([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:k_}));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(xE)),m=E=>d.has(E)||[...d].some(C=>E.startsWith(`${C}/`)),p=E=>E.previousPath?[E.path,E.previousPath]:[E.path],g=SE(u.flatMap(p),t),_=[],I=[],b=[];if(u.forEach((E,C)=>{let F=l[C]??"";if(E.binary){I.push(E.path);return}if(p(E).some(Q=>$E(Q)||g.has(Q))&&!m(E.path)){b.push(E.path);return}_.push({path:E.path,...E.previousPath?{previousPath:E.previousPath}:{},status:wE(F,E),additions:E.additions,deletions:E.deletions,patch:F})}),_.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 x={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Un(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:I_(_),commitMessages:IE(`${i}..HEAD`,t),heldBackPaths:b.sort()};return EE(x),{payload:x,skippedBinaryPaths:I.sort(),uncommittedPaths:c}}function _E(e){let t=[Fr(["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(Fr(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(lE,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Fr(e,t){try{return E_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).trim()}catch{return null}}function yE(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 bE(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 Jg(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;Jg(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 Yg=new Set(["type","properties","required","additionalProperties"]),Wg=["oneOf","anyOf"];function Kg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function yl(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Yg.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]??Kg(c);l!=null&&(s.some(d=>JSON.stringify(d)===JSON.stringify(l))||s.push(l))}let u=s.length===1?s[0]:yl(s)??{allOf:s};ae(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=Kg(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 GI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Yg)if(n in e)return;let r=t.filter(n=>Wg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=yl(t);else{let n=r[0],i=Wg.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=>yl([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,$r(e,o))}function mt(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),g=p.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(g)):$r(c,g),$r(c,l),s._zod.parent===d)for(let I in c)I==="$ref"||I==="allOf"||I in l||delete c[I];if(g.$ref&&p.def)for(let I in c)I==="$ref"||I==="allOf"||I in p.def&&JSON.stringify(c[I])===JSON.stringify(p.def[I])&&delete c[I]}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 g in c)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(c[g])===JSON.stringify(p.def[g])&&delete c[g]}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())Jg(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)??[])GI(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)}$r(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,ae(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:_n(t,"input",e.processors),output:_n(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function he(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 he(o.element,r);if(o.type==="set")return he(o.valueType,r);if(o.type==="lazy")return he(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 he(o.innerType,r);if(o.type==="intersection")return he(o.left,r)||he(o.right,r);if(o.type==="record"||o.type==="map")return he(o.keyType,r)||he(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:he(o.in,r)||he(o.out,r);if(o.type==="object"){for(let n in o.shape)if(he(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(he(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(he(n,r))return!0;return!!(o.rest&&he(o.rest,r))}return!1}var bl=(e,t={})=>r=>{let o=dt({...r,processors:t});return W(e,o),pt(o,e),mt(o,e)},_n=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=dt({...n??{},target:i,io:t,processors:r});return W(e,a),pt(a,e),mt(a,e)};var yn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},bn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Xg=(e,t)=>{yn(e,"minimum",t),bn(e,"maximum",t)},nh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},rh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ih=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},oh=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Qg=(e,t)=>yn(e,"minimum",t.minimum),eh=(e,t)=>bn(e,"maximum",t.maximum),th=e=>(t,r)=>{oh(t,r.format);let[o,n]=e[r.format];yn(t,"minimum",o),bn(t,"maximum",n)},qI={greater_than:(e,t)=>yn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>bn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>nh(e,t.value),number_format:th(Bn),bigint_format:th(Vn),min_length:Qg,max_length:eh,length_equals:(e,t)=>Xg(e,t.length),min_size:Qg,max_size:eh,size_equals:(e,t)=>Xg(e,t.size),string_format:(e,t)=>{oh(e,t.format),t.pattern&&rh(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)=>ih(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)qI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&yn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&yn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&bn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&bn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&nh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&ih(t,n.mime);for(let i of n.patterns??[])rh(t,i);return t}var HI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},WI=new Map([[Oi,ks],[sr,Es]]),ah=e=>WI.get(e)??e,Sl=(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=HI[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(ah);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}))])}},xl=(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 g=new Set;for(let b of s)Number.isFinite(b)&&b!==0?g.add(Math.abs(b)):re(e,t,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[_,...I]=g;_!==void 0&&(n.multipleOf=_),I.length&&(n.allOf=[...n.allOf??[],...I.map(b=>({multipleOf:b}))])}},Il=(e,t,r,o)=>{r.type="boolean"},kl=(e,t,r,o)=>{re(e,t,r,o,"BigInt cannot be represented in JSON Schema")},El=(e,t,r,o)=>{re(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Al=(e,t,r,o)=>{re(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Pl=(e,t,r,o)=>{re(e,t,r,o,"Void cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{r.not={}},Cl=(e,t,r,o)=>{},Ol=(e,t,r,o)=>{},Nl=(e,t,r,o)=>{re(e,t,r,o,"Date cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{let n=e._zod.def,i=Bt(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},zl=(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},Ul=(e,t,r,o)=>{re(e,t,r,o,"NaN cannot be represented in JSON Schema")},Ll=(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},jl=(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})))},Ml=(e,t,r,o)=>{r.type="boolean"},Fl=(e,t,r,o)=>{re(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{re(e,t,r,o,"Function types cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{re(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Vl=(e,t,r,o)=>{re(e,t,r,o,"Map cannot be represented in JSON Schema")},Gl=(e,t,r,o)=>{re(e,t,r,o,"Set cannot be represented in JSON Schema")},ql=(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 Sr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Sr(t.out):t.type==="catch"?Sr(t.innerType):e._zod.optin}var Hl=(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)ae(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"?Sr(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)},Ro=(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},Wl=(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)},Kl=(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((_,I)=>W(_,t,{...o,path:[...o.path,a,I]})),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"?Sr(_)!==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:g}=ie(e);typeof p=="number"&&(n.minItems=p),typeof g=="number"&&(n.maxItems=g)};function wl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let _=wl(e,g,r);return _===g?t:_}for(let g of["anyOf","oneOf"]){let _=t[g];if(!Array.isArray(_))continue;let I=_.map(b=>wl(e,b,r));I.some((b,x)=>b!==_[x])&&(t={...t,[g]:I})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(g=>g==="number"||g==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(g=>typeof g=="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(g=>typeof g=="number"?String(g):g):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Je:er).source)),p}var $l=new WeakMap;function KI(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 $l.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=wl(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 Jl=(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)ae(n.patternProperties,ah(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=$l.get(t);l||(l=[],$l.set(t,l),t.deferred.push(()=>KI(t))),l.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=t.io==="input"&&Sr(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))}},Yl=(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"}]},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},Ql=Symbol();function sh(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 ed=(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=sh(n.defaultValue,e,t,r,o);a!==Ql&&(r.default=a)},td=(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=sh(n.defaultValue,e,t,r,o);a!==Ql&&(r._prefault=a)},nd=(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},rd=(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},id=(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},od=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Co=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ad=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},Po={string:Sl,number:xl,boolean:Il,bigint:kl,symbol:El,null:Tl,undefined:Al,void:Pl,never:Rl,any:Cl,unknown:Ol,date:Nl,enum:Dl,literal:zl,nan:Ul,template_literal:Ll,file:jl,success:Ml,custom:Fl,function:Zl,transform:Bl,map:Vl,set:Gl,array:ql,object:Hl,union:Ro,intersection:Wl,tuple:Kl,record:Jl,nullable:Yl,nonoptional:Xl,default:ed,prefault:td,catch:nd,pipe:rd,readonly:id,promise:od,optional:Co,lazy:ad};function Oo(e,t){if("_idmap"in e){let o=e,n=dt({...t,processors:Po}),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;pt(n,l),ae(a,c,mt(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=dt({...t,processors:Po});return W(e,r),pt(r,e),mt(r,e)}var No=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=dt({processors:Po,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,pt(this.ctx,t);let o=mt(this.ctx,t),{"~standard":n,...i}=o;return i}};var uh={};var Tn={};Ge(Tn,{ZodAny:()=>Td,ZodArray:()=>Cd,ZodBase64:()=>Qo,ZodBase64URL:()=>ea,ZodBigInt:()=>kn,ZodBigIntFormat:()=>ra,ZodBoolean:()=>In,ZodCIDRv4:()=>Yo,ZodCIDRv6:()=>Xo,ZodCUID:()=>Vo,ZodCUID2:()=>Go,ZodCatch:()=>Qd,ZodCodec:()=>Or,ZodCreditCard:()=>bd,ZodCustom:()=>Nr,ZodCustomStringFormat:()=>Ut,ZodDate:()=>Er,ZodDefault:()=>Hd,ZodDiscriminatedUnion:()=>Nd,ZodE164:()=>ta,ZodEmail:()=>Mo,ZodEmoji:()=>Zo,ZodEnum:()=>$n,ZodExactOptional:()=>sa,ZodFile:()=>Bd,ZodFunction:()=>cp,ZodGUID:()=>Fo,ZodIBAN:()=>wd,ZodIPv4:()=>Ko,ZodIPv6:()=>Jo,ZodISODate:()=>gt,ZodISODateTime:()=>ft,ZodISODuration:()=>vt,ZodISOTime:()=>ht,ZodInstanceOf:()=>pp,ZodIntersection:()=>Dd,ZodJWT:()=>na,ZodKSUID:()=>Wo,ZodLazy:()=>ap,ZodLiteral:()=>Zd,ZodMAC:()=>yd,ZodMap:()=>Md,ZodNaN:()=>tp,ZodNanoID:()=>Bo,ZodNever:()=>Pd,ZodNonOptional:()=>ua,ZodNull:()=>kd,ZodNullable:()=>qd,ZodNumber:()=>xn,ZodNumberFormat:()=>Lt,ZodObject:()=>Ar,ZodOptional:()=>Rr,ZodPipe:()=>Cr,ZodPrefault:()=>Kd,ZodPreprocess:()=>np,ZodPromise:()=>up,ZodReadonly:()=>rp,ZodRecord:()=>wn,ZodSet:()=>Fd,ZodString:()=>Sn,ZodStringFormat:()=>K,ZodSuccess:()=>Xd,ZodSymbol:()=>xd,ZodTemplateLiteral:()=>op,ZodTransform:()=>Vd,ZodTuple:()=>Ud,ZodType:()=>j,ZodULID:()=>qo,ZodURL:()=>kr,ZodUUID:()=>Be,ZodUndefined:()=>Id,ZodUnion:()=>Pr,ZodUnknown:()=>Ad,ZodVoid:()=>Rd,ZodXID:()=>Ho,ZodXor:()=>Od,_ZodString:()=>jo,_default:()=>Wd,_function:()=>bv,any:()=>Yh,array:()=>Tr,base64:()=>Rh,base64url:()=>Ch,bigint:()=>qh,boolean:()=>Sd,catch:()=>ep,check:()=>wv,cidrv4:()=>Ah,cidrv6:()=>Ph,codec:()=>hv,creditCard:()=>Nh,cuid:()=>wh,cuid2:()=>$h,currencyCode:()=>Mh,custom:()=>$v,date:()=>Qh,describe:()=>Sv,discriminatedUnion:()=>ov,e164:()=>Oh,email:()=>dh,emoji:()=>yh,enum:()=>oa,exactOptional:()=>Gd,file:()=>pv,float32:()=>Zh,float64:()=>Bh,function:()=>bv,guid:()=>ph,hash:()=>Fh,hex:()=>jh,hostname:()=>Lh,httpUrl:()=>_h,iban:()=>Dh,instanceof:()=>Iv,int:()=>Uo,int32:()=>Vh,int64:()=>Hh,intersection:()=>zd,invertCodec:()=>vv,ipv4:()=>kh,ipv6:()=>Th,json:()=>Ev,jwt:()=>zh,keyof:()=>ev,ksuid:()=>Ih,lazy:()=>sp,literal:()=>dv,looseObject:()=>rv,looseRecord:()=>sv,mac:()=>Eh,map:()=>uv,meta:()=>xv,nan:()=>gv,nanoid:()=>bh,nativeEnum:()=>lv,never:()=>ia,nonoptional:()=>Yd,null:()=>Ed,nullable:()=>Ir,nullish:()=>mv,number:()=>$d,object:()=>tv,optional:()=>Dt,partialRecord:()=>av,pipe:()=>Lo,prefault:()=>Jd,preprocess:()=>Tv,promise:()=>yv,readonly:()=>ip,record:()=>jd,refine:()=>lp,set:()=>cv,strictObject:()=>nv,string:()=>xr,stringFormat:()=>Uh,stringbool:()=>kv,success:()=>fv,superRefine:()=>dp,symbol:()=>Kh,templateLiteral:()=>_v,transform:()=>aa,tuple:()=>Ld,uint32:()=>Gh,uint64:()=>Wh,ulid:()=>Sh,undefined:()=>Jh,union:()=>En,unknown:()=>Nt,url:()=>vh,uuid:()=>mh,uuidv4:()=>fh,uuidv6:()=>gh,uuidv7:()=>hh,void:()=>Xh,xid:()=>xh,xor:()=>iv});var Do={};Ge(Do,{endsWith:()=>ln,gt:()=>Fe,gte:()=>Ee,includes:()=>un,length:()=>Ct,lowercase:()=>an,lt:()=>Me,lte:()=>ke,maxLength:()=>Rt,maxSize:()=>lt,mime:()=>pn,minLength:()=>Ye,minSize:()=>Ze,multipleOf:()=>ct,negative:()=>ko,nonnegative:()=>To,nonpositive:()=>Eo,normalize:()=>mn,overwrite:()=>Le,positive:()=>Io,properties:()=>dn,property:()=>Ao,regex:()=>on,size:()=>Pt,slugify:()=>vn,startsWith:()=>cn,toLowerCase:()=>gn,toUpperCase:()=>hn,trim:()=>fn,uppercase:()=>sn});var ch=new WeakSet([Object.prototype,Error.prototype]);function zo(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 lh=(e,t)=>{as.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ch.has(r)||(ch.add(r),zo(r,"format",o=>n=>Jn(o,n)),zo(r,"flatten",o=>n=>Kn(o,n)),zo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Vt,2)}),zo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Vt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},YI=h("ZodError",lh),Se=h("ZodError",lh,void 0,{Parent:Error});var sd=Kt(Se),ud=Jt(Se),cd=Yt(Se),ld=Xt(Se),dd=li(Se),pd=di(Se),md=pi(Se),fd=mi(Se),gd=fi(Se),hd=gi(Se),vd=hi(Se),_d=vi(Se);function QI(){oe.localeError||te(Ki())}function zt(){oe.memoizer||te({memoizer:fr()})}var j=h("ZodType",(e,t)=>(QI(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(w.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(lp(e,t))},superRefine(e,t){return this.check(dp(e,t))},overwrite(e){return this.check(Le(e))},optional(){return Dt(this)},exactOptional(){return Gd(this)},nullable(){return Ir(this)},nullish(){return Dt(Ir(this))},nonoptional(e){return Yd(this,e)},array(){return Tr(this)},or(e){return En([this,e])},and(e){return zd(this,e)},transform(e){return Lo(this,aa(e))},default(e){return Wd(this,e)},prefault(e){return Jd(this,e)},catch(e){return ep(this,e)},pipe(e){return Lo(this,e)},readonly(){return ip(this)},describe(e){let t=this.clone();return se.add(t,{description:e}),t},meta(...e){if(e.length===0)return se.get(this);let t=this.clone();return se.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 w.hide(this,"~standard",{...Ti(this),jsonSchema:{input:_n(this,"input"),output:_n(this,"output")}})},set"~standard"(e){w.own(this,"~standard",e)},parse:function e(t,r){return sd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await ud(this,t,r,{callee:e})},safeParse(e,t){return cd(this,e,t)},async safeParseAsync(e,t){return ld(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){w.own(this,"spa",e)},validate(e,t){return Yn(this,e,t)},validateAsync(e,t){return Xn(this,e,t)},encode:function e(t,r){return dd(this,t,r,{callee:e})},decode:function e(t,r){return pd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await md(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await fd(this,t,r,{callee:e})},safeEncode(e,t){return gd(this,e,t)},safeDecode(e,t){return hd(this,e,t)},async safeEncodeAsync(e,t){return vd(this,e,t)},async safeDecodeAsync(e,t){return _d(this,e,t)},toJSONSchema(e){return bl(this,{})(e)},get description(){return se.get(this)?.description},get _def(){return this._zod.def}}),jo=h("_ZodString",(e,t)=>{kt.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sl(e,r,o,n)},w.derived({format:e=>ie(e).format??null,minLength:e=>ie(e).minimum??null,maxLength:e=>ie(e).maximum??null},{regex(...e){return this.check(on(...e))},includes(...e){return this.check(un(...e))},startsWith(...e){return this.check(cn(...e))},endsWith(...e){return this.check(ln(...e))},min(...e){return this.check(Ye(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Ct(...e))},nonempty(...e){return this.check(Ye(1,...e))},lowercase(e){return this.check(an(e))},uppercase(e){return this.check(sn(e))},trim(){return this.check(fn())},normalize(...e){return this.check(mn(...e))},toLowerCase(){return this.check(gn())},toUpperCase(){return this.check(hn())},slugify(){return this.check(vn())}})),Sn=h("ZodString",(e,t)=>{kt.init(e,t),jo.init(e,t)},{email(e){return this.check(ro(Mo,e))},url(e){return this.check(vr(kr,e))},jwt(e){return this.check(xo(na,e))},emoji(e){return this.check(co(Zo,e))},guid(e){return this.check(io(Fo,e))},uuid(e){return this.check(oo(Be,e))},uuidv4(e){return this.check(ao(Be,e))},uuidv6(e){return this.check(so(Be,e))},uuidv7(e){return this.check(uo(Be,e))},nanoid(e){return this.check(lo(Bo,e))},cuid(e){return this.check(po(Vo,e))},cuid2(e){return this.check(mo(Go,e))},ulid(e){return this.check(fo(qo,e))},base64(e){return this.check(wo(Qo,e))},base64url(e){return this.check($o(ea,e))},xid(e){return this.check(go(Ho,e))},ksuid(e){return this.check(ho(Wo,e))},ipv4(e){return this.check(vo(Ko,e))},ipv6(e){return this.check(_o(Jo,e))},cidrv4(e){return this.check(yo(Yo,e))},cidrv6(e){return this.check(bo(Xo,e))},e164(e){return this.check(So(ta,e))},datetime(e){return this.check(_r(ft,e))},date(e){return this.check(yr(gt,e))},time(e){return this.check(br(ht,e))},duration(e){return this.check(wr(vt,e))}});function xr(e){return zc(Sn,e)}var K=h("ZodStringFormat",(e,t)=>{H.init(e,t),jo.init(e,t)}),ft=h("ZodISODateTime",(e,t)=>{ku.init(e,t),K.init(e,t)}),gt=h("ZodISODate",(e,t)=>{Eu.init(e,t),K.init(e,t)}),ht=h("ZodISOTime",(e,t)=>{Tu.init(e,t),K.init(e,t)}),vt=h("ZodISODuration",(e,t)=>{Au.init(e,t),K.init(e,t)}),Mo=h("ZodEmail",(e,t)=>{gu.init(e,t),K.init(e,t)});function dh(e){return ro(Mo,e)}var Fo=h("ZodGUID",(e,t)=>{mu.init(e,t),K.init(e,t)});function ph(e){return io(Fo,e)}var Be=h("ZodUUID",(e,t)=>{fu.init(e,t),K.init(e,t)});function mh(e){return oo(Be,e)}function fh(e){return ao(Be,e)}function gh(e){return so(Be,e)}function hh(e){return uo(Be,e)}var kr=h("ZodURL",(e,t)=>{_u.init(e,t),K.init(e,t)});function vh(e){return vr(kr,e)}function _h(e){return vr(kr,{protocol:Qn,hostname:As,...w.normalizeParams(e)})}var Zo=h("ZodEmoji",(e,t)=>{yu.init(e,t),K.init(e,t)});function yh(e){return co(Zo,e)}var Bo=h("ZodNanoID",(e,t)=>{bu.init(e,t),K.init(e,t)});function bh(e){return lo(Bo,e)}var Vo=h("ZodCUID",(e,t)=>{wu.init(e,t),K.init(e,t)});function wh(e){return po(Vo,e)}var Go=h("ZodCUID2",(e,t)=>{$u.init(e,t),K.init(e,t)});function $h(e){return mo(Go,e)}var qo=h("ZodULID",(e,t)=>{Su.init(e,t),K.init(e,t)});function Sh(e){return fo(qo,e)}var Ho=h("ZodXID",(e,t)=>{xu.init(e,t),K.init(e,t)});function xh(e){return go(Ho,e)}var Wo=h("ZodKSUID",(e,t)=>{Iu.init(e,t),K.init(e,t)});function Ih(e){return ho(Wo,e)}var Ko=h("ZodIPv4",(e,t)=>{Pu.init(e,t),K.init(e,t)});function kh(e){return vo(Ko,e)}var yd=h("ZodMAC",(e,t)=>{Cu.init(e,t),K.init(e,t)});function Eh(e){return Lc(yd,e)}var Jo=h("ZodIPv6",(e,t)=>{Ru.init(e,t),K.init(e,t)});function Th(e){return _o(Jo,e)}var Yo=h("ZodCIDRv4",(e,t)=>{Ou.init(e,t),K.init(e,t)});function Ah(e){return yo(Yo,e)}var Xo=h("ZodCIDRv6",(e,t)=>{Nu.init(e,t),K.init(e,t)});function Ph(e){return bo(Xo,e)}var Qo=h("ZodBase64",(e,t)=>{Du.init(e,t),K.init(e,t)});function Rh(e){return wo(Qo,e)}var ea=h("ZodBase64URL",(e,t)=>{zu.init(e,t),K.init(e,t)});function Ch(e){return $o(ea,e)}var ta=h("ZodE164",(e,t)=>{Uu.init(e,t),K.init(e,t)});function Oh(e){return So(ta,e)}var bd=h("ZodCreditCard",(e,t)=>{Lu.init(e,t),K.init(e,t)});function Nh(e){return jc(bd,e)}var wd=h("ZodIBAN",(e,t)=>{ju.init(e,t),K.init(e,t)});function Dh(e){return Mc(wd,e)}var na=h("ZodJWT",(e,t)=>{Mu.init(e,t),K.init(e,t)});function zh(e){return xo(na,e)}var Ut=h("ZodCustomStringFormat",(e,t)=>{Fu.init(e,t),K.init(e,t)});function Uh(e,t,r={}){return Ot(Ut,e,t,r)}function Lh(e){return Ot(Ut,"hostname",Ts,e)}function jh(e){return Ot(Ut,"hex",Bs,e)}function Mh(e){return Ot(Ut,"currency_code",Rs,e)}function Fh(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ce[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Ot(Ut,o,n,t)}var xn=h("ZodNumber",(e,t)=>{Li.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n),e.isFinite=!0},w.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(Fe(e,t))},gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},lt(e,t){return this.check(Me(e,t))},lte(e,t){return this.check(ke(e,t))},max(e,t){return this.check(ke(e,t))},int(e){return this.check(Uo(e))},safe(e){return this.check(Uo(e))},positive(e){return this.check(Fe(0,e))},nonnegative(e){return this.check(Ee(0,e))},negative(e){return this.check(Me(0,e))},nonpositive(e){return this.check(ke(0,e))},multipleOf(e,t){return this.check(ct(e,t))},step(e,t){return this.check(ct(e,t))},finite(){return this}}));function $d(e){return Zc(xn,e)}var Lt=h("ZodNumberFormat",(e,t)=>{Zu.init(e,t),xn.init(e,t)});function Uo(e){return Vc(Lt,e)}function Zh(e){return Gc(Lt,e)}function Bh(e){return qc(Lt,e)}function Vh(e){return Hc(Lt,e)}function Gh(e){return Wc(Lt,e)}var In=h("ZodBoolean",(e,t)=>{ur.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function Sd(e){return Kc(In,e)}var kn=h("ZodBigInt",(e,t)=>{ji.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)},w.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(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},gt(e,t){return this.check(Fe(e,t))},lt(e,t){return this.check(Me(e,t))},lte(e,t){return this.check(ke(e,t))},max(e,t){return this.check(ke(e,t))},positive(e){return this.check(Fe(BigInt(0),e))},negative(e){return this.check(Me(BigInt(0),e))},nonpositive(e){return this.check(ke(BigInt(0),e))},nonnegative(e){return this.check(Ee(BigInt(0),e))},multipleOf(e,t){return this.check(ct(e,t))}}));function qh(e){return Yc(kn,e)}var ra=h("ZodBigIntFormat",(e,t)=>{Bu.init(e,t),kn.init(e,t)});function Hh(e){return Qc(ra,e)}function Wh(e){return el(ra,e)}var xd=h("ZodSymbol",(e,t)=>{Vu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)});function Kh(e){return tl(xd,e)}var Id=h("ZodUndefined",(e,t)=>{Gu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n)});function Jh(e){return nl(Id,e)}var kd=h("ZodNull",(e,t)=>{qu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n)});function Ed(e){return rl(kd,e)}var Td=h("ZodAny",(e,t)=>{Hu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n)});function Yh(){return il(Td)}var Ad=h("ZodUnknown",(e,t)=>{Wu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function Nt(){return ol(Ad)}var Pd=h("ZodNever",(e,t)=>{Ku.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function ia(e){return al(Pd,e)}var Rd=h("ZodVoid",(e,t)=>{Ju.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Xh(e){return sl(Rd,e)}var Er=h("ZodDate",(e,t)=>{Yu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.min=(r,o)=>e.check(Ee(r,o)),e.max=(r,o)=>e.check(ke(r,o))},w.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 Qh(e){return ul(Er,e)}var Cd=h("ZodArray",(e,t)=>{zt(),Qu.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.element=t.element},{min(e,t){return this.check(Ye(e,t))},nonempty(e){return this.check(Ye(1,e))},max(e,t){return this.check(Rt(e,t))},length(e,t){return this.check(Ct(e,t))},unwrap(){return this.element}});function Tr(e,t){return dl(Cd,e,t)}function ev(e){let t=e._zod.def.shape;return oa(Object.keys(t))}var Ar=h("ZodObject",(e,t)=>{zt(),ec.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),w.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return oa(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(w.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(w.mergeDefs(this._zod.def,{catchall:Nt()}))},loose(){return this.clone(w.mergeDefs(this._zod.def,{catchall:Nt()}))},strict(){return this.clone(w.mergeDefs(this._zod.def,{catchall:ia()}))},strip(){return this.clone(w.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return w.extend(this,e)},safeExtend(e){return w.safeExtend(this,e)},merge(e){return w.merge(this,e)},pick(e){return w.pick(this,e)},omit(e){return w.omit(this,e)},partial(...e){return w.partial(Rr,this,e[0])},exactPartial(...e){return w.partial(sa,this,e[0],"exactPartial")},required(...e){return w.required(ua,this,e[0])}});function tv(e,t){let r={type:"object",shape:e??{},...w.normalizeParams(t)};return new Ar(r)}function nv(e,t){return new Ar({type:"object",shape:e,catchall:ia(),...w.normalizeParams(t)})}function rv(e,t){return new Ar({type:"object",shape:e,catchall:Nt(),...w.normalizeParams(t)})}var Pr=h("ZodUnion",(e,t)=>{cr.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ro(e,r,o,n),e.options=t.options});function En(e,t){return new Pr({type:"union",options:e,...w.normalizeParams(t)})}var Od=h("ZodXor",(e,t)=>{Pr.init(e,t),tc.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ro(e,r,o,n),e.options=t.options});function iv(e,t){return new Od({type:"union",options:e,inclusive:!1,...w.normalizeParams(t)})}var Nd=h("ZodDiscriminatedUnion",(e,t)=>{Pr.init(e,t),rc.init(e,t)});function ov(e,t,r){return new Nd({type:"union",options:t,discriminator:e,...w.normalizeParams(r)})}var Dd=h("ZodIntersection",(e,t)=>{ic.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n)});function zd(e,t){return new Dd({type:"intersection",left:e,right:t})}var Ud=h("ZodTuple",(e,t)=>{zt(),Mi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(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 Rr({type:"optional",innerType:t}))})}});function Ld(e,t,r){let o=t instanceof z,n=o?r:t,i=o?t:null;return new Ud({type:"tuple",items:e,rest:i,...w.normalizeParams(n)})}var wn=h("ZodRecord",(e,t)=>{zt(),oc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function jd(e,t,r){return!t||!t._zod?new wn({type:"record",keyType:xr(),valueType:e,...w.normalizeParams(t)}):new wn({type:"record",keyType:e,valueType:t,...w.normalizeParams(r)})}function av(e,t,r){return new wn({type:"record",keyType:e,valueType:t,...w.normalizeParams(r),partial:!0})}function sv(e,t,r){return new wn({type:"record",keyType:e,valueType:t,mode:"loose",...w.normalizeParams(r)})}var Md=h("ZodMap",(e,t)=>{zt(),ac.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ze(...r)),e.nonempty=r=>e.check(Ze(1,r)),e.max=(...r)=>e.check(lt(...r)),e.size=(...r)=>e.check(Pt(...r))});function uv(e,t,r){return new Md({type:"map",keyType:e,valueType:t,...w.normalizeParams(r)})}var Fd=h("ZodSet",(e,t)=>{zt(),sc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.min=(...r)=>e.check(Ze(...r)),e.nonempty=r=>e.check(Ze(1,r)),e.max=(...r)=>e.check(lt(...r)),e.size=(...r)=>e.check(Pt(...r))});function cv(e,t){return new Fd({type:"set",valueType:e,...w.normalizeParams(t)})}var $n=h("ZodEnum",(e,t)=>{uc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Dl(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 $n({...t,checks:[],...w.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 $n({...t,checks:[],...w.normalizeParams(n),entries:i})}});function oa(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new $n({type:"enum",entries:r,...w.normalizeParams(t)})}function lv(e,t){return new $n({type:"enum",entries:e,...w.normalizeParams(t)})}var Zd=h("ZodLiteral",(e,t)=>{cc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(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 dv(e,t){return new Zd({type:"literal",values:Array.isArray(e)?e:[e],...w.normalizeParams(t)})}var Bd=h("ZodFile",(e,t)=>{lc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.min=(r,o)=>e.check(Ze(r,o)),e.max=(r,o)=>e.check(lt(r,o)),e.mime=(r,o)=>e.check(pn(Array.isArray(r)?r:[r],o))});function pv(e){return pl(Bd,e)}var Vd=h("ZodTransform",(e,t)=>{zt(),dc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new st(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(w.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(w.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 aa(e){return new Vd({type:"transform",transform:e})}var Rr=h("ZodOptional",(e,t)=>{Fi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Co(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Dt(e){return new Rr({type:"optional",innerType:e})}var sa=h("ZodExactOptional",(e,t)=>{pc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Co(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Gd(e){return new sa({type:"optional",innerType:e})}var qd=h("ZodNullable",(e,t)=>{mc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ir(e){return new qd({type:"nullable",innerType:e})}function mv(e){return Dt(Ir(e))}var Hd=h("ZodDefault",(e,t)=>{fc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Wd(e,t){return new Hd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():w.shallowClone(t)}})}var Kd=h("ZodPrefault",(e,t)=>{gc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Jd(e,t){return new Kd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():w.shallowClone(t)}})}var ua=h("ZodNonOptional",(e,t)=>{hc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Yd(e,t){return new ua({type:"nonoptional",innerType:e,...w.normalizeParams(t)})}var Xd=h("ZodSuccess",(e,t)=>{vc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fv(e){return new Xd({type:"success",innerType:e})}var Qd=h("ZodCatch",(e,t)=>{_c.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ep(e,t){return new Qd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:w.constantCatch(t)})}var tp=h("ZodNaN",(e,t)=>{yc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n)});function gv(e){return ll(tp,e)}var Cr=h("ZodPipe",(e,t)=>{Zi.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.in=t.in,e.out=t.out});function Lo(e,t){return new Cr({type:"pipe",in:e,out:t})}var Or=h("ZodCodec",(e,t)=>{Cr.init(e,t),lr.init(e,t)});function hv(e,t,r){return new Or({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function vv(e){let t=e._zod.def;return new Or({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var np=h("ZodPreprocess",(e,t)=>{Cr.init(e,t),bc.init(e,t)}),rp=h("ZodReadonly",(e,t)=>{wc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ip(e){return new rp({type:"readonly",innerType:e})}var op=h("ZodTemplateLiteral",(e,t)=>{$c.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n)});function _v(e,t){return new op({type:"template_literal",parts:e,...w.normalizeParams(t)})}var ap=h("ZodLazy",(e,t)=>{dr.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function sp(e){return new ap({type:"lazy",getter:e})}var up=h("ZodPromise",(e,t)=>{xc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yv(e){return new up({type:"promise",innerType:e})}var cp=h("ZodFunction",(e,t)=>{Sc.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)});function bv(e){return new cp({type:"function",input:Array.isArray(e?.input)?Ld(e?.input):e?.input??Tr(Nt()),output:e?.output??Nt()})}var Nr=h("ZodCustom",(e,t)=>{Ic.init(e,t),j.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function wv(e){let t=new J({check:"custom"});return t._zod.check=e,t}function $v(e,t){return ml(Nr,e??(()=>!0),t)}function lp(e,t={}){return fl(Nr,e,t)}function dp(e,t){return gl(e,t)}var Sv=hl,xv=vl,pp=h("ZodInstanceOf",(e,t)=>{Nr.init(e,t)},{properties(e,t){return this.check(dn(e,t))}});function Iv(e,t={}){let r=new pp({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...w.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 kv=(...e)=>_l({Codec:Or,Boolean:In,String:Sn},...e);function Ev(e){let t=sp(()=>En([xr(e),$d(),Sd(),Ed(),Tr(t),jd(xr(),t)]));return t}function Tv(e,t){return new np({type:"pipe",in:aa(e),out:t})}var ek={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 tk(e){te({customError:e})}function nk(){return te().customError}var mp;mp||(mp={});var Dr={};Ge(Dr,{ZodISODate:()=>gt,ZodISODateTime:()=>ft,ZodISODuration:()=>vt,ZodISOTime:()=>ht,date:()=>ik,datetime:()=>rk,duration:()=>ak,time:()=>ok});function rk(e){return _r(ft,e)}function ik(e){return yr(gt,e)}function ok(e){return br(ht,e)}function ak(e){return wr(vt,e)}var T={...Tn,...Do,iso:Dr},sk=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 uk(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 Av(e,t){return e.map((r,o)=>o<t?r:r.optional())}function ck(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function lk(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:ck(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 dk(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 fp(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=fp(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=fp(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 pk=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),mk=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function zr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(zr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>pk.has(t)?zr(r):!mk.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(zr))}function Pv(e){return e===1?"element":"elements"}function fk(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=fp(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 ${Pv(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 ${Pv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Rv(e,t){if(e!==!1)return e===void 0||e===!0?T.any():ve(e,t)}var gk=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Cv(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=lk(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 Cv(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(gk)):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);ae(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 I=ve(d[_],t),b=T.string().regex(new RegExp(_));p.push(T.looseRecord(b,I))}let g=[];if(Object.keys(n).length>0&&g.push(T.object(n).passthrough()),g.push(...p),g.length===0)o=T.object({}).passthrough();else if(g.length===1)o=g[0];else{let _=T.intersection(g[0],g[1]);for(let I=2;I<g.length;I++)_=T.intersection(_,g[I]);o=_}if(e.additionalProperties===!1){let _=Object.keys(n),I=m.map(x=>new RegExp(x)),b=o;o=o.check(x=>{if(!Pe(x.value))return;let E=[];for(let C of Object.keys(x.value))_.includes(C)||I.some(F=>F.test(C))||E.push(C);E.length&&x.issues.push({code:"unrecognized_keys",keys:E,input:x.value,inst:b})})}}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=dk(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=Av(s,a),c=Array.isArray(i)?void 0:Rv(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=Av(s,a),c=Rv(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=fk(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=Cv(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&&!zr(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&&!zr(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))sk.has(s)||ae(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function Ov(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=uk(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??se};return ve(r,i)}var Nv=Symbol("z.visit/resolving");function Ur(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===Nv)return new dr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Nv);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 g of l){let _=n(c[g]);_!==c[g]&&(d=!0),m[g]=_}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 g=n(p);g!==p&&(l=!0),d.push(g)}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 Dv(e){return Ur(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:En(r.options)}})}function hk(e,t){if(!t?.length)return e;let r=e._zod.def;return q(e,ze(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function zv(e){return hk(e.out,e.checks)}function vk(e){return e.in._zod.traits.has("$ZodTransform")?zv(e):e.in}function Uv(e){return Ur(e,{pipe:t=>vk(t._zod.def),default:(t,r)=>r?Dt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function Lv(e){return Ur(e,{pipe:t=>zv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var gp={};Ge(gp,{bigint:()=>wk,boolean:()=>bk,date:()=>$k,number:()=>yk,string:()=>_k});function _k(e){return Uc(Sn,e)}function yk(e){return Bc(xn,e)}function bk(e){return Jc(In,e)}function wk(e){return Xc(kn,e)}function $k(e){return cl(Er,e)}var Sk=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(),jv=f.array(Sk).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 hp(e){return new TextEncoder().encode(e).byteLength}var Mv=128*1024,Fv=512*1024,Zv=64,Bv=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"),Vv=f.string().refine(e=>hp(e)<=Mv&&!e.includes("\0"),`File contents must be text without null bytes, at most ${Mv} UTF-8 bytes`),Hz=f.record(Bv,Vv.nullable()),vp=f.record(Bv,Vv).superRefine((e,t)=>{let r=Object.keys(e);(r.length>Zv||Object.values(e).reduce((o,n)=>o+hp(n),0)>Fv)&&t.addIssue({code:"custom",message:`Save at most ${Zv} helper files totaling ${Fv} 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 xk=/'/g,Ik=/^[A-Za-z0-9_./:=@,+-]+$/,ca=/^[A-Za-z_][A-Za-z0-9_]*$/;function kk(e){return`'${e.replace(xk,"'\\''")}'`}function Qe(e){return e===""?"''":Ik.test(e)?e:kk(e)}var Ek=12,Tk=10;var Ak=f.object({name:f.string().regex(ca).max(128),description:f.string().trim().min(1).max(300),values:f.array(f.string().min(1).max(200)).min(2).max(Tk).describe("Public non-secret setting values. Sent to QA models and shown in GitHub results.").optional()}).strict(),Gv=f.array(Ak).max(Ek);var Lr={Compose:"compose",Command:"command"};var qv=8,Pk=64,Kv=/^\/workspace\/(?!\.+$)(?!.*\.\.)[A-Za-z0-9._-]+$/,Rk=f.object({repoOwner:f.string().trim().min(1,"repoOwner is required"),repoName:f.string().trim().min(1,"repoName is required"),sandboxPath:f.string().regex(Kv,"sandboxPath must be a single path segment under /workspace").optional()}).strict();function Ck(e){return e.sandboxPath??`/workspace/${e.repoName}`}var cU=f.array(Rk).min(1,"at least one repo is required").max(qv,`at most ${qv} 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=Ck(i);if(!Kv.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)})}),Hv=f.object({name:f.string(),envVar:f.string()}),jr=f.record(f.string().regex(ca,"must be a POSIX-style environment variable name"),f.string()),Jv=f.object({type:f.enum([Lr.Compose]),files:f.array(f.string()).optional(),service:f.string().optional(),profiles:f.array(f.string()).optional()}).strict(),_p=f.object({fixtures:jv.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:Jv.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:jr.optional(),composeEnv:jr.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:jr.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(Pk).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(Hv).optional()}).strict().optional(),e2e:f.object({testCommand:f.string(),seedCommand:f.string().optional(),resetCommand:f.string().optional(),credentials:f.array(Hv).optional()}).strict().optional(),qaSwitches:Gv.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(),Ok="dockerfile",Nk=f.union([f.object({type:f.literal(Lr.Command),command:f.string().optional()}).passthrough(),f.object({type:f.literal(Ok),context:f.string().optional(),dockerfile:f.string().optional(),service:f.string().optional()}).passthrough()]),Yv=_p.extend({entry:f.union([Jv,Nk]).optional()}),Dk=/^[a-z][a-z0-9-]*$/;var Xv=f.object({id:f.string().trim().min(1).regex(Dk),description:f.string().trim().min(1),config:_p}).strict(),zk=Xv.extend({config:Yv}),Uk=f.array(Xv).superRefine((e,t)=>{new Set(e.map(r=>r.id)).size!==e.length&&t.addIssue({code:"custom",message:"App runtime names must be unique"})}),Wv=["defect","walkthrough","edge-case"];var Qv=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(Wv)).min(1).max(Wv.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(),lU=f.object({sandbox:f.object({appRuntime:_p.optional(),appRuntimes:Uk.optional(),helperFiles:vp.optional(),runtimeVariables:jr.optional(),iosApp:Qv.optional()}).strict().refine(e=>e.appRuntime===void 0||e.appRuntimes===void 0,{message:"Supply appRuntimes or legacy appRuntime, not both"}).optional()}).strict(),dU=f.object({sandbox:f.object({appRuntime:Yv.optional(),appRuntimes:f.array(zk).optional(),helperFiles:vp.optional(),runtimeVariables:jr.optional(),iosApp:Qv.optional()}).strict().optional()}).strict();function yp(e){if(!e)return null;let t=e.entry;if(t===void 0||t.type===Lr.Compose)return e;let{entry:r,...o}=e,n=t.type===Lr.Command?t.command?.trim():void 0,i=e.bootScript?.trim()?e.bootScript:n||e.bootScript;return{...o,...i!==void 0?{bootScript:i}:{}}}var la=1,Lk=["name","description","provisioningKind","provisioningConfig","helperFiles","cache","networkPolicy"];function jk(e){let t=e?.sandbox;if(!t)return e;let{appRuntime:r,appRuntimes:o,...n}=t;return{...e,sandbox:{...n,...r?{appRuntime:yp(r)}:{},...o?{appRuntimes:o.map(i=>({...i,config:yp(i.config)}))}:{}}}}function da(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:jk(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 e_(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 t_(e,t){let r={...da(e),repos:e.repos},o={...t.environment,repos:t.repos};return[...Lk,"repos"].filter(n=>e_(r[n]??null)!==e_(o[n]??null))}function n_(e,t){let r=da(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}async function r_(e,t){return(await P(e,A("/api/environments/:id",{id:t}))).data}function Zk(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!==la||!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 ${la}).`,{hint:"Write one with `arcanist environments export owner/repo -o <file>`."});return o}async function i_(e,t={},r){let{config:o}=G(r,t),n=await Ln(o,e),i=await r_(o,n.id),a={version:la,exportedFrom:{apiUrl:o.apiUrl,environmentId:i.id,configurationGeneration:i.cache.configurationGeneration,exportedAt:new Date().toISOString()},repos:i.repos,environment:da(i)},s=`${JSON.stringify(a,null,2)}
71
+ `;if(t.output){await Fk(t.output,s,"utf8"),O(r,t,{environmentId:i.id,name:i.name,configurationGeneration:i.cache.configurationGeneration,path:t.output},u=>{console.log(`Exported "${N(u.name)}" (generation ${u.configurationGeneration}) to ${u.path}`)});return}process.stdout.write(s)}async function Bk(e,t,r,o){let n=t.repos[0],i=`${n.repoOwner}/${n.repoName}`,{name:a}=t.environment;if(r.dryRun){O(o,r,{environmentId:null,name:a,created:!1,applied:!1},u=>{console.log(`Would create "${N(u.name)}" for ${i} (dry run; nothing was sent).`)});return}let s=await P(e,A("/api/environments"),{method:"POST",body:JSON.stringify({...t.environment,repos:t.repos,scope:"team"})});O(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 "${N(u.name)}" for ${i} (${u.environmentId}).`),u.buildScheduled&&console.log("A build is scheduled; watch it with `arcanist environments status --wait`.")})}async function o_(e,t,r={},o){let n=Zk(await Mk(e,"utf8"),e),{config:i}=G(o,r),a=n.repos[0],s=t===void 0?await Um(i,{owner:a.repoOwner,repo:a.repoName}):await Ln(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 Bk(i,n,r,o);return}let u=await r_(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=t_(u,n),d=n_(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 P(i,`${A("/api/environments/:id",{id:u.id})}?dryRun=1`,{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),r.dryRun||l.length===0){O(o,r,{...m,applied:!1},_=>{console.log(_.changedFields.length===0?`"${N(_.name)}" already matches ${e}; nothing to apply.`:`Would change ${_.changedFields.join(", ")} on "${N(_.name)}" (dry run).`)});return}let p=await P(i,A("/api/environments/:id",{id:u.id}),{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),g=p.data.cache.configurationGeneration;O(o,r,{...m,applied:!0,configurationGeneration:{before:u.cache.configurationGeneration,after:g},rebuildScheduled:g!==u.cache.configurationGeneration&&p.data.cache.status==="enabled"},_=>{console.log(`Applied ${_.changedFields.join(", ")} to "${N(_.name)}" (generation ${_.configurationGeneration.before} -> ${_.configurationGeneration.after}).`),_.rebuildScheduled&&console.log("A rebuild is scheduled; watch it with `arcanist environments status --wait`.")})}var Mr="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.",pa="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 An(e){let t=Date.now()+e.timeoutMs;for(;Date.now()<t;){let r=await e.fetchStatus();if(r!==null)return r;await Kr(e.pollIntervalMs)}throw new y("server",e.timeoutMessage)}var a_=250,ma=1e3,s_=6e4,u_=200;function c_(e){return Hp(e)}var Vk=/^\d+$/;function Ve(e,t={}){let r=t.defaultMs??ma,o=t.minMs??a_,n=t.maxMs===void 0?s_:t.maxMs;if(!e)return r;if(!Vk.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 Pn=5e3,Gk=7200*1e3;function bp(e){let t=He(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function et(e,t){let o=(await P(e,A("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=Hk(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${Qe(o.question.id)} --answer-stdin --json`:n==="add_credentials"&&o.secretRequest?`arcanist environments secrets ${o.fullName} --request ${Qe(o.secretRequest.id)} --entries-stdin --json`:l_(n,o.fullName);return{...o,nextAction:n,command:i}}function qk(e){return e.nextAction==="wait"}function l_(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"add_credentials":case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function Hk(e){return e.status==="not_started"?"prepare":e.status==="ready"?"review":e.secretRequest?"add_credentials":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 Wk(e,t){return(e.repos?.length?e.repos:[{repoOwner:e.repoOwner,repoName:e.repoName}]).some(o=>o.repoOwner.toLowerCase()===t.owner.toLowerCase()&&o.repoName.toLowerCase()===t.repo.toLowerCase())}async function Kk(e,t){let r;try{r=(await P(e,A("/api/environments"))).data.environments}catch{return null}let o=r.find(a=>a.scope==="team"&&Wk(a,t));if(!o)return null;let n=`arcanist environments login ${o.repoOwner}/${o.repoName}`,i=o.browserState;return i?i.reloginNeeded?{state:"expired",capturedAt:i.capturedAt,command:n}:i.lastVerifiedAt?{state:"ready",capturedAt:i.capturedAt,command:null}:{state:"unverified",capturedAt:i.capturedAt,command:null}:{state:"none",capturedAt:null,command:n}}function Jk(e){if(!e)return;let t={none:"not captured",ready:"ready",expired:"expired",unverified:"captured, not verified yet"}[e.state];console.log(`browser login: ${t}${e.command?` (run: ${N(e.command)})`:""}`)}function fa(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${N(e.fullName)}: ${N(e.status)}${t?` (${N(t)})`:""}`)}async function wp(e,t,r){return An({pollIntervalMs:r,timeoutMs:Gk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await et(e,t);return qk(o)?null:o}})}async function $p(e,t){return(await P(e,A("/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 d_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t);await P(i,A("/api/repos"));let a=t.wait?await wp(i,n.fullName,o??Pn):await et(i,n.fullName),s=await Kk(i,n);O(r,t,{repository:a,browserLogin:s},({repository:u,browserLogin:c})=>{fa(u),Jk(c)})}async function p_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t),[a]=await $p(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",Mr):a.reason==="installation_github_check_failed"?new y("server",pa):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 wp(i,n.fullName,o??Pn);O(r,t,{repository:c},({repository:l})=>fa(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:l_(s,a.fullName)};O(r,t,{repository:u},({repository:c})=>fa(c))}async function m_(e,t={},r){let o=t.wait?Ve(t.pollInterval,{defaultMs:Pn,maxMs:null}):null,n=bp(e),{config:i}=G(r,t);await P(i,A("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await wp(i,n.fullName,o??Pn):await et(i,n.fullName);O(r,t,{repository:a},({repository:s})=>fa(s))}var Yk=["openai","anthropic","baseten"],f_=f.enum(Yk),g_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),GU=f.object({managedFallback:f.boolean()}).strict(),h_=f.object({name:f.string().trim().min(1).max(80)}).strict();var ga=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}=G(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 P(o,`${A("/api/inference/keys")}?${n}`);O(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=h_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=G(o,r),a=await P(i,A("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});O(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}=G(o,r),i=await P(n,A("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});O(o,r,i,()=>console.log("Inference key revoked. Existing streams may finish."))}};var ha=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");ga.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=f_.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}=G(o,r),a=await P(i,t,n);O(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(A("/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=g_.safeParse({key:await bt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(A("/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(A("/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(A("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async usage(t,r){let{config:o}=G(r,t),n=await P(o,A("/api/inference/usage"));O(r,t,n,()=>console.log("Workflow usage is unavailable until proxy metering is connected. No spend totals are being reported."))}};var v_="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 E_}from"node:child_process";import{basename as uE,extname as cE}from"node:path";function __(e){return e.blocking===!0}var Xk=/[.!]+$/u,y_=["clear","issues_found","inconclusive"];var Qk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},b_="blocks merge";var w_="\u2705 Ruled out";function $_(e){return e.replace(Xk,"")}function S_(e){return Qk[e==="do_not_merge"?"do_not_merge":"merge"]}function eE(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function tE(e){return __(e)?"blocking":"non_blocking"}function nE(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function x_(e){let t=eE(e).prFindings,r=t.map(s=>({finding:s,impact:tE(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=nE(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var xp=3e6,Sp=f.string().regex(/^[0-9a-f]{40}$/),rE=["added","modified","removed","renamed"],iE=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(rE),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),oE=f.object({sha:Sp,subject:f.string(),body:f.string()}),mL=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:Sp,headRef:f.string().min(1),headSha:Sp,files:f.array(iE).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(oE),heldBackPaths:f.array(f.string())});function I_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var aE=["running","completed","failed"],sE=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(aE),verdict:f.enum(y_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),fL=f.object({reviews:f.array(sE),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var lE=/^origin\//,dE=/^new file mode /m,pE=/^deleted file mode /m,mE=/^\.\//,fE=/\/+$/,k_=64*1024*1024,gE=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),hE=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),vE=[".example",".sample",".template"];function T_(e={}){let t=e.cwd;if(Fr(["rev-parse","--is-inside-work-tree"],t)!=="true")throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Fr(["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&&!Fr(["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}:_E(t),n=Un(["rev-parse","HEAD"],{cwd:t}),i=Un(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=yE(Om([...s,"--numstat","-z",a],{cwd:t,maxBuffer:k_})),c=kE(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=bE(zn([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:k_}));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(xE)),m=E=>d.has(E)||[...d].some(C=>E.startsWith(`${C}/`)),p=E=>E.previousPath?[E.path,E.previousPath]:[E.path],g=SE(u.flatMap(p),t),_=[],I=[],b=[];if(u.forEach((E,C)=>{let F=l[C]??"";if(E.binary){I.push(E.path);return}if(p(E).some(Q=>$E(Q)||g.has(Q))&&!m(E.path)){b.push(E.path);return}_.push({path:E.path,...E.previousPath?{previousPath:E.previousPath}:{},status:wE(F,E),additions:E.additions,deletions:E.deletions,patch:F})}),_.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 x={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Un(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:I_(_),commitMessages:IE(`${i}..HEAD`,t),heldBackPaths:b.sort()};return EE(x),{payload:x,skippedBinaryPaths:I.sort(),uncommittedPaths:c}}function _E(e){let t=[Fr(["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(Fr(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(lE,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Fr(e,t){try{return E_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).trim()}catch{return null}}function yE(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 bE(e){let t=[],r=null;for(let o of e.split(`
72
72
  `))o.startsWith("diff --git ")?(r&&t.push(`${r.join(`
73
73
  `)}
74
74
  `),r=[o]):r&&r.push(o);return r&&(r[r.length-1]===""&&r.pop(),t.push(`${r.join(`
@@ -82,12 +82,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
82
82
  ${n.message}
83
83
  Hint: ${n.hint??""}
84
84
  `),process.exit(Ne)};for(let n of N_)process.once(n,t);let r=Date.now(),o=r;try{return await An({pollIntervalMs:e.pollIntervalMs,timeoutMs:Ep,timeoutMessage:Tp,fetchStatus:async()=>{let n=M_(await j_(e.config,e.requestId)),i=Date.now();if(n===null&&i-o>=CE){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===Tp?new y("server",Tp,{hint:`The review may still finish. Get its result with \`${e.resumeCommand}\`.`}):n}finally{for(let n of N_)process.off(n,t)}}function D_(e,t,r){let o=De(t.failure?.message??"").trim(),n=t.failure?.code;return new y(e,o.length>0?o:r,{...n?{data:{serverCode:n}}:{}})}async function F_(e,t,r){try{return await(r===void 0?P(e,t):P(e,t,r))}catch(o){if(!(o instanceof ce))throw o;let n=o.data?.serverCode,i=n==="active_request_exists"?zE(o.body):null,a=DE(o,n,t,i),s=i?{...o.data,requestId:i}:o.data;throw new y(o.code,De(o.message),{exitCode:o.exitCode,...a?{hint:a}:{},...o.requestId?{requestId:o.requestId}:{},...s?{data:s}:{}})}}function DE(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 ${De(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===U_?void 0:"Check the id passed to --request.":e.hint}}function zE(e){try{let t=JSON.parse(e);if(typeof t.requestId!="string")return null;let r=N(t.requestId).trim();return r.length>0?r:null}catch{return null}}function UE(e,t){return e?.optsWithGlobals?.()?.quiet===!0||t.quiet===!0?()=>{}:o=>{process.stderr.write(`${o}
85
- `)}}function LE(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(N).join(", ")}`)}function jE(e){let t=e.findings??[];console.log(Vr(e.verdict??"unknown",t)),e.environmentDegradedReason&&console.log(v_);let r=De(e.summary??"").trim();r.length>0&&console.log(r);for(let o of jt(t,{withBody:!0}))console.log(o);for(let o of R_(e.alsoChecked??[]))console.log(o)}function z_(e){let t=N(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 ME}from"node:child_process";import{createHash as FE,randomBytes as ZE}from"node:crypto";var Z_="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function _a(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+=Z_[t[o]%Z_.length];return`${r.slice(0,4)}-${r.slice(4)}`}var BE=2e3,VE=10*6e4;async function B_(e,t){let r=ee(t,e),o=Qr(r.apiUrl),n=Za(r,!1),i=null,a=null;if(e.tokenStdin?i=await bt():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 qE(o,GE(e.scope)))}if(!i.startsWith("arc_"))throw new y("user","Invalid token format. Token must start with 'arc_'.");try{await P({apiUrl:o,token:i},A("/api/auth/whoami"));let s={apiUrl:o,token:i};return Xr(s),e.emitResult===!1||(r.json?qe({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 ce&&(s.status===401||s.status===403)?new y("auth","Token could not be verified. It may be invalid or expired."):s}}function GE(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 qE(e,t){let r=ZE(32).toString("hex"),o=FE("sha256").update(r).digest("hex"),n=`${e}/cli/login?challenge=${o}&scope=${t}`;console.error(`Your code: ${await _a(o)}`),console.error("Opening your browser to sign in. Enter this code on the page to approve."),console.error(`If it does not open, open this URL:
86
- ${n}`),HE(n);let i=Date.now()+VE,a=()=>{process.exit(Ne)};process.once("SIGINT",a);try{for(;Date.now()<i;){let s;try{s=await P({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:r})})}catch(u){throw u instanceof ce&&(u.status===409||u.status===410)?new y("user",u.message):u}if(s.token)return{token:s.token,scope:s.scope??t};await new Promise(u=>setTimeout(u,BE))}}finally{process.off("SIGINT",a)}throw new y("user","Login timed out. Run arcanist auth login again.")}function HE(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]],o=ME(t,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}var Gr=[{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"]}],G_=Gr.length-1,WE="Finishing up";function V_(e){return e?Gr.findIndex(t=>t.stages.includes(e)):-1}function KE(e){if(e.status==="ready")return Gr.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?G_:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=V_(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=V_(o)}return Math.max(t,r)}function q_(e){let t=KE(e);if(t>=Gr.length)return null;let r=[...e.history??[],e.stage];return t===G_&&(r.includes("smoke_passed")||r.includes("completed"))?WE:Gr[t].label}import{createHash as JE,randomUUID as YE}from"node:crypto";import{mkdirSync as XE,readFileSync as QE,rmSync as Ap}from"node:fs";import{homedir as eT}from"node:os";import{join as H_}from"node:path";import tT from"proper-lockfile";var nT=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 W_(e,t,r){let o=H_(eT(),".arcanist");XE(o,{recursive:!0,mode:448});let n=JE("sha256").update(JSON.stringify({apiUrl:e.apiUrl,...t})).digest("hex"),i=H_(o,`onboarding-review-${n}.json`),a;try{a=await tT.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&&Ap(i,{force:!0});let s=null;try{s=nT.parse(JSON.parse(QE(i,"utf8")))}catch(u){if(u.code!=="ENOENT")throw u}if(s||(s={requestId:void 0,idempotencyKey:YE()},_t(i,s)),s.requestId===void 0){let u=await P(e,A("/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},_t(i,s)}try{let u=await P(e,A("/api/pr-reviews/requests/:requestId",{requestId:s.requestId}));return(u.status==="cancelled"||u.status==="admission_rejected")&&Ap(i,{force:!0}),u}catch(u){throw u instanceof ce&&u.status===404&&Ap(i,{force:!0}),u}}finally{await a()}}import{createHash as K_,randomBytes as rT}from"node:crypto";import{chmodSync as iT,mkdirSync as oT,readFileSync as aT,rmSync as sT}from"node:fs";import{homedir as uT}from"node:os";import{join as J_}from"node:path";import cT from"proper-lockfile";var lT=f.object({verifier:f.string().regex(/^[a-f0-9]{64}$/),expiresAt:f.number()}),dT=10*6e4;async function Y_(e,t,r){let o=J_(uT(),".arcanist");oT(o,{recursive:!0,mode:448});let n=J_(o,`login-${K_("sha256").update(e).digest("hex")}.json`),i;try{i=await cT.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=Nn({json:!0});if(a?.apiUrl===e&&a.token!==r)return{status:"approved",config:a};let s=null;try{s=lT.parse(JSON.parse(aT(n,"utf8")))}catch(c){if(c.code!=="ENOENT")throw c}if(s){iT(n,384);try{let c=await P({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:s.verifier})});if(c.token){let l={apiUrl:e,token:c.token};return Xr(l,t),sT(n,{force:!0}),{status:"approved",config:l}}s.expiresAt<=Date.now()&&(s=null)}catch(c){if(!(c instanceof ce)||c.status!==410)throw c;s=null}}s||(s={verifier:rT(32).toString("hex"),expiresAt:Date.now()+dT},_t(n,s));let u=K_("sha256").update(s.verifier).digest("hex");return{status:"approval_required",authorizationUrl:`${e}/cli/login?challenge=${u}&scope=write`,approvalCode:await _a(u),expiresAt:s.expiresAt}}finally{await i()}}async function ya(e,t,r){let o=ee(r,t),n=He(e),i=`${n.owner}/${n.repo}`;if(t.restartReview&&!t.pr)throw new y("user","--restart-review requires --pr.");let a=t.pr===void 0?null:Rm(t.pr);if(t.pr!==void 0&&(!a||`${a.owner}/${a.repo}`.toLowerCase()!==i.toLowerCase()))throw new y("user","--pr must be a GitHub pull request URL in the repository being onboarded.");let s=`arcanist onboard ${i}${a?` --pr ${a.prUrl}`:""}${o.apiUrl?` --api-url ${Qe(o.apiUrl)}`:""} --json`,u=Nn(o),c=u?.token,l=u?.apiUrl??Qr(o.apiUrl),d=null;if(u)try{d=await P(u,A("/api/auth/whoami")),d.tokenScope!=="write"&&(u=null)}catch(b){if(!(b instanceof ce)||b.status!==401)throw b;u=null}if(!u){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 b=Fa(),x=await Y_(l,b?.apiUrl===l?b.token:void 0,c);if(x.status==="approval_required"){O(r,t,{...x,message:`One quick approval, then your agent can take it from here. Open this link, enter code ${x.approvalCode} to connect Arcanist, then return to your agent.`,command:s},E=>{console.log(E.message),console.log(E.authorizationUrl),console.log(`Code: ${E.approvalCode}`),console.log(`Then run: ${E.command}`)});return}u=x.config,d=await P(u,A("/api/auth/whoami"))}if(!d?.businessId||d.tokenScope!=="write")throw new y("auth","Onboarding needs write access to a workspace. Run arcanist onboard again to request it.");let m=(b,x,E=s)=>{O(r,t,{status:"github_approval_required",authorizationUrl:b,command:E,resumeCommand:s,message:x},C=>{console.log(C.message),console.log(C.authorizationUrl),console.log(`Then run: ${C.command}`)})},p;try{p=await et(u,i)}catch(b){if(!(b instanceof ce)||b.data?.serverCode!=="github_not_connected")throw b;let x=new URL("/auth/github/connect",u.apiUrl);x.searchParams.set("returnTo","/cli/onboarding"),m(x.toString(),"Connect your GitHub account, then resume onboarding.");return}let g=`Approve Arcanist access to ${i} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(p.nextAction==="prepare"){let[b]=await $p(u,{repositories:[n]});if(!b)throw new y("server","Environment setup returned no repository result.");if(b.status==="failed"&&b.reason==="installation_github_permissions_required"){if(d.businessRole!=="admin")throw new y("auth",Mr);g=Mr,p={...p,nextAction:"authorize_github"}}else if(b.status==="forbidden"){if(b.reason==="repository_limit"||d.businessRole!=="admin")throw new y("auth",`Cannot prepare ${i}: ${b.reason??"repository access required"}.`);p={...p,nextAction:"authorize_github"}}else{if(b.status==="failed"&&b.reason==="installation_github_check_failed")throw new y("server",pa);if(b.status==="failed")throw new y("server",`Could not start setup for ${i}.`);p=await et(u,i)}}if(p.nextAction==="authorize_github"){let b=await P(u,A("/api/onboarding/github-installation"));m(b.authorizationUrl,g,p.status==="failed"?`arcanist environments retry ${i}${o.apiUrl?` --api-url ${Qe(u.apiUrl)}`:""} --json`:s);return}if(p.command&&o.apiUrl&&(p={...p,command:`${p.command} --api-url ${Qe(u.apiUrl)}`}),p.nextAction==="review"&&a){let b=await W_(u,{businessId:d.businessId,userId:d.userId,prUrl:a.prUrl},t.restartReview===!0);if(b.status==="cancelled"||b.status==="admission_rejected")throw new y("user",b.terminalReason??`First review ${b.status}.`);let x=b.status==="completed"&&(b.verdict==="clear"||b.verdict==="issues_found")&&!!b.headSha,E=x?`You're set. Arcanist has completed its first review of ${i}. ${b.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:b.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 ${i}. Your agent can follow its progress; nothing is needed from you right now.`;O(r,t,{message:E,status:x?"complete":b.status==="completed"?"review_needs_attention":"review_pending",repository:p,reviewVerified:x,review:b,pullRequestUrl:a.prUrl,command:b.status==="completed"?null:s},C=>{console.log(C.message),console.log(a.prUrl),C.command&&console.log(`Continue with: ${C.command}`)});return}let I={review:`${i} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${q_({...p,status:p.status==="not_started"?"pending":p.status})??"Configuring the environment"} for ${i}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${i}. Your agent will share the question and continue with your answer.`,add_credentials:`${i} needs credentials to finish setup. Your agent will explain which ones are needed and help you provide them.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${i}. Your progress is saved.`,retry:`Setup for ${i} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${i}.`,authorize_github:`GitHub access is needed for ${i}.`}[p.nextAction];O(r,t,{message:I,status:p.nextAction==="review"?"repository_ready":p.nextAction==="wait"?"setup_pending":"action_required",repository:p,reviewVerified:!1,command:p.nextAction==="wait"?s:p.command,resumeCommand:s},b=>{console.log(b.message),b.command&&console.log(`Continue with: ${b.command}`)})}async function X_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await bt();if(!o)throw new y("user","The answer must not be empty.");let n=He(e),{config:i}=G(r,t);if((await et(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 P(i,A("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});O(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function Q_(e,t,r){if(!t.entriesStdin)throw new y("user","Supply a JSON object of requested credentials through --entries-stdin.");let o;try{o=f.record(f.string(),f.string()).parse(JSON.parse(await bt()))}catch{throw new y("user","Expected a JSON object mapping credential names to string values on stdin.")}let n=He(e),{config:i}=G(r,t),a=await et(i,`${n.owner}/${n.repo}`);if(a.secretRequest?.id!==t.request)throw new y("conflict","That credential request is no longer pending. Run arcanist onboard again.");await P(i,A("/api/environments/:id/secret-requests/:requestId",{id:a.secretRequest.environmentId,requestId:t.request}),{method:"POST",body:JSON.stringify({entries:o,...t.comment?{comment:t.comment}:{}})}),O(r,t,{ok:!0},()=>console.log("Credentials submitted. Run arcanist onboard to continue."))}async function ey(e={},t){let{config:r}=G(t,e),o=await P(r,A("/api/repos"));O(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 ty(e,t,r){let o=ee(r,t),n=_e(o),[i,a]=await Promise.all([P(n,A("/api/pr-reviews/requests/:requestId",{requestId:e})),P(n,A("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);O(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(De(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of jt(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=N(l);console.log(`Next: arcanist sessions view ${d}`)}})}var ny=["published","publish_failed","gate_rejected"],ry=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var iy=["bundle","ledger","disposition","lineage"];var pT=/^\d{1,3}$/,mT=/^fe[89ab]/,fT=/^f[cd]/,gT=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,hT=/^\[/,vT=/\]$/;var oy=300,qr=500,Rp=3,_T=6e3;var ay=/^dl-[0-9a-f]{8}$/,yT=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function Pp(e){let t=e.split(".");if(t.length===4&&t.every(r=>pT.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"||mT.test(r)||fT.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(gT);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return Pp(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return Pp(o)}return!1}return!1}function bT(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(hT,"").replace(vT,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!yT.has(r)&&!Pp(r)}catch{return!1}}var a0=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(oy)}).strict(),f.object({kind:f.literal("fetch"),url:f.string().url().max(qr).refine(bT,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(oy).optional(),offset:f.number().int().min(0).optional()}).strict()]),wT=f.object({url:f.string().max(qr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(_T)}).strict(),s0=f.object({results:f.array(wT).max(Rp)}).strict();var sy=f.string().regex(/^q-[1-9][0-9]*$/).max(16);var Cp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],f0=f.object({lookupId:f.string().regex(ay),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(qr),status:f.enum(Cp),resultUrls:f.array(f.string().max(qr)).max(Rp),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:sy.optional()}).strict();var Op="zeus_telemetry";var uy=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],cy={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"},$T={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},T0={"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:ry},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:ny},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",...iy]}},"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:uy},effort:"string",stall:{kind:"object",fields:cy},codexTcpSockets:{kind:"object",fields:$T}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:uy},stall:{kind:"object",fields:cy},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:Cp},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 ly=["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"],dy=["observed"],py=["sandbox_bridge","control_plane"],my=["started","completed","failed","skipped","blocked"];var ST=["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"],Np=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Te(e){return typeof e=="number"&&Number.isFinite(e)}function X(e){return e===void 0||typeof e=="string"}function fy(e){return e===void 0||L(e)}function ba(e){return e==null||typeof e=="string"}function je(e,t){return typeof e=="string"&&t.includes(e)}function xT(e){return typeof e=="string"||L(e)&&typeof e.label=="string"&&X(e.description)}function ue(e){return L(e)?X(e.bridgeEventType)&&!gy(e)&&fy(e.bridgeData):!1}function gy(e){return L(e)?typeof e.bridgeEventType=="string"&&Np.has(e.bridgeEventType):!1}function wa(e,t){if(!L(t))return!1;switch(e){case"session.create":return ue(t)&&je(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||je(t.sessionKind,["repo"]));case"sandbox.spawn":return ue(t)&&je(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Te(t.attempt))&&X(t.reason);case"bridge.connect":return ue(t)&&je(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!gy(t)&&fy(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ue(t)&&ba(t.actorUserId)&&X(t.agent)&&ba(t.model);case"prompt.context":return ue(t);case"prompt.dispatch":return ue(t)&&ba(t.startupAttemptId);case"agent.session.create":return ue(t)&&je(t.status,["started","complete","failed"])&&X(t.agentSessionId)&&X(t.agent);case"tool.call":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&X(t.summary)&&(t.args===void 0||L(t.args));case"tool.result":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&X(t.error);case"text.delta":return ue(t)&&je(t.channel,["output","reasoning"])&&typeof t.text=="string"&&X(t.partId);case"prompt.complete":return ue(t)&&typeof t.success=="boolean"&&X(t.error)&&X(t.errorCode);case"git.push":return ue(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&X(t.error);case"pr.open":return ue(t)&&typeof t.success=="boolean"&&X(t.prUrl)&&(t.prNumber===void 0||Te(t.prNumber))&&X(t.error);case"timeline":return ue(t)&&je(t.eventType,ly)&&je(t.source,dy)&&je(t.observer,py)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||je(t.status,my))&&(t.metadata===void 0||L(t.metadata));case"error":return ue(t)&&typeof t.message=="string"&&X(t.code);case"user_question":return ue(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(xT));case"idle":return ue(t)&&(t.sessionEditCount===void 0||Te(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Te(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function IT(e){return typeof e=="string"&&ST.includes(e)}function hy(e){if(!L(e))throw new Error("Invalid ArcanistEvent");if(!IT(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(!L(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)?kT(e.phase,e.payload):wa(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function kT(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Te(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Te(t[o]))return!1;if(!X(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return ET(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")&&X(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return ba(t.startupAttemptId);case"prompt_accepted":return X(t.startupAttemptId);case"agent_prompt_sent":return X(t.startupAttemptId)&&X(t.agentSessionId)&&X(t.agentRuntimeBackend);case"prompt_activity":return je(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&X(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 wa(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return wa(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&X(t.btSpanId);default:return wa(e,t)}}function ET(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return X(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return L(e.runtime);case"sandbox_undersized":return Te(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||Te(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Te(e[t]));case"estimated_input_composition":return L(e.components);case"retry_status":return Te(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||Te(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Te(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Te(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=>L(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 vy(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 Dp(e,t){if(!L(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return hy(e);if(typeof e.phase=="string"&&L(e.payload)){let m=e,p=e.payload;if(!L(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let g=L(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:I,...b}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...g,...b}};let x=typeof p.bridgeEventType=="string"?p.bridgeEventType:vy(m),E=m.phase==="text.delta"&&x==="text"?"token":m.phase==="prompt.dispatch"&&x==="prompt_processing"?"prompt_accepted":x,C=Dp({...g,type:E,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??g.messageId,promptId:m.promptId??g.promptId,ackId:e.ackId},m.sessionId??"");return C.phase==="bridge.connect"&&C.payload.kind==="heartbeat"&&delete b.status,b.startupAttemptId===null&&delete b.startupAttemptId,{...C,payload:{...C.payload,...b}}}if(typeof e.type!="string"||Np.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=L(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,...g}=u;l="error",d={...g,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 _y=["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"],Z0=_y.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),TT=["started","succeeded","failed"],AT=200;function PT(e){return typeof e=="string"&&_y.includes(e)}function RT(e){return typeof e=="string"&&TT.includes(e)}function yy(e){if(!L(e))return null;let t=e;if(!PT(t.stage))return null;let r=RT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,AT);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var CT="Arcanist blocked this malformed search command before execution.",OT=/\/bin\/bash:\s+-c:\s+line\s+\d+:\s+unexpected EOF while looking for matching [`'\"][`'\"]?/i,NT=24,DT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function $a(e){return"phase"in e&&typeof e.phase=="string"}var by=new WeakMap;function Sa(e){let t=by.get(e);return t||(t=Dp(e),by.set(e,t)),t}function xa(e){return Sa(e).payload}function zT(e){let t=xa(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function ky(e){return xa(e).kind}function Ey(e){return Sa(e).promptId}function de(e,t){let r=Ey(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function UT(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}:{},...L(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 Hr(e){return $a(e)?Ey(e):L(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function Rn(e){if(!$a(e))return e.type;let t=xa(e),r=ky(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(Sa(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 LT(e){if($a(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=L(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 jT(e){let t=LT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function Up(e){if(!$a(e))return L(e.data)?e.data:void 0;let t=xa(e),r=ky(e),o=de(e,zT(e));switch(Sa(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:L(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 UT(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}:{},...L(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 Ty(e){let t=Up(e);return{raw:e,type:Rn(e),data:t,promptId:Hr(e)}}function wy(e){return e.map(t=>Ty(t))}function MT(e,t){return t?t.length<NT?!0:!e.endsWith(t):!1}function FT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function ZT(e,t){return`${e}:${t}`}function $y(e,t){return t===0?e:`${e}#${t}`}function Mt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function BT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function VT(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(!VT(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 qT(e,t,r,o,n,i,a){let s=ZT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=MT(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:$y(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:$y(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 zp(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function WT(e,t){let r=zp(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...L(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function KT(){return{merged:[],streams:FT(),toolCallIndexById:new Map,agentProgressIndexByKey:new Map,questionIndexById:new Map,narrationIndex:null,malformedSearchBlockedPromptIds:new Set,malformedSearchBlockedWithoutPrompt:!1}}function JT(e){return typeof e=="string"&&e.includes(CT)}function YT(e){return OT.test(e)}function XT(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)&&YT(t.text)))}function Oe(e,t){t&&e.merged.push(t)}function QT(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function eA(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 tA(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 nA(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 rA(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 iA(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 oA(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}=iA(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 aA(e,t){let r=typeof e?.eventName=="string"?e.eventName:Op;return{type:Op,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function sA(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}:{},...L(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function uA(e,t){let r=V(e);return{type:"agent_progress",id:Mt(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 cA(e,t){let r=uA(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 lA(e,t){return{type:"session_error",id:Mt(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 dA(e,t){if(e?.code!=="malformed_search_command"&&!JT(e?.error))return;let r=V(e);r?t.malformedSearchBlockedPromptIds.add(r):t.malformedSearchBlockedWithoutPrompt=!0}function pA(e,t){return{type:"session_resumed_cold",id:Mt(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 mA(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&&DT.has(o)?null:{type:"raw_agent_runtime",id:Mt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function fA(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 Sy(e,t,r,o){qT(r.merged,r.streams,e,Mt(t,e,r.merged.length),BT(t),V(t),o)}function gA(e,t){let r=Mt(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=zp(e?.toolStatus),a=L(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}:{},...L(e?.failure)?{failure:e.failure}:{}};t.merged[o]=HT(n,s)}}else{let n=zp(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)}:{},...L(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}:{},...L(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function hA(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]=WT(n,e))}function vA(e,t){let r={type:"question",id:Mt(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 _A(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 yA(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 bA(e,t){let r=yy(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 wA(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 Ay(e){let t=KT();for(let r of e){let o=Ty(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Oe(t,QT(i,t.merged.length));break;case"sandbox_compaction_complete":Oe(t,eA(i,t.merged.length));break;case"sandbox_context_fill_warning":Oe(t,tA(i,t.merged.length));break;case"sandbox_tool_truncated":Oe(t,nA(i,t.merged.length));break;case"retry_status":Oe(t,rA(i,t.merged.length));break;case"prompt_retrying":Oe(t,oA(i,t.merged.length));break;case"zeus_telemetry":Oe(t,aA(i,t.merged.length));break;case"agent_timeline":Oe(t,sA(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":cA(i,t);break;case"session_error":dA(i,t),Oe(t,lA(i,t.merged.length));break;case"session_resumed_cold":Oe(t,pA(i,t.merged.length));break;case"raw_agent_runtime":Oe(t,mA(i,t.merged.length));break;case"reasoning":Sy("reasoning",i,t,jT(o.raw));break;case"text":Sy("text",i,t);break;case"patch":Oe(t,fA(i,t.merged.length));break;case"todo_update":yA(i,t);break;case"answer":_A(i,t);break;case"tool_call":gA(i,t);break;case"tool_update":hA(i,t);break;case"question":vA(i,t);break;case"narration":wA(i,t);break;case"onboarding_status":bA(i,t);break}}return XT(t)}function Py(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Hr(i),s=typeof a=="string"&&r.has(a)?a:null;Rn(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function $A(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 xy(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function Iy(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function Ry(e){let t=wy(e),r=$A(t),o=t.filter(b=>b.type==="prompt_activity"),n=t.filter(b=>b.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=wy(r),a=i.filter(b=>b.type==="prompt_activity"),s=i.filter(b=>b.type==="agent_progress"),u=new Set(a.map(xy)),c=new Set(s.map(Iy)),l=a.length,d=s.length,m=0,p=0,g=o.filter(b=>{let x=xy(b);return u.has(x)?(m+=1,!1):(u.add(x),!0)}),_=n.filter(b=>{let x=Iy(b);return c.has(x)?(p+=1,!1):(c.add(x),!0)}),I=[...g,..._].map(b=>b.raw);return{events:I.length>0?[...I,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:g.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var Cy=1e3;async function Oy(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>Cy)throw new y("user",`${e} exceeded ${Cy} 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 Ia(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function Ny(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function ka(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 SA="## Previously declined findings on this repository (calibration)",xA="## Findings already reported by other reviewers",IA="## Graphite stack neighbours",Dy=[SA,xA,IA,"## Independent review suggestions"];var Uy=/\r?\n/,kA=/\n{3,}/g,EA=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,TA=[/^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],AA=[/<\/?(?: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],PA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function RA(e){let t=e.split(Uy),r=[],o=[];if(t.forEach((a,s)=>{let u=Dy.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(`
87
- `).trim()}function zy(e){return AA.some(t=>t.test(e))}function CA(e){return e.replace(EA,"").split(Uy).filter(o=>!TA.some(n=>n.test(o.trim()))).join(`
88
- `).replace(kA,`
85
+ `)}}function LE(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(N).join(", ")}`)}function jE(e){let t=e.findings??[];console.log(Vr(e.verdict??"unknown",t)),e.environmentDegradedReason&&console.log(v_);let r=De(e.summary??"").trim();r.length>0&&console.log(r);for(let o of jt(t,{withBody:!0}))console.log(o);for(let o of R_(e.alsoChecked??[]))console.log(o)}function z_(e){let t=N(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 FE}from"node:child_process";import{createHash as ZE,randomBytes as BE}from"node:crypto";var Z_="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function _a(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+=Z_[t[o]%Z_.length];return ME(r)}function ME(e){return`${e.slice(0,4)}-${e.slice(4)}`}var VE=2e3,GE=10*6e4;async function B_(e,t){let r=ee(t,e),o=Qr(r.apiUrl),n=Za(r,!1),i=null,a=null;if(e.tokenStdin?i=await bt():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 HE(o,qE(e.scope)))}if(!i.startsWith("arc_"))throw new y("user","Invalid token format. Token must start with 'arc_'.");try{await P({apiUrl:o,token:i},A("/api/auth/whoami"));let s={apiUrl:o,token:i};return Xr(s),e.emitResult===!1||(r.json?qe({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 ce&&(s.status===401||s.status===403)?new y("auth","Token could not be verified. It may be invalid or expired."):s}}function qE(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 HE(e,t){let r=BE(32).toString("hex"),o=ZE("sha256").update(r).digest("hex"),n=`${e}/cli/login?challenge=${o}&scope=${t}`;console.error(`Your code: ${await _a(o)}`),console.error("Opening your browser to sign in. Enter this code on the page to approve."),console.error(`If it does not open, open this URL:
86
+ ${n}`),WE(n);let i=Date.now()+GE,a=()=>{process.exit(Ne)};process.once("SIGINT",a);try{for(;Date.now()<i;){let s;try{s=await P({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:r})})}catch(u){throw u instanceof ce&&(u.status===409||u.status===410)?new y("user",u.message):u}if(s.token)return{token:s.token,scope:s.scope??t};await new Promise(u=>setTimeout(u,VE))}}finally{process.off("SIGINT",a)}throw new y("user","Login timed out. Run arcanist auth login again.")}function WE(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]],o=FE(t,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}var Gr=[{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"]}],G_=Gr.length-1,KE="Finishing up";function V_(e){return e?Gr.findIndex(t=>t.stages.includes(e)):-1}function JE(e){if(e.status==="ready")return Gr.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?G_:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=V_(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=V_(o)}return Math.max(t,r)}function q_(e){let t=JE(e);if(t>=Gr.length)return null;let r=[...e.history??[],e.stage];return t===G_&&(r.includes("smoke_passed")||r.includes("completed"))?KE:Gr[t].label}import{createHash as YE,randomUUID as XE}from"node:crypto";import{mkdirSync as QE,readFileSync as eT,rmSync as Ap}from"node:fs";import{homedir as tT}from"node:os";import{join as H_}from"node:path";import nT from"proper-lockfile";var rT=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 W_(e,t,r){let o=H_(tT(),".arcanist");QE(o,{recursive:!0,mode:448});let n=YE("sha256").update(JSON.stringify({apiUrl:e.apiUrl,...t})).digest("hex"),i=H_(o,`onboarding-review-${n}.json`),a;try{a=await nT.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&&Ap(i,{force:!0});let s=null;try{s=rT.parse(JSON.parse(eT(i,"utf8")))}catch(u){if(u.code!=="ENOENT")throw u}if(s||(s={requestId:void 0,idempotencyKey:XE()},_t(i,s)),s.requestId===void 0){let u=await P(e,A("/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},_t(i,s)}try{let u=await P(e,A("/api/pr-reviews/requests/:requestId",{requestId:s.requestId}));return(u.status==="cancelled"||u.status==="admission_rejected")&&Ap(i,{force:!0}),u}catch(u){throw u instanceof ce&&u.status===404&&Ap(i,{force:!0}),u}}finally{await a()}}import{createHash as K_,randomBytes as iT}from"node:crypto";import{chmodSync as oT,mkdirSync as aT,readFileSync as sT,rmSync as uT}from"node:fs";import{homedir as cT}from"node:os";import{join as J_}from"node:path";import lT from"proper-lockfile";var dT=f.object({verifier:f.string().regex(/^[a-f0-9]{64}$/),expiresAt:f.number()}),pT=10*6e4;async function Y_(e,t,r){let o=J_(cT(),".arcanist");aT(o,{recursive:!0,mode:448});let n=J_(o,`login-${K_("sha256").update(e).digest("hex")}.json`),i;try{i=await lT.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=Nn({json:!0});if(a?.apiUrl===e&&a.token!==r)return{status:"approved",config:a};let s=null;try{s=dT.parse(JSON.parse(sT(n,"utf8")))}catch(c){if(c.code!=="ENOENT")throw c}if(s){oT(n,384);try{let c=await P({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:s.verifier})});if(c.token){let l={apiUrl:e,token:c.token};return Xr(l,t),uT(n,{force:!0}),{status:"approved",config:l}}s.expiresAt<=Date.now()&&(s=null)}catch(c){if(!(c instanceof ce)||c.status!==410)throw c;s=null}}s||(s={verifier:iT(32).toString("hex"),expiresAt:Date.now()+pT},_t(n,s));let u=K_("sha256").update(s.verifier).digest("hex");return{status:"approval_required",authorizationUrl:`${e}/cli/login?challenge=${u}&scope=write`,approvalCode:await _a(u),expiresAt:s.expiresAt}}finally{await i()}}async function ya(e,t,r){let o=ee(r,t),n=He(e),i=`${n.owner}/${n.repo}`;if(t.restartReview&&!t.pr)throw new y("user","--restart-review requires --pr.");let a=t.pr===void 0?null:Rm(t.pr);if(t.pr!==void 0&&(!a||`${a.owner}/${a.repo}`.toLowerCase()!==i.toLowerCase()))throw new y("user","--pr must be a GitHub pull request URL in the repository being onboarded.");let s=`arcanist onboard ${i}${a?` --pr ${a.prUrl}`:""}${o.apiUrl?` --api-url ${Qe(o.apiUrl)}`:""} --json`,u=Nn(o),c=u?.token,l=u?.apiUrl??Qr(o.apiUrl),d=null;if(u)try{d=await P(u,A("/api/auth/whoami")),d.tokenScope!=="write"&&(u=null)}catch(b){if(!(b instanceof ce)||b.status!==401)throw b;u=null}if(!u){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 b=Fa(),x=await Y_(l,b?.apiUrl===l?b.token:void 0,c);if(x.status==="approval_required"){O(r,t,{...x,message:`One quick approval, then your agent can take it from here. Open this link, enter code ${x.approvalCode} to connect Arcanist, then return to your agent.`,command:s},E=>{console.log(E.message),console.log(E.authorizationUrl),console.log(`Code: ${E.approvalCode}`),console.log(`Then run: ${E.command}`)});return}u=x.config,d=await P(u,A("/api/auth/whoami"))}if(!d?.businessId||d.tokenScope!=="write")throw new y("auth","Onboarding needs write access to a workspace. Run arcanist onboard again to request it.");let m=(b,x,E=s)=>{O(r,t,{status:"github_approval_required",authorizationUrl:b,command:E,resumeCommand:s,message:x},C=>{console.log(C.message),console.log(C.authorizationUrl),console.log(`Then run: ${C.command}`)})},p;try{p=await et(u,i)}catch(b){if(!(b instanceof ce)||b.data?.serverCode!=="github_not_connected")throw b;let x=new URL("/auth/github/connect",u.apiUrl);x.searchParams.set("returnTo","/cli/onboarding"),m(x.toString(),"Connect your GitHub account, then resume onboarding.");return}let g=`Approve Arcanist access to ${i} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(p.nextAction==="prepare"){let[b]=await $p(u,{repositories:[n]});if(!b)throw new y("server","Environment setup returned no repository result.");if(b.status==="failed"&&b.reason==="installation_github_permissions_required"){if(d.businessRole!=="admin")throw new y("auth",Mr);g=Mr,p={...p,nextAction:"authorize_github"}}else if(b.status==="forbidden"){if(b.reason==="repository_limit"||d.businessRole!=="admin")throw new y("auth",`Cannot prepare ${i}: ${b.reason??"repository access required"}.`);p={...p,nextAction:"authorize_github"}}else{if(b.status==="failed"&&b.reason==="installation_github_check_failed")throw new y("server",pa);if(b.status==="failed")throw new y("server",`Could not start setup for ${i}.`);p=await et(u,i)}}if(p.nextAction==="authorize_github"){let b=await P(u,A("/api/onboarding/github-installation"));m(b.authorizationUrl,g,p.status==="failed"?`arcanist environments retry ${i}${o.apiUrl?` --api-url ${Qe(u.apiUrl)}`:""} --json`:s);return}if(p.command&&o.apiUrl&&(p={...p,command:`${p.command} --api-url ${Qe(u.apiUrl)}`}),p.nextAction==="review"&&a){let b=await W_(u,{businessId:d.businessId,userId:d.userId,prUrl:a.prUrl},t.restartReview===!0);if(b.status==="cancelled"||b.status==="admission_rejected")throw new y("user",b.terminalReason??`First review ${b.status}.`);let x=b.status==="completed"&&(b.verdict==="clear"||b.verdict==="issues_found")&&!!b.headSha,E=x?`You're set. Arcanist has completed its first review of ${i}. ${b.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:b.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 ${i}. Your agent can follow its progress; nothing is needed from you right now.`;O(r,t,{message:E,status:x?"complete":b.status==="completed"?"review_needs_attention":"review_pending",repository:p,reviewVerified:x,review:b,pullRequestUrl:a.prUrl,command:b.status==="completed"?null:s},C=>{console.log(C.message),console.log(a.prUrl),C.command&&console.log(`Continue with: ${C.command}`)});return}let I={review:`${i} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${q_({...p,status:p.status==="not_started"?"pending":p.status})??"Configuring the environment"} for ${i}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${i}. Your agent will share the question and continue with your answer.`,add_credentials:`${i} needs credentials to finish setup. Your agent will explain which ones are needed and help you provide them.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${i}. Your progress is saved.`,retry:`Setup for ${i} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${i}.`,authorize_github:`GitHub access is needed for ${i}.`}[p.nextAction];O(r,t,{message:I,status:p.nextAction==="review"?"repository_ready":p.nextAction==="wait"?"setup_pending":"action_required",repository:p,reviewVerified:!1,command:p.nextAction==="wait"?s:p.command,resumeCommand:s},b=>{console.log(b.message),b.command&&console.log(`Continue with: ${b.command}`)})}async function X_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await bt();if(!o)throw new y("user","The answer must not be empty.");let n=He(e),{config:i}=G(r,t);if((await et(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 P(i,A("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});O(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function Q_(e,t,r){if(!t.entriesStdin)throw new y("user","Supply a JSON object of requested credentials through --entries-stdin.");let o;try{o=f.record(f.string(),f.string()).parse(JSON.parse(await bt()))}catch{throw new y("user","Expected a JSON object mapping credential names to string values on stdin.")}let n=He(e),{config:i}=G(r,t),a=await et(i,`${n.owner}/${n.repo}`);if(a.secretRequest?.id!==t.request)throw new y("conflict","That credential request is no longer pending. Run arcanist onboard again.");await P(i,A("/api/environments/:id/secret-requests/:requestId",{id:a.secretRequest.environmentId,requestId:t.request}),{method:"POST",body:JSON.stringify({entries:o,...t.comment?{comment:t.comment}:{}})}),O(r,t,{ok:!0},()=>console.log("Credentials submitted. Run arcanist onboard to continue."))}async function ey(e={},t){let{config:r}=G(t,e),o=await P(r,A("/api/repos"));O(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 ty(e,t,r){let o=ee(r,t),n=_e(o),[i,a]=await Promise.all([P(n,A("/api/pr-reviews/requests/:requestId",{requestId:e})),P(n,A("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);O(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(De(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of jt(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=N(l);console.log(`Next: arcanist sessions view ${d}`)}})}var ny=["published","publish_failed","gate_rejected"],ry=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var iy=["bundle","ledger","disposition","lineage"];var mT=/^\d{1,3}$/,fT=/^fe[89ab]/,gT=/^f[cd]/,hT=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,vT=/^\[/,_T=/\]$/;var oy=300,qr=500,Rp=3,yT=6e3;var ay=/^dl-[0-9a-f]{8}$/,bT=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function Pp(e){let t=e.split(".");if(t.length===4&&t.every(r=>mT.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"||fT.test(r)||gT.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(hT);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return Pp(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return Pp(o)}return!1}return!1}function wT(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(vT,"").replace(_T,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!bT.has(r)&&!Pp(r)}catch{return!1}}var s0=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(oy)}).strict(),f.object({kind:f.literal("fetch"),url:f.string().url().max(qr).refine(wT,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(oy).optional(),offset:f.number().int().min(0).optional()}).strict()]),$T=f.object({url:f.string().max(qr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(yT)}).strict(),u0=f.object({results:f.array($T).max(Rp)}).strict();var sy=f.string().regex(/^q-[1-9][0-9]*$/).max(16);var Cp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],g0=f.object({lookupId:f.string().regex(ay),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(qr),status:f.enum(Cp),resultUrls:f.array(f.string().max(qr)).max(Rp),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:sy.optional()}).strict();var Op="zeus_telemetry";var uy=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],cy={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"},ST={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},A0={"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:ry},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:ny},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",...iy]}},"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:uy},effort:"string",stall:{kind:"object",fields:cy},codexTcpSockets:{kind:"object",fields:ST}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:uy},stall:{kind:"object",fields:cy},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:Cp},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 ly=["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"],dy=["observed"],py=["sandbox_bridge","control_plane"],my=["started","completed","failed","skipped","blocked"];var xT=["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"],Np=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Te(e){return typeof e=="number"&&Number.isFinite(e)}function X(e){return e===void 0||typeof e=="string"}function fy(e){return e===void 0||L(e)}function ba(e){return e==null||typeof e=="string"}function je(e,t){return typeof e=="string"&&t.includes(e)}function IT(e){return typeof e=="string"||L(e)&&typeof e.label=="string"&&X(e.description)}function ue(e){return L(e)?X(e.bridgeEventType)&&!gy(e)&&fy(e.bridgeData):!1}function gy(e){return L(e)?typeof e.bridgeEventType=="string"&&Np.has(e.bridgeEventType):!1}function wa(e,t){if(!L(t))return!1;switch(e){case"session.create":return ue(t)&&je(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||je(t.sessionKind,["repo"]));case"sandbox.spawn":return ue(t)&&je(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Te(t.attempt))&&X(t.reason);case"bridge.connect":return ue(t)&&je(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!gy(t)&&fy(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ue(t)&&ba(t.actorUserId)&&X(t.agent)&&ba(t.model);case"prompt.context":return ue(t);case"prompt.dispatch":return ue(t)&&ba(t.startupAttemptId);case"agent.session.create":return ue(t)&&je(t.status,["started","complete","failed"])&&X(t.agentSessionId)&&X(t.agent);case"tool.call":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&X(t.summary)&&(t.args===void 0||L(t.args));case"tool.result":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&X(t.error);case"text.delta":return ue(t)&&je(t.channel,["output","reasoning"])&&typeof t.text=="string"&&X(t.partId);case"prompt.complete":return ue(t)&&typeof t.success=="boolean"&&X(t.error)&&X(t.errorCode);case"git.push":return ue(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&X(t.error);case"pr.open":return ue(t)&&typeof t.success=="boolean"&&X(t.prUrl)&&(t.prNumber===void 0||Te(t.prNumber))&&X(t.error);case"timeline":return ue(t)&&je(t.eventType,ly)&&je(t.source,dy)&&je(t.observer,py)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||je(t.status,my))&&(t.metadata===void 0||L(t.metadata));case"error":return ue(t)&&typeof t.message=="string"&&X(t.code);case"user_question":return ue(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(IT));case"idle":return ue(t)&&(t.sessionEditCount===void 0||Te(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Te(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function kT(e){return typeof e=="string"&&xT.includes(e)}function hy(e){if(!L(e))throw new Error("Invalid ArcanistEvent");if(!kT(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(!L(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)?ET(e.phase,e.payload):wa(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function ET(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Te(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Te(t[o]))return!1;if(!X(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return TT(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")&&X(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return ba(t.startupAttemptId);case"prompt_accepted":return X(t.startupAttemptId);case"agent_prompt_sent":return X(t.startupAttemptId)&&X(t.agentSessionId)&&X(t.agentRuntimeBackend);case"prompt_activity":return je(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&X(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 wa(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return wa(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&X(t.btSpanId);default:return wa(e,t)}}function TT(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return X(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return L(e.runtime);case"sandbox_undersized":return Te(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||Te(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Te(e[t]));case"estimated_input_composition":return L(e.components);case"retry_status":return Te(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||Te(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Te(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Te(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=>L(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 vy(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 Dp(e,t){if(!L(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return hy(e);if(typeof e.phase=="string"&&L(e.payload)){let m=e,p=e.payload;if(!L(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let g=L(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:I,...b}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...g,...b}};let x=typeof p.bridgeEventType=="string"?p.bridgeEventType:vy(m),E=m.phase==="text.delta"&&x==="text"?"token":m.phase==="prompt.dispatch"&&x==="prompt_processing"?"prompt_accepted":x,C=Dp({...g,type:E,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??g.messageId,promptId:m.promptId??g.promptId,ackId:e.ackId},m.sessionId??"");return C.phase==="bridge.connect"&&C.payload.kind==="heartbeat"&&delete b.status,b.startupAttemptId===null&&delete b.startupAttemptId,{...C,payload:{...C.payload,...b}}}if(typeof e.type!="string"||Np.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=L(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,...g}=u;l="error",d={...g,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 _y=["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"],B0=_y.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),AT=["started","succeeded","failed"],PT=200;function RT(e){return typeof e=="string"&&_y.includes(e)}function CT(e){return typeof e=="string"&&AT.includes(e)}function yy(e){if(!L(e))return null;let t=e;if(!RT(t.stage))return null;let r=CT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,PT);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var OT="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,DT=24,zT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function $a(e){return"phase"in e&&typeof e.phase=="string"}var by=new WeakMap;function Sa(e){let t=by.get(e);return t||(t=Dp(e),by.set(e,t)),t}function xa(e){return Sa(e).payload}function UT(e){let t=xa(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function ky(e){return xa(e).kind}function Ey(e){return Sa(e).promptId}function de(e,t){let r=Ey(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function LT(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}:{},...L(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 Hr(e){return $a(e)?Ey(e):L(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function Rn(e){if(!$a(e))return e.type;let t=xa(e),r=ky(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(Sa(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 jT(e){if($a(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=L(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 MT(e){let t=jT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function Up(e){if(!$a(e))return L(e.data)?e.data:void 0;let t=xa(e),r=ky(e),o=de(e,UT(e));switch(Sa(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:L(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 LT(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}:{},...L(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 Ty(e){let t=Up(e);return{raw:e,type:Rn(e),data:t,promptId:Hr(e)}}function wy(e){return e.map(t=>Ty(t))}function FT(e,t){return t?t.length<DT?!0:!e.endsWith(t):!1}function ZT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function BT(e,t){return`${e}:${t}`}function $y(e,t){return t===0?e:`${e}#${t}`}function Mt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function VT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function GT(e){switch(e.type){case"agent_progress":case"retry_status":case"zeus_telemetry":case"agent_timeline":return!0;default:return!1}}function qT(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(!GT(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 HT(e,t,r,o,n,i,a){let s=BT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=FT(u,n);if(c!==void 0){let p=e[c];if(p.type===r&&l&&qT(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:$y(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:$y(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{},...a!==void 0?{startedAtMs:a,endedAtMs:a}:{}}),!0}function WT(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 zp(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function KT(e,t){let r=zp(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...L(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function JT(){return{merged:[],streams:ZT(),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(OT)}function XT(e){return NT.test(e)}function QT(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)&&XT(t.text)))}function Oe(e,t){t&&e.merged.push(t)}function eA(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function tA(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 nA(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 rA(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 iA(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 oA(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 aA(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}=oA(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 sA(e,t){let r=typeof e?.eventName=="string"?e.eventName:Op;return{type:Op,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function uA(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}:{},...L(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function cA(e,t){let r=V(e);return{type:"agent_progress",id:Mt(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 lA(e,t){let r=cA(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 dA(e,t){return{type:"session_error",id:Mt(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 pA(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 mA(e,t){return{type:"session_resumed_cold",id:Mt(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 fA(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&&zT.has(o)?null:{type:"raw_agent_runtime",id:Mt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function gA(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 Sy(e,t,r,o){HT(r.merged,r.streams,e,Mt(t,e,r.merged.length),VT(t),V(t),o)}function hA(e,t){let r=Mt(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=zp(e?.toolStatus),a=L(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}:{},...L(e?.failure)?{failure:e.failure}:{}};t.merged[o]=WT(n,s)}}else{let n=zp(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)}:{},...L(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}:{},...L(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function vA(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]=KT(n,e))}function _A(e,t){let r={type:"question",id:Mt(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 yA(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 bA(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 wA(e,t){let r=yy(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 $A(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 Ay(e){let t=JT();for(let r of e){let o=Ty(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Oe(t,eA(i,t.merged.length));break;case"sandbox_compaction_complete":Oe(t,tA(i,t.merged.length));break;case"sandbox_context_fill_warning":Oe(t,nA(i,t.merged.length));break;case"sandbox_tool_truncated":Oe(t,rA(i,t.merged.length));break;case"retry_status":Oe(t,iA(i,t.merged.length));break;case"prompt_retrying":Oe(t,aA(i,t.merged.length));break;case"zeus_telemetry":Oe(t,sA(i,t.merged.length));break;case"agent_timeline":Oe(t,uA(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":lA(i,t);break;case"session_error":pA(i,t),Oe(t,dA(i,t.merged.length));break;case"session_resumed_cold":Oe(t,mA(i,t.merged.length));break;case"raw_agent_runtime":Oe(t,fA(i,t.merged.length));break;case"reasoning":Sy("reasoning",i,t,MT(o.raw));break;case"text":Sy("text",i,t);break;case"patch":Oe(t,gA(i,t.merged.length));break;case"todo_update":bA(i,t);break;case"answer":yA(i,t);break;case"tool_call":hA(i,t);break;case"tool_update":vA(i,t);break;case"question":_A(i,t);break;case"narration":$A(i,t);break;case"onboarding_status":wA(i,t);break}}return QT(t)}function Py(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Hr(i),s=typeof a=="string"&&r.has(a)?a:null;Rn(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function SA(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 xy(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function Iy(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function Ry(e){let t=wy(e),r=SA(t),o=t.filter(b=>b.type==="prompt_activity"),n=t.filter(b=>b.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=wy(r),a=i.filter(b=>b.type==="prompt_activity"),s=i.filter(b=>b.type==="agent_progress"),u=new Set(a.map(xy)),c=new Set(s.map(Iy)),l=a.length,d=s.length,m=0,p=0,g=o.filter(b=>{let x=xy(b);return u.has(x)?(m+=1,!1):(u.add(x),!0)}),_=n.filter(b=>{let x=Iy(b);return c.has(x)?(p+=1,!1):(c.add(x),!0)}),I=[...g,..._].map(b=>b.raw);return{events:I.length>0?[...I,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:g.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var Cy=1e3;async function Oy(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>Cy)throw new y("user",`${e} exceeded ${Cy} 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 LA}from"eventsource-parser";function Ia(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function Ny(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function ka(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 xA="## Previously declined findings on this repository (calibration)",IA="## Findings already reported by other reviewers",kA="## Graphite stack neighbours",Dy=[xA,IA,kA,"## Independent review suggestions"];var Uy=/\r?\n/,EA=/\n{3,}/g,TA=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,AA=[/^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],PA=[/<\/?(?: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],RA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function CA(e){let t=e.split(Uy),r=[],o=[];if(t.forEach((a,s)=>{let u=Dy.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(`
87
+ `).trim()}function zy(e){return PA.some(t=>t.test(e))}function OA(e){return e.replace(TA,"").split(Uy).filter(o=>!AA.some(n=>n.test(o.trim()))).join(`
88
+ `).replace(EA,`
89
89
 
90
- `).trim()}function Lp(e){let t=e.replyToText?.trim();if(t&&!zy(t))return t;if(PA.test(e.prompt.trimStart()))return RA(e.prompt.trim());if(zy(e.prompt)){let r=CA(e.prompt);if(r)return r}return t||e.prompt.trim()}var OA=["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"],NA=new Set(OA);var Ly={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"},DA={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 jy(e){return typeof e=="string"&&NA.has(e)}function zA(e){return jy(e)?Ly[e]:Ly.unknown}function jp(e,t){if(!t||!jy(t)||t==="unknown")return e;let r=zA(t),o=DA[t];return o&&(e===o||e.startsWith(`${o}:`))?`${r}${e.slice(o.length)}`:e.includes(r)?e:`${r}: ${e}`}var LA=/\.\d+Z$/,jA=/\s+/g,MA=8,FA=80,ZA=new Set(qp),BA=new Set(["creating","reconnecting","stopping","none"]),VA=new Set(["user","resumable","none"]),GA=new Set(["post_execution","publishing","none"]);function qA(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().replace("T"," ").replace(LA," 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})`:""}
90
+ `).trim()}function Lp(e){let t=e.replyToText?.trim();if(t&&!zy(t))return t;if(RA.test(e.prompt.trimStart()))return CA(e.prompt.trim());if(zy(e.prompt)){let r=OA(e.prompt);if(r)return r}return t||e.prompt.trim()}var NA=["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"],DA=new Set(NA);var Ly={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"},zA={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 jy(e){return typeof e=="string"&&DA.has(e)}function UA(e){return jy(e)?Ly[e]:Ly.unknown}function jp(e,t){if(!t||!jy(t)||t==="unknown")return e;let r=UA(t),o=zA[t];return o&&(e===o||e.startsWith(`${o}:`))?`${r}${e.slice(o.length)}`:e.includes(r)?e:`${r}: ${e}`}var jA=/\.\d+Z$/,MA=/\s+/g,FA=8,ZA=80,BA=new Set(qp),VA=new Set(["creating","reconnecting","stopping","none"]),GA=new Set(["user","resumable","none"]),qA=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(jA," UTC")}function WA(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})`:""}
91
91
  `;case"reasoning":return`<details><summary>Reasoning</summary>
92
92
  <br>
93
93
 
@@ -111,25 +111,25 @@ ${e.answer?`**Answer:** ${e.answer}
111
111
  `;case"prompt_activity":return"";case"agent_progress":return`*[${e.label}]*
112
112
  `;case"narration":return`*[Currently: ${e.text}]*
113
113
  `;case"onboarding_status":return`*[${e.stage}: ${e.status}]*
114
- `;case"raw_agent_runtime":return""}}function Mp(e){return e.toLocaleString()}function Ea(e){return typeof e=="string"&&e.trim()?e:null}function Fy(e){let{prUrl:t,publishedBranch:r,lastBranch:o}=WA(e),n=Ea(e.baseBranch),i=r??(o&&o!==n?o:null);return t?`PR: ${t}${i?` (${i})`:""}`:i?`Branch: ${i}`:null}function WA(e){let t={},r=Ea(e.prUrl),o=Ea(e.publishedBranch),n=Ea(e.lastBranch);return r&&(t.prUrl=r),o&&(t.publishedBranch=o),n&&(t.lastBranch=n),t}function Zy(e){let t=[],r=e.prompts.map(i=>i.id),o=Py(e.events,r);t.push(`# Session transcript
115
- `),e.session.repoUrl&&t.push(`**Repo:** ${e.session.repoUrl} `),t.push(`**Session:** ${e.session.id.slice(0,MA)} `),t.push(`**Created:** ${qA(e.session.createdAt)} `),t.push(`**Status:** ${e.session.status} `);let n=Ny(e.prompts);if(!e.pr?.url&&Ia(n)){let i=ka(n.noChangeReason);i.state!=="no_changes"&&t.push(`**Outcome:** ${i.title} `)}t.push(`**Tokens:** ${Mp(e.tokens.inputTokens)} in / ${Mp(e.tokens.outputTokens)} out / ${Mp(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}=Ry(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=Ay(u);if(t.push(`---
114
+ `;case"raw_agent_runtime":return""}}function Mp(e){return e.toLocaleString()}function Ea(e){return typeof e=="string"&&e.trim()?e:null}function Fy(e){let{prUrl:t,publishedBranch:r,lastBranch:o}=KA(e),n=Ea(e.baseBranch),i=r??(o&&o!==n?o:null);return t?`PR: ${t}${i?` (${i})`:""}`:i?`Branch: ${i}`:null}function KA(e){let t={},r=Ea(e.prUrl),o=Ea(e.publishedBranch),n=Ea(e.lastBranch);return r&&(t.prUrl=r),o&&(t.publishedBranch=o),n&&(t.lastBranch=n),t}function Zy(e){let t=[],r=e.prompts.map(i=>i.id),o=Py(e.events,r);t.push(`# Session transcript
115
+ `),e.session.repoUrl&&t.push(`**Repo:** ${e.session.repoUrl} `),t.push(`**Session:** ${e.session.id.slice(0,FA)} `),t.push(`**Created:** ${HA(e.session.createdAt)} `),t.push(`**Status:** ${e.session.status} `);let n=Ny(e.prompts);if(!e.pr?.url&&Ia(n)){let i=ka(n.noChangeReason);i.state!=="no_changes"&&t.push(`**Outcome:** ${i.title} `)}t.push(`**Tokens:** ${Mp(e.tokens.inputTokens)} in / ${Mp(e.tokens.outputTokens)} out / ${Mp(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}=Ry(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=Ay(u);if(t.push(`---
116
116
  `),t.push(`## Turn ${i+1}
117
117
  `),t.push(`**Prompt ID:** ${a.id} `),t.push(`**Prompt status:** ${a.status}${a.error?` | ${a.error}`:""}`),t.push(""),t.push(`**User:**
118
118
  `),t.push(Lp({prompt:a.prompt,replyToText:a.replyToText})),t.push(""),l.length>0){t.push(`**Assistant:**
119
- `);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:**
119
+ `);let d="";for(let m of l){let p=WA(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:**
120
120
  `),t.push(`**Error:** ${a.error}`),t.push(""))}return t.join(`
121
- `)}function By(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(`
121
+ `)}function By(e){let t=[],r=LA({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(`
122
122
 
123
- `);let o=null,n=[];for(let i of t){let a=i.data?KA(i.data):{},s=L(a)?a:{};if(i.event==="status"){let u=s.phase,l={phase:typeof u=="string"&&ZA.has(u)?u:null},d=Fp(s.sandboxSubstate,BA);d!==void 0&&(l.sandboxSubstate=d);let m=Fp(s.stopMode,VA);m!==void 0&&(l.stopMode=m);let p=Fp(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 Fp(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function KA(e){try{return JSON.parse(e)}catch(t){throw new Error(`Malformed SSE JSON payload: ${xe(t)}`)}}function My(e,t){if(!e)return"";let r=t.get(e);return r?` - ${r}`:""}function Vy(e){let t=new Map;for(let r of e){let o=Lp({prompt:r.prompt,replyToText:r.replyToText});t.set(r.promptId,o.replace(jA," ").trim().slice(0,FA))}return t}function Ta(e,t){let r=L(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"}${My(o,t.promptLabels)}`}}case"prompt_processing":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[prompt] ${o??"unknown"} started${My(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] ${jp(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 Gy(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 JA(e,t){return e!==null&&t-e.since<15e3}function qy(e,t,r){return JA(t,r)?{...e,phase:t.heldPhase,sandboxSubstate:t.heldSubstate}:e}var YA=/^\d+$/;function Zp(e,t,r){if(!e)return r;if(!YA.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 Wr(e){if(e!==null&&Date.now()>=e)throw new y("server","Timed out waiting for session events.")}function Hy(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 QA(e,t,r,o){let n=e.phase?{phase:e.phase,sandboxSubstate:e.sandboxSubstate}:null,i=Gy(t,r,n,o);return{displayStatus:n?{...e,...qy(n,i,o)}:e,mask:i,view:n}}async function eP(e,t){try{let o=(await P(e,A("/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(Ia(i)){let a=ka(i.noChangeReason);a.state!=="no_changes"&&console.log(`[outcome] ${a.title}`)}break}}catch{}}async function Bp(e,t){let r=await P(e,A("/api/sessions/:sessionId/prompts",{sessionId:t}));return Vy(r.prompts)}async function Wy(e,t,r){let o=ee(r,t),n=_e(o),i=Ve(t.pollInterval),a=Zp(t.afterSequence,"--after-sequence",0),s=Zp(t.limit,"--limit",u_),u=Zp(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=Ie(r,t),d=new Map;if(!l)try{d=await Bp(n,e)}catch(x){console.error(`Warning: failed to fetch prompt labels for session ${e}: ${xe(x)}`)}let m={promptLabels:d,toolCalls:new Map},p=a,g=null,_=!1,I=null,b=null;l||console.log(`Watching session ${e}...`);try{for(;;){Wr(c);let x=new URLSearchParams({afterSequence:String(p),limit:String(s)}),E=Hy(c),C;try{C=await im(n,`${A("/api/sessions/:sessionId/events",{sessionId:e})}?${x}`,E===void 0?void 0:{timeoutMs:E})}catch(ne){throw Wr(c),ne}let F=By(C),B=F.events.length>=s;if(!l&&F.status){let ne=QA(F.status,I,b,Date.now());I=ne.mask,b=ne.view;let Ae=XA(ne.displayStatus);Ae!==g&&(_&&(process.stdout.write(`
123
+ `);let o=null,n=[];for(let i of t){let a=i.data?JA(i.data):{},s=L(a)?a:{};if(i.event==="status"){let u=s.phase,l={phase:typeof u=="string"&&BA.has(u)?u:null},d=Fp(s.sandboxSubstate,VA);d!==void 0&&(l.sandboxSubstate=d);let m=Fp(s.stopMode,GA);m!==void 0&&(l.stopMode=m);let p=Fp(s.finalizingStep,qA);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 Fp(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function JA(e){try{return JSON.parse(e)}catch(t){throw new Error(`Malformed SSE JSON payload: ${xe(t)}`)}}function My(e,t){if(!e)return"";let r=t.get(e);return r?` - ${r}`:""}function Vy(e){let t=new Map;for(let r of e){let o=Lp({prompt:r.prompt,replyToText:r.replyToText});t.set(r.promptId,o.replace(MA," ").trim().slice(0,ZA))}return t}function Ta(e,t){let r=L(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"}${My(o,t.promptLabels)}`}}case"prompt_processing":{let o=typeof r.promptId=="string"?r.promptId:void 0;return{kind:"line",line:`[prompt] ${o??"unknown"} started${My(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] ${jp(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 Gy(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 YA(e,t){return e!==null&&t-e.since<15e3}function qy(e,t,r){return YA(t,r)?{...e,phase:t.heldPhase,sandboxSubstate:t.heldSubstate}:e}var XA=/^\d+$/;function Zp(e,t,r){if(!e)return r;if(!XA.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 Wr(e){if(e!==null&&Date.now()>=e)throw new y("server","Timed out waiting for session events.")}function Hy(e){if(e!==null)return Math.max(0,e-Date.now())}function QA(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 eP(e,t,r,o){let n=e.phase?{phase:e.phase,sandboxSubstate:e.sandboxSubstate}:null,i=Gy(t,r,n,o);return{displayStatus:n?{...e,...qy(n,i,o)}:e,mask:i,view:n}}async function tP(e,t){try{let o=(await P(e,A("/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(Ia(i)){let a=ka(i.noChangeReason);a.state!=="no_changes"&&console.log(`[outcome] ${a.title}`)}break}}catch{}}async function Bp(e,t){let r=await P(e,A("/api/sessions/:sessionId/prompts",{sessionId:t}));return Vy(r.prompts)}async function Wy(e,t,r){let o=ee(r,t),n=_e(o),i=Ve(t.pollInterval),a=Zp(t.afterSequence,"--after-sequence",0),s=Zp(t.limit,"--limit",u_),u=Zp(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=Ie(r,t),d=new Map;if(!l)try{d=await Bp(n,e)}catch(x){console.error(`Warning: failed to fetch prompt labels for session ${e}: ${xe(x)}`)}let m={promptLabels:d,toolCalls:new Map},p=a,g=null,_=!1,I=null,b=null;l||console.log(`Watching session ${e}...`);try{for(;;){Wr(c);let x=new URLSearchParams({afterSequence:String(p),limit:String(s)}),E=Hy(c),C;try{C=await im(n,`${A("/api/sessions/:sessionId/events",{sessionId:e})}?${x}`,E===void 0?void 0:{timeoutMs:E})}catch(ne){throw Wr(c),ne}let F=By(C),B=F.events.length>=s;if(!l&&F.status){let ne=eP(F.status,I,b,Date.now());I=ne.mask,b=ne.view;let Ae=QA(ne.displayStatus);Ae!==g&&(_&&(process.stdout.write(`
124
124
  `),_=!1),console.log(Ae),g=Ae)}for(let ne of F.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})}
125
125
  `);continue}let Ae=Ta(ne,m);if(Ae){if(Ae.kind==="text"){if(!Ae.text)continue;_||(process.stdout.write("assistant> "),_=!0),process.stdout.write(Ae.text);continue}_&&(process.stdout.write(`
126
126
  `),_=!1),console.log(Ae.line)}}if(B){Wr(c);continue}if(F.status?.phase&&c_(F.status.phase)){!l&&F.status.phase==="completed"&&(_&&(process.stdout.write(`
127
- `),_=!1),await eP(n,e));break}Wr(c);let Q=Hy(c);await Kr(Q===void 0?i:Math.min(i,Q)),Wr(c)}}finally{_&&process.stdout.write(`
127
+ `),_=!1),await tP(n,e));break}Wr(c);let Q=Hy(c);await Kr(Q===void 0?i:Math.min(i,Q)),Wr(c)}}finally{_&&process.stdout.write(`
128
128
  `)}}async function Ky(e,t){let r=ee(t,e),o=_e(r),{items:n,nextCursor:i}=await Oy("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 P(o,`${A("/api/sessions")}${u.size?`?${u.toString()}`:""}`);return{items:c.sessions,nextCursor:c.nextCursor}}),a={sessions:n,nextCursor:i};if(Ie(t,e)){qe(a);return}if(a.sessions.length===0){console.log("No sessions found.");return}for(let s of a.sessions){let u=N(String(s.id??s.sessionId??"")),c=N(String(s.status??"")),l=typeof s.title=="string"?` ${N(s.title)}`:"";console.log(`${u} ${c}${l}`)}a.nextCursor&&console.log(`Next cursor: ${N(a.nextCursor)}`)}async function Jy(e,t,r){let o=ee(r,t),n=_e(o),i=await P(n,A("/api/sessions/:sessionId",{sessionId:e}));if(Ie(r,t)){qe(i);return}let a=i.session&&typeof i.session=="object"&&!Array.isArray(i.session)?i.session:i;console.log(`Session: ${N(String(a.sessionId??a.id??e))}`),console.log(`Status: ${N(String(a.phase??a.status??"unknown"))}`),a.repoUrl&&console.log(`Repo: ${N(String(a.repoUrl))}`),a.title&&console.log(`Title: ${N(String(a.title))}`);let s=Fy(a);s&&console.log(N(s))}async function Yy(e,t,r){let o=ee(r,t),n=_e(o),i=await P(n,`${A("/api/sessions/:sessionId/view",{sessionId:e})}?promptLimit=1`);O(r,o,i,a=>{o.quiet||console.log(De(JSON.stringify(a,null,2)))})}async function Xy(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 Wy(e,{...t,pollInterval:t.pollInterval,afterSequence:o,limit:t.limit},r);return}let i=ee(r,t),a=_e(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 P(a,`${A("/api/sessions/:sessionId/events/history",{sessionId:e})}${s.size?`?${s.toString()}`:""}`);if(Ie(r,t)){qe(u);return}let l={promptLabels:await Bp(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=Ta({type:Rn(m),data:Up(m)??{}},l);p?.kind==="line"&&(d&&(process.stdout.write(`
129
129
  `),d=!1),console.log(p.line)),p?.kind==="text"&&p.text&&(process.stdout.write(p.text),d=!0)}d&&process.stdout.write(`
130
- `)}import{execFile as tP}from"node:child_process";import{constants as nP}from"node:fs";import{access as rP}from"node:fs/promises";import{basename as iP,delimiter as oP,join as Vp,resolve as Aa}from"node:path";import{promisify as aP}from"node:util";var Pa=aP(tP);async function Qy(e,t,r){let o=ee(r,t),n=process.env.npm_execpath,i=n&&iP(n)==="npm-cli.js"?process.execPath:"npm",a=i===process.execPath?[n]:[],s={shell:process.platform==="win32"&&i==="npm"},u=`@tryarcanist/cli@${nt}`,c;try{c=(await Pa(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=Vp(c,...l?[]:["lib"],"node_modules/@tryarcanist/cli/dist/index.js"),m;try{m=(await Pa(process.execPath,[d,"--version"])).stdout.trim()}catch{}if(m!==nt){!o.json&&!o.quiet&&process.stderr.write(`Installing Arcanist for future reviews\u2026
131
- `);try{await Pa(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 Pa(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!==nt)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:Vp(c,"bin");try{await rP(Vp(p,l?"arcanist.cmd":"arcanist"),nP.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(oP).some(_=>l?Aa(_).toLowerCase()===Aa(p).toLowerCase():Aa(_)===Aa(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=${Qe(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.
132
- `),await ya(e,t,r)}async function eb(e,t,r){let{config:o}=G(r,t),n=sP(t.last),i=await P(o,A("/api/sessions/:sessionId/export",{sessionId:e})),a=n==null?i:uP(i,n,{includeBoundaryEvent:!Ie(r,t)});O(r,t,a,s=>console.log(Zy(s)))}function sP(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 uP(e,t,r){let o=Math.max(0,e.events.length-t),n=cP(e.events,o),i=e.events.slice(o),a=r.includeBoundaryEvent&&n!==null&&n<o?[e.events[n],...i]:i,s=lP(a);if(n!==null){let c=Hr(e.events[n]);c&&s.add(c)}let u=e.prompts.filter(c=>s.has(c.id));return{...e,prompts:u,events:a}}function cP(e,t){for(let r=t;r>=0;r--){let o=e[r];if(o&&Rn(o)==="prompt_processing")return r}return null}function lP(e){let t=new Set;for(let r of e){let o=Hr(r);o&&t.add(o)}return t}function tb(){let e=new dP().name("arcanist").description("Arcanist CLI").version(nt).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",`
130
+ `)}import{execFile as nP}from"node:child_process";import{constants as rP}from"node:fs";import{access as iP}from"node:fs/promises";import{basename as oP,delimiter as aP,join as Vp,resolve as Aa}from"node:path";import{promisify as sP}from"node:util";var Pa=sP(nP);async function Qy(e,t,r){let o=ee(r,t),n=process.env.npm_execpath,i=n&&oP(n)==="npm-cli.js"?process.execPath:"npm",a=i===process.execPath?[n]:[],s={shell:process.platform==="win32"&&i==="npm"},u=`@tryarcanist/cli@${nt}`,c;try{c=(await Pa(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=Vp(c,...l?[]:["lib"],"node_modules/@tryarcanist/cli/dist/index.js"),m;try{m=(await Pa(process.execPath,[d,"--version"])).stdout.trim()}catch{}if(m!==nt){!o.json&&!o.quiet&&process.stderr.write(`Installing Arcanist for future reviews\u2026
131
+ `);try{await Pa(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 Pa(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!==nt)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:Vp(c,"bin");try{await iP(Vp(p,l?"arcanist.cmd":"arcanist"),rP.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(aP).some(_=>l?Aa(_).toLowerCase()===Aa(p).toLowerCase():Aa(_)===Aa(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=${Qe(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.
132
+ `),await ya(e,t,r)}async function eb(e,t,r){let{config:o}=G(r,t),n=uP(t.last),i=await P(o,A("/api/sessions/:sessionId/export",{sessionId:e})),a=n==null?i:cP(i,n,{includeBoundaryEvent:!Ie(r,t)});O(r,t,a,s=>console.log(Zy(s)))}function uP(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 cP(e,t,r){let o=Math.max(0,e.events.length-t),n=lP(e.events,o),i=e.events.slice(o),a=r.includeBoundaryEvent&&n!==null&&n<o?[e.events[n],...i]:i,s=dP(a);if(n!==null){let c=Hr(e.events[n]);c&&s.add(c)}let u=e.prompts.filter(c=>s.has(c.id));return{...e,prompts:u,events:a}}function lP(e,t){for(let r=t;r>=0;r--){let o=e[r];if(o&&Rn(o)==="prompt_processing")return r}return null}function dP(e){let t=new Set;for(let r of e){let o=Hr(r);o&&t.add(o)}return t}function tb(){let e=new pP().name("arcanist").description("Arcanist CLI").version(nt).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",`
133
133
  Examples:
134
134
  arcanist auth login --token-stdin
135
135
  arcanist sessions list --json
@@ -184,7 +184,7 @@ Examples:
184
184
  JSON: {review, requestStatus} preserves the result and status-batch envelopes, including unavailableRequestIds.
185
185
  A successful read exits 0 for active reviews and blocking findings. This command starts no model run.
186
186
  For local requests use arcanist review --request <id> --no-wait --json.
187
- `).action((s,u,c)=>ty(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 pP("--sandbox-runtime <runtime>","Force the sandbox runtime: modal or e2b").hideHelp()).addHelpText("after",`
187
+ `).action((s,u,c)=>ty(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 mP("--sandbox-runtime <runtime>","Force the sandbox runtime: modal or e2b").hideHelp()).addHelpText("after",`
188
188
  Examples:
189
189
  arcanist review
190
190
  arcanist review --base origin/release --json
@@ -232,7 +232,7 @@ Examples:
232
232
 
233
233
  JSON:
234
234
  JSON mode without --follow returns one JSON object from /events/history: {events: [...], ...}; canonical events carry phase.
235
- --follow --json emits NDJSON, one {sequence, type, data} object per line, until a terminal phase: ${fP(Cn)}.
235
+ --follow --json emits NDJSON, one {sequence, type, data} object per line, until a terminal phase: ${gP(Cn)}.
236
236
  --timeout bounds follow; 0 or omitted means unbounded. Process exit is a terminal phase, not session_idle.
237
237
  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.
238
238
  `).action((s,u,c)=>Xy(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",`
@@ -305,7 +305,7 @@ review doc, and its first build is scheduled by the server. With --create, --dry
305
305
  JSON:
306
306
  JSON mode returns {environmentId, name, changedFields, applied, configurationGeneration: {before, after?}, rebuildScheduled?}.
307
307
  A create returns {environmentId, name, created, applied, configurationGeneration: {after}, buildScheduled}.
308
- `).action((s,u,c,l)=>o_(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=gP(e,s);if(Ie(c,u)){qe(Wp(l));return}l.help({error:!1})}),{program:e,auth:t,reviews:o,environments:a}}async function nb(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){mP(o)&&process.exit(0),Ra(o,"commander.help")&&process.exit(1),o instanceof y&&o.exitCode===Ne&&hP();let n=t(nm(o),r);e.opts().json?process.stderr.write(`${Jr(n)}
308
+ `).action((s,u,c,l)=>o_(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=hP(e,s);if(Ie(c,u)){qe(Wp(l));return}l.help({error:!1})}),{program:e,auth:t,reviews:o,environments:a}}async function nb(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){fP(o)&&process.exit(0),Ra(o,"commander.help")&&process.exit(1),o instanceof y&&o.exitCode===Ne&&vP();let n=t(nm(o),r);e.opts().json?process.stderr.write(`${Jr(n)}
309
309
  `):(process.stderr.write(`Error: ${n.message}
310
310
  `),n.hint&&process.stderr.write(`Hint: ${n.hint}
311
- `)),process.exit(n.exitCode)}}function Ra(e,t){return!!e&&typeof e=="object"&&"code"in e&&e.code===t}function mP(e){return Ra(e,"commander.helpDisplayed")||Ra(e,"commander.version")?!0:Ra(e,"commander.help")&&"exitCode"in e&&e.exitCode===0}function fP(e){let t=e.at(-1);return t===void 0?"":e.length===1?t:`${e.slice(0,-1).join(", ")}, or ${t}`}function gP(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 hP(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h")}var{program:vP}=tb();nb(vP);
311
+ `)),process.exit(n.exitCode)}}function Ra(e,t){return!!e&&typeof e=="object"&&"code"in e&&e.code===t}function fP(e){return Ra(e,"commander.helpDisplayed")||Ra(e,"commander.version")?!0:Ra(e,"commander.help")&&"exitCode"in e&&e.exitCode===0}function gP(e){let t=e.at(-1);return t===void 0?"":e.length===1?t:`${e.slice(0,-1).join(", ")}, or ${t}`}function hP(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 vP(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h")}var{program:_P}=tb();nb(_P);