@tryarcanist/cli 0.1.527 → 0.1.528

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 +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire as __arcanistCreateRequire } from "node:module";
3
3
  const require = __arcanistCreateRequire(import.meta.url);
4
4
  var Yy=Object.defineProperty;var Ve=(e,t)=>{for(var r in t)Yy(e,r,{get:t[r],enumerable:!0})};import{Command as BA,Option as GA}from"commander";var Vp="npx --yes @tryarcanist/cli@latest setup";var Bp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Rn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],Xy=new Set(Rn),QA=new Set(Rn.filter(e=>e!=="completed")),eR=Rn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Gp(e,t){return Xy.has(e)}function qp(e){let t=e.createHelp().visibleGlobalOptions(e).map(Wp);return{...Hp(e),...t.length>0?{globalOptions:t}:{}}}function Hp(e){let t=Qy(e);return{path:Ta(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(Wp),...t?{notes:t}:{},subcommands:e.commands.map(Hp)}}function Wp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Ta(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function Qy(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Bb,mkdirSync as Gb,writeFileSync as qb}from"node:fs";import{basename as Hb,join as fm,resolve as Wb}from"node:path";var eb="en-US";function Kp(e,t){let r=new Intl.DateTimeFormat(eb,{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}function Gr(e){return e instanceof Error&&e.name==="AbortError"}var oR=Date.parse("2026-09-26T15:00:00Z"),aR=60*1e3,sR=5*6e4;var uR=6*36e5;var cR=2*6e4,lR=5*6e4,dR=20*6e4,pR=5*6e4,mR=10*1e3,fR=60*1e3,gR=5*6e4;var vR=48*36e5,hR=6*36e5,_R=7*864e5,yR=5*6e4;var bR=168*36e5,wR=168*36e5,$R=30*1e3,SR=90*1e3;var xR=6*36e5,IR=30*6e4,tb=15*6e4,nb=90*6e4,kR=15*6e4,ER=tb+2*nb,TR=2*6e4,AR=40*1e3,RR=14*864e5,PR=30*864e5;var CR=30*6e4;var OR=15*6e4;var NR=10*1e3,DR=15*1e3;var zR=60*6e4,UR=5*6e4,LR=2*6e4;var jR=3*6e4,MR=10*6e4,FR=10*6e4,ZR=24*36e5,VR=24*36e5,BR=2*6e4,GR=5*1e3;function qr(e){return new Promise(t=>setTimeout(t,e))}var rb=new Set([408,429,500,502,503,504]);function Jp(e,t){let r=t.includeDefaults!==!1&&rb.has(e)||t.includeServerErrors===!0&&e>=500;return t.remove?.includes(e)?!1:r||t.add?.includes(e)===!0}var ib=/\/+$/;function Je(e){return e.replace(ib,"")}var Aa="team@tryarcanist.com",tP=`mailto:${Aa}`;var Yp=`Setup and reviews are paused for this workspace. Contact ${Aa} to resume them.`;function Xp(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 Ra(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=Xp(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 ob=/^error: /,ab=/^\((.*)\)$/,ht=130,Pa=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??Qp(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},vt=class extends y{},ae=class extends y{status;body;constructor(t,r,o,n){let i=em(t),a=Ra(r);super(i,ub(t,r,a),{exitCode:sb(t),hint:cb(t,a,n),requestId:o,data:a?.serverCode||a?.repository||a?.environmentsUrl||a?.billingUrl?{...a.serverCode?{serverCode:a.serverCode}:{},...a.repository?{repository:a.repository}:{},...a.environmentsUrl?{environmentsUrl:a.environmentsUrl}:{},...a.billingUrl?{billingUrl:a.billingUrl}:{}}:void 0}),this.name="ApiError",this.status=t,this.body=r}};function Qp(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function em(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function sb(e){return Qp(em(e))}function ub(e,t,r=Ra(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function cb(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&t?.message===Yp)){if(e===403&&t?.serverCode==="github_not_connected")return"This user has not connected GitHub. Open `/auth/github/connect` on the Arcanist app and approve, then retry. `arcanist onboard <owner/repo>` prints that link.";if(e===403)return"This token is not allowed to do that. `arcanist auth whoami --json` shows its tokenScope and your businessRole: a change needs a write-scope token (mint one in Settings > CLI), and a workspace-wide change also needs the admin role.";if(e===404)return r==="repo"?"Check accessible repositories with `arcanist repos list`.":r==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&t?.repository){if(t.serverCode==="environment_required")return`Run \`arcanist environments prepare ${t.repository} --wait\`, then retry the review.`;if(t.serverCode==="environment_preparing"||t.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${t.repository} --wait\` for the latest setup state.`}if(e===409)return"Check the current resource state and retry the command when it is ready.";if(e>=500)return"Retry later or check the control-plane logs."}}var lb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function db(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(ob,"").split(`
5
- `);return new y("user",t,{hint:r?r.replace(ab,"$1"):lb})}function tm(e){if(e instanceof y)return e;if(e instanceof Error){let t=db(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Hr(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 nm={name:"@tryarcanist/cli",version:"0.1.527",description:"Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",type:"module",bin:{arcanist:"dist/index.js"},engines:{node:">=22"},files:["dist/index.js"],scripts:{build:"tsup",typecheck:"node ../../node_modules/tsrs/bin/tsrs --noEmit",prepublishOnly:"npm --prefix ../.. run guard:cli-bundle"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/tryarcanist/arcanist.git",directory:"apps/cli"},homepage:"https://www.tryarcanist.com",license:"MIT",dependencies:{commander:"^12.1.0","eventsource-parser":"3.1.1","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var Ye=`${nm.version}`;var mb=/^\d+$/,fb=`arcanist-cli/${Ye}`,gb=3e4,vb=1e3,hb=6e5,Wr="ARCANIST_HTTP_TIMEOUT_MS";function _b(e=process.env){let t=e[Wr];if(!t)return gb;if(!mb.test(t))throw new y("user",`${Wr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<vb||r>hb)throw new y("user",`${Wr} must be between 1000 and 600000 milliseconds.`);return r}function yb(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 Ca(e){return new vt("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Wr} for slow links, or check the API connection.`})}function bb(e){let t=_b();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 Oa(e,t,r,o){let{fetchInit:n,timeoutMs:i}=bb(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",fb),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${Je(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw Gr(l)?Ca(i):new vt("server",`Network error: could not reach ${Je(e.apiUrl)} (${yb(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(Gr(d))throw Ca(i);return""});throw new ae(c.status,l,c.headers.get("x-request-id")??void 0,wb(t))}return await o(c)}catch(u){throw u instanceof y?u:Gr(u)?Ca(i):u instanceof TypeError?new vt("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 wb(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function P(e,t,r){return Oa(e,t,r,o=>o.json())}async function rm(e,t,r){return Oa(e,t,r,o=>o.text())}async function im(e,t,r){return Oa(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}function om(e){return e instanceof vt||e instanceof ae&&Jp(e.status,{includeServerErrors:!0})}var $b=/:([A-Za-z]+)/g,L={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"},getInferenceCopies:{method:"GET",pattern:"/api/inference/settings"},setInferenceCopies:{method:"PATCH",pattern:"/api/inference/settings"},getInferenceCalls:{method:"GET",pattern:"/api/inference/calls"},getInferenceWorkflows:{method:"GET",pattern:"/api/inference/workflows"},getInferenceWorkflowUsage:{method:"GET",pattern:"/api/inference/workflows/usage"},getInferenceTraces:{method:"GET",pattern:"/api/inference/traces"},getInferenceTrace:{method:"GET",pattern:"/api/inference/traces/:traceId"},getInferenceTraceBody:{method:"GET",pattern:"/api/inference/traces/:traceId/calls/:callId"},getInferenceUsage:{method:"GET",pattern:"/api/inference/usage"},getCurrentUser:{method:"GET",pattern:"/api/auth/whoami"},exchangeCliLogin:{method:"POST",pattern:"/api/cli-login/exchange"},getGithubInstallation:{method:"GET",pattern:"/api/onboarding/github-installation"},answerOnboardingQuestion:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/question"},listRepositories:{method:"GET",pattern:"/api/repos"},listSessions:{method:"GET",pattern:"/api/sessions"},getSession:{method:"GET",pattern:"/api/sessions/:sessionId"},getSessionView:{method:"GET",pattern:"/api/sessions/:sessionId/view"},getSessionPrompts:{method:"GET",pattern:"/api/sessions/:sessionId/prompts"},getSessionEvents:{method:"GET",pattern:"/api/sessions/:sessionId/events"},getSessionEventHistory:{method:"GET",pattern:"/api/sessions/:sessionId/events/history"},exportSession:{method:"GET",pattern:"/api/sessions/:sessionId/export"},listSessionArtifacts:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/list"},viewSessionArtifact:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/:artifactId/view"},createReview:{method:"POST",pattern:"/api/pr-reviews"},getReviewRequest:{method:"GET",pattern:"/api/pr-reviews/requests/:requestId"},getReviewRequestStatuses:{method:"POST",pattern:"/api/pr-reviews/requests/status-batch"},createLocalReview:{method:"POST",pattern:"/api/local-reviews"},getLocalReview:{method:"GET",pattern:"/api/local-reviews/:requestId"},getRepositoryOnboarding:{method:"GET",pattern:"/api/settings/repositories/onboarding"},prepareRepository:{method:"POST",pattern:"/api/settings/repositories/onboarding"},retryRepositoryOnboarding:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/retry"},getSettingsBusinessReviewDefault:{method:"GET",pattern:"/api/settings/business/review-default"},putSettingsBusinessReviewDefault:{method:"PUT",pattern:"/api/settings/business/review-default"},listEnvironments:{method:"GET",pattern:"/api/environments"},getEnvironment:{method:"GET",pattern:"/api/environments/:id"},updateEnvironment:{method:"PUT",pattern:"/api/environments/:id"},getEnvironmentMockDependencies:{method:"GET",pattern:"/api/environments/:id/mock-dependencies"},updateEnvironmentMockDependency:{method:"PUT",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},deleteEnvironmentMockDependency:{method:"DELETE",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},createEnvironment:{method:"POST",pattern:"/api/environments"}};function R(e,t={}){return am(e,t)}function am(e,t){return e.replace($b,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var SP=[{...L.getInferenceApiKeys,command:"inference keys list"},{...L.createInferenceApiKey,command:"inference keys create"},{...L.revokeInferenceApiKey,command:"inference keys revoke"},{...L.getInferenceProviders,command:"inference providers list"},{...L.setInferenceKey,command:"inference providers set-key"},{...L.removeInferenceKey,command:"inference providers remove-key"},{...L.setInferenceFallback,command:"inference providers fallback"},{...L.getInferenceCalls,command:"inference calls"},{...L.getInferenceCopies,command:"inference copies"},{...L.setInferenceCopies,command:"inference copies <on|off>"},{...L.getInferenceUsage,command:"inference usage"},{...L.getCurrentUser,command:"auth whoami"},{...L.exchangeCliLogin,command:"auth login",public:!0},{...L.getGithubInstallation,command:"onboard"},{...L.getSettingsBusinessReviewDefault,command:"onboard"},{...L.putSettingsBusinessReviewDefault,command:"onboard --automatic-review"},{...L.answerOnboardingQuestion,command:"environments answer"},{...L.listRepositories,command:"repos list"},{...L.listSessions,command:"sessions list"},{...L.getSession,command:"sessions get"},{...L.getSessionView,command:"sessions view"},{...L.getSessionPrompts,command:"sessions events --follow"},{...L.getSessionEvents,command:"sessions events --follow"},{...L.getSessionEventHistory,command:"sessions events"},{...L.exportSession,command:"sessions transcript"},{...L.listSessionArtifacts,command:"sessions artifacts"},{...L.viewSessionArtifact,command:"sessions artifacts get"},{...L.createReview,command:"review <pr-url>"},{...L.getReviewRequest,command:"review <pr-url>"},{...L.getReviewRequest,command:"reviews get"},{...L.getReviewRequestStatuses,command:"reviews get"},{...L.createLocalReview,command:"review"},{...L.getLocalReview,command:"review --request"},{...L.getRepositoryOnboarding,command:"environments status"},{...L.prepareRepository,command:"environments prepare"},{...L.retryRepositoryOnboarding,command:"environments retry"},{...L.listEnvironments,command:"environments export"},{...L.getEnvironment,command:"environments export"},{...L.listEnvironments,command:"environments import"},{...L.getEnvironment,command:"environments import"},{...L.updateEnvironment,command:"environments import"},{...L.createEnvironment,command:"environments import --create"}];import{createHash as um}from"node:crypto";import{existsSync as Pn,mkdirSync as Eb,readFileSync as Na,statSync as Tb}from"node:fs";import{homedir as Ab}from"node:os";import{dirname as cm,join as yt,resolve as Rb}from"node:path";import{randomUUID as Sb}from"node:crypto";import{renameSync as xb,rmSync as Ib,writeFileSync as kb}from"node:fs";function _t(e,t){let r=`${e}.${Sb()}.tmp`;try{kb(r,JSON.stringify(t,null,2)+`
5
+ `);return new y("user",t,{hint:r?r.replace(ab,"$1"):lb})}function tm(e){if(e instanceof y)return e;if(e instanceof Error){let t=db(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Hr(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 nm={name:"@tryarcanist/cli",version:"0.1.528",description:"Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",type:"module",bin:{arcanist:"dist/index.js"},engines:{node:">=22"},files:["dist/index.js"],scripts:{build:"tsup",typecheck:"node ../../node_modules/tsrs/bin/tsrs --noEmit",prepublishOnly:"npm --prefix ../.. run guard:cli-bundle"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/tryarcanist/arcanist.git",directory:"apps/cli"},homepage:"https://www.tryarcanist.com",license:"MIT",dependencies:{commander:"^12.1.0","eventsource-parser":"3.1.1","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var Ye=`${nm.version}`;var mb=/^\d+$/,fb=`arcanist-cli/${Ye}`,gb=3e4,vb=1e3,hb=6e5,Wr="ARCANIST_HTTP_TIMEOUT_MS";function _b(e=process.env){let t=e[Wr];if(!t)return gb;if(!mb.test(t))throw new y("user",`${Wr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<vb||r>hb)throw new y("user",`${Wr} must be between 1000 and 600000 milliseconds.`);return r}function yb(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 Ca(e){return new vt("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Wr} for slow links, or check the API connection.`})}function bb(e){let t=_b();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 Oa(e,t,r,o){let{fetchInit:n,timeoutMs:i}=bb(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",fb),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${Je(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw Gr(l)?Ca(i):new vt("server",`Network error: could not reach ${Je(e.apiUrl)} (${yb(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(Gr(d))throw Ca(i);return""});throw new ae(c.status,l,c.headers.get("x-request-id")??void 0,wb(t))}return await o(c)}catch(u){throw u instanceof y?u:Gr(u)?Ca(i):u instanceof TypeError?new vt("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 wb(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function P(e,t,r){return Oa(e,t,r,o=>o.json())}async function rm(e,t,r){return Oa(e,t,r,o=>o.text())}async function im(e,t,r){return Oa(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}function om(e){return e instanceof vt||e instanceof ae&&Jp(e.status,{includeServerErrors:!0})}var $b=/:([A-Za-z]+)/g,L={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"},getInferenceCopies:{method:"GET",pattern:"/api/inference/settings"},setInferenceCopies:{method:"PATCH",pattern:"/api/inference/settings"},getInferenceCalls:{method:"GET",pattern:"/api/inference/calls"},getInferenceWorkflows:{method:"GET",pattern:"/api/inference/workflows"},getInferenceWorkflowUsage:{method:"GET",pattern:"/api/inference/workflows/usage"},getInferenceTraces:{method:"GET",pattern:"/api/inference/traces"},getInferenceTrace:{method:"GET",pattern:"/api/inference/traces/:traceId"},getInferenceTraceBody:{method:"GET",pattern:"/api/inference/traces/:traceId/calls/:callId"},getInferenceUsage:{method:"GET",pattern:"/api/inference/usage"},getCurrentUser:{method:"GET",pattern:"/api/auth/whoami"},exchangeCliLogin:{method:"POST",pattern:"/api/cli-login/exchange"},getGithubInstallation:{method:"GET",pattern:"/api/onboarding/github-installation"},answerOnboardingQuestion:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/question"},listRepositories:{method:"GET",pattern:"/api/repos"},listSessions:{method:"GET",pattern:"/api/sessions"},getSession:{method:"GET",pattern:"/api/sessions/:sessionId"},getSessionView:{method:"GET",pattern:"/api/sessions/:sessionId/view"},getSessionPrompts:{method:"GET",pattern:"/api/sessions/:sessionId/prompts"},getSessionEvents:{method:"GET",pattern:"/api/sessions/:sessionId/events"},getSessionEventHistory:{method:"GET",pattern:"/api/sessions/:sessionId/events/history"},exportSession:{method:"GET",pattern:"/api/sessions/:sessionId/export"},listSessionArtifacts:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/list"},viewSessionArtifact:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/:artifactId/view"},createReview:{method:"POST",pattern:"/api/pr-reviews"},getReviewRequest:{method:"GET",pattern:"/api/pr-reviews/requests/:requestId"},getReviewRequestStatuses:{method:"POST",pattern:"/api/pr-reviews/requests/status-batch"},createLocalReview:{method:"POST",pattern:"/api/local-reviews"},getLocalReview:{method:"GET",pattern:"/api/local-reviews/:requestId"},getRepositoryOnboarding:{method:"GET",pattern:"/api/settings/repositories/onboarding"},prepareRepository:{method:"POST",pattern:"/api/settings/repositories/onboarding"},retryRepositoryOnboarding:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/retry"},getSettingsBusinessReviewDefault:{method:"GET",pattern:"/api/settings/business/review-default"},putSettingsBusinessReviewDefault:{method:"PUT",pattern:"/api/settings/business/review-default"},listEnvironments:{method:"GET",pattern:"/api/environments"},getEnvironment:{method:"GET",pattern:"/api/environments/:id"},updateEnvironment:{method:"PUT",pattern:"/api/environments/:id"},getEnvironmentMockDependencies:{method:"GET",pattern:"/api/environments/:id/mock-dependencies"},updateEnvironmentMockDependency:{method:"PUT",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},deleteEnvironmentMockDependency:{method:"DELETE",pattern:"/api/environments/:id/mock-dependencies/:dependencyName"},createEnvironment:{method:"POST",pattern:"/api/environments"}};function R(e,t={}){return am(e,t)}function am(e,t){return e.replace($b,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var SP=[{...L.getInferenceApiKeys,command:"inference keys list"},{...L.createInferenceApiKey,command:"inference keys create"},{...L.revokeInferenceApiKey,command:"inference keys revoke"},{...L.getInferenceProviders,command:"inference providers list"},{...L.setInferenceKey,command:"inference providers set-key"},{...L.removeInferenceKey,command:"inference providers remove-key"},{...L.setInferenceFallback,command:"inference providers fallback"},{...L.getInferenceCalls,command:"inference calls"},{...L.getInferenceCopies,command:"inference copies"},{...L.setInferenceCopies,command:"inference copies <on|off>"},{...L.getInferenceUsage,command:"inference usage"},{...L.getCurrentUser,command:"auth whoami"},{...L.exchangeCliLogin,command:"auth login",public:!0},{...L.getGithubInstallation,command:"onboard"},{...L.getSettingsBusinessReviewDefault,command:"onboard"},{...L.putSettingsBusinessReviewDefault,command:"onboard --automatic-review"},{...L.answerOnboardingQuestion,command:"environments answer"},{...L.listRepositories,command:"repos list"},{...L.listSessions,command:"sessions list"},{...L.getSession,command:"sessions get"},{...L.getSessionView,command:"sessions view"},{...L.getSessionPrompts,command:"sessions events --follow"},{...L.getSessionEvents,command:"sessions events --follow"},{...L.getSessionEventHistory,command:"sessions events"},{...L.exportSession,command:"sessions transcript"},{...L.listSessionArtifacts,command:"sessions artifacts"},{...L.viewSessionArtifact,command:"sessions artifacts get"},{...L.createReview,command:"review <pr-url>"},{...L.getReviewRequest,command:"review <pr-url>"},{...L.getReviewRequest,command:"reviews get"},{...L.getReviewRequestStatuses,command:"reviews get"},{...L.createLocalReview,command:"review"},{...L.getLocalReview,command:"review --request"},{...L.getRepositoryOnboarding,command:"environments status"},{...L.prepareRepository,command:"environments prepare"},{...L.retryRepositoryOnboarding,command:"environments retry"},{...L.listEnvironments,command:"environments export"},{...L.getEnvironment,command:"environments export"},{...L.listEnvironments,command:"environments import"},{...L.getEnvironment,command:"environments import"},{...L.updateEnvironment,command:"environments import"},{...L.createEnvironment,command:"environments import --create"}];import{createHash as um}from"node:crypto";import{existsSync as Pn,mkdirSync as Eb,readFileSync as Na,statSync as Tb}from"node:fs";import{homedir as Ab}from"node:os";import{dirname as cm,join as yt,resolve as Rb}from"node:path";import{randomUUID as Sb}from"node:crypto";import{renameSync as xb,rmSync as Ib,writeFileSync as kb}from"node:fs";function _t(e,t){let r=`${e}.${Sb()}.tmp`;try{kb(r,JSON.stringify(t,null,2)+`
6
6
  `,{mode:384,flag:"wx"}),xb(r,e)}finally{Ib(r,{force:!0})}}var Pb=/\r?\n/,Cb=/^\[|\]$/g,lm=yt(Ab(),".arcanist"),dm=yt(lm,"config.json"),Xe=".arcanist-cli.json",Ob="https://app.tryarcanist.com";function Da(){try{return JSON.parse(Na(dm,"utf-8"))}catch{return null}}function Cn(e){let t=Nb(e);if(t)return sm(t);let r=za(),o=Ua(e,r!==null),n=Da(),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 ${Xe} -> ${u.apiUrl}
7
7
  `),u}function Kr(e,t){let r=Yr(e.apiUrl);if(r)throw new y("user",r);Eb(lm,{recursive:!0,mode:448});let o=Je(e.apiUrl),n=Da(),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 he(e){let t=Cn(e);if(!t)throw new y("auth","Not logged in.",{hint:"Run `arcanist auth login` or set `ARCANIST_TOKEN`."});return t}function Jr(e){let t=e??process.env.ARCANIST_API_URL??Da()?.apiUrl??Ob,r=Yr(t);if(r)throw new y("user",r);return Je(t)}function za(e=process.cwd()){let t=Db(e);if(!t)return null;let r=e;for(;;){let o=yt(r,Xe);if(Pn(o))return Lb(o);if(r===t)return null;let n=cm(r);if(n===r)return null;r=n}}function Yr(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 Ua(e,t){let r=e.apiUrl??process.env.ARCANIST_API_URL,o=e.token??process.env.ARCANIST_TOKEN;if(!t)return!r&&!o?null:{apiUrl:r,token:o};if(r&&!o||!r&&o)throw new y("user",`${Xe} is active; set both ARCANIST_API_URL and ARCANIST_TOKEN, pass both --api-url and --token, or set neither.`);return!r||!o?null:{apiUrl:r,token:o}}function Nb(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=Yr(e.apiUrl);if(t)throw new y("user",t);return{apiUrl:Je(e.apiUrl),token:e.token}}function Db(e){let t=e;for(;;){if(zb(t))return t;let r=cm(t);if(r===t)return null;t=r}}function zb(e){let t=yt(e,".git");if(!Pn(t))return!1;try{let r=Tb(t);if(r.isDirectory())return Pn(yt(t,"HEAD"))&&Pn(yt(t,"config"));if(!r.isFile())return!1;let o=Ub(t);return o?Pn(yt(Rb(e,o),"HEAD")):!1}catch{return!1}}function Ub(e){let t=Na(e,"utf-8").split(Pb).find(o=>o.startsWith("gitdir:"));return t&&t.slice(7).trim()||null}function Lb(e){let t;try{t=JSON.parse(Na(e,"utf-8"))}catch{throw new y("user",`${Xe} is not valid JSON.`)}if(!t||typeof t!="object")throw new y("user",`${Xe} must contain both apiUrl and token.`);let r=t;if(typeof r.apiUrl!="string"||typeof r.token!="string"||!r.apiUrl||!r.token)throw new y("user",`${Xe} must contain both apiUrl and token.`);let o;try{o=new URL(r.apiUrl)}catch{throw new y("user",`${Xe} apiUrl must be a valid URL.`)}if(!pm(o))throw new y("user",`${Xe} apiUrl must be a loopback host.`);let n=Yr(r.apiUrl);if(n)throw new y("user",n);return{apiUrl:Je(r.apiUrl),token:r.token}}function pm(e){let t=e.hostname.replace(Cb,"");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 Be(e){process.stdout.write(`${JSON.stringify(e)}
8
8
  `)}function N(e,t,r,o){if(Ie(e,t)){Be(r);return}o(r)}function K(e,t){let r=ee(e,t);return{runtime:r,config:he(r)}}async function jb(){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 Mt(){return(await jb()).trim()}function mm(e){(e.noColor===!0||!process.stdout.isTTY)&&(process.env.NO_COLOR="1")}var Mb=/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,Fb=/\u001b\[[0-?]*[ -\/]*[@-~]/g,Zb=/[\u0000-\u001f\u007f]/g,Vb=/\r?\n/;function j(e){return e.replace(Mb,"").replace(Fb,"").replace(Zb,"")}function _e(e){return e.split(Vb).map(j).join(`
@@ -69,7 +69,7 @@ ${u}
69
69
 
70
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 Cg(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;Cg(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 Og=new Set(["type","properties","required","additionalProperties"]),Rg=["oneOf","anyOf"];function Pg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function ml(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Og.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]??Pg(c);l!=null&&(s.some(d=>JSON.stringify(d)===JSON.stringify(l))||s.push(l))}let u=s.length===1?s[0]:ml(s)??{allOf:s};se(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let s=Pg(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 uI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Og)if(n in e)return;let r=t.filter(n=>Rg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=ml(t);else{let n=r[0],i=Rg.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=>ml([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,vr(e,o))}function st(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){o(d);let p=e.seen.get(d),v=p.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(v)):vr(c,v),vr(c,l),s._zod.parent===d)for(let S in c)S==="$ref"||S==="allOf"||S in l||delete c[S];if(v.$ref&&p.def)for(let S in c)S==="$ref"||S==="allOf"||S in p.def&&JSON.stringify(c[S])===JSON.stringify(p.def[S])&&delete c[S]}let m=s._zod.parent;if(m&&m!==d){o(m);let p=e.seen.get(m);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let v in c)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(c[v])===JSON.stringify(p.def[v])&&delete c[v]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Cg(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)??[])uI(c)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}vr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,se(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:hn(t,"input",e.processors),output:hn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ge(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ge(o.element,r);if(o.type==="set")return ge(o.valueType,r);if(o.type==="lazy")return ge(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return ge(o.innerType,r);if(o.type==="intersection")return ge(o.left,r)||ge(o.right,r);if(o.type==="record"||o.type==="map")return ge(o.keyType,r)||ge(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ge(o.in,r)||ge(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ge(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ge(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ge(n,r))return!0;return!!(o.rest&&ge(o.rest,r))}return!1}var fl=(e,t={})=>r=>{let o=ot({...r,processors:t});return W(e,o),at(o,e),st(o,e)},hn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=ot({...n??{},target:i,io:t,processors:r});return W(e,a),at(a,e),st(a,e)};var _n=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},yn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Ng=(e,t)=>{_n(e,"minimum",t),yn(e,"maximum",t)},Lg=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},jg=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Mg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Fg=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Dg=(e,t)=>_n(e,"minimum",t.minimum),zg=(e,t)=>yn(e,"maximum",t.maximum),Ug=e=>(t,r)=>{Fg(t,r.format);let[o,n]=e[r.format];_n(t,"minimum",o),yn(t,"maximum",n)},cI={greater_than:(e,t)=>_n(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>yn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Lg(e,t.value),number_format:Ug(Un),bigint_format:Ug(Ln),min_length:Dg,max_length:zg,length_equals:(e,t)=>Ng(e,t.length),min_size:Dg,max_size:zg,size_equals:(e,t)=>Ng(e,t.size),string_format:(e,t)=>{Fg(e,t.format),t.pattern&&jg(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)=>Mg(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)cI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&_n(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&_n(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&yn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&yn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Lg(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Mg(t,n.mime);for(let i of n.patterns??[])jg(t,i);return t}var lI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dI=new Map([[Ti,bs],[tr,ws]]),Zg=e=>dI.get(e)??e,hl=(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=lI[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(Zg);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}))])}},_l=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:c,isInt:l}=ie(e);n.type=l?"integer":"number";let d=typeof c=="number"&&c>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(n.minimum=c,n.exclusiveMinimum=!0):n.exclusiveMinimum=c:typeof i=="number"&&(n.minimum=i),m?p?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let E of s)Number.isFinite(E)&&E!==0?v.add(Math.abs(E)):re(e,t,n,o,`A multipleOf divisor of ${E} cannot be represented in JSON Schema`);let[_,...S]=v;_!==void 0&&(n.multipleOf=_),S.length&&(n.allOf=[...n.allOf??[],...S.map(E=>({multipleOf:E}))])}},yl=(e,t,r,o)=>{r.type="boolean"},bl=(e,t,r,o)=>{re(e,t,r,o,"BigInt cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{re(e,t,r,o,"Symbols cannot be represented in JSON Schema")},$l=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Sl=(e,t,r,o)=>{re(e,t,r,o,"Undefined cannot be represented in JSON Schema")},xl=(e,t,r,o)=>{re(e,t,r,o,"Void cannot be represented in JSON Schema")},Il=(e,t,r,o)=>{r.not={}},kl=(e,t,r,o)=>{},El=(e,t,r,o)=>{},Tl=(e,t,r,o)=>{re(e,t,r,o,"Date cannot be represented in JSON Schema")},Al=(e,t,r,o)=>{let n=e._zod.def,i=Zt(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},Rl=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(re(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(re(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Pl=(e,t,r,o)=>{re(e,t,r,o,"NaN cannot be represented in JSON Schema")},Cl=(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},Ol=(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})))},Nl=(e,t,r,o)=>{r.type="boolean"},Dl=(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")},Ul=(e,t,r,o)=>{re(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Ll=(e,t,r,o)=>{re(e,t,r,o,"Map cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{re(e,t,r,o,"Set cannot be represented in JSON Schema")},Ml=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ie(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=W(i.element,t,{...o,path:[...o.path,"items"]})};function hr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?hr(t.out):t.type==="catch"?hr(t.innerType):e._zod.optin}var Fl=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&re(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let c in a)se(n.properties,c,W(a[c],t,{...o,path:[...o.path,"properties",c]}));let u=[];for(let c of Object.keys(a)){let l=i.shape[c];(t.io==="input"?hr(l)===void 0:l._zod.optout===void 0)&&u.push(c)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=W(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},ko=(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},Zl=(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)},Vl=(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((_,S)=>W(_,t,{...o,path:[...o.path,a,S]})),c=i.rest?W(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let _=i.items[l-1];if(!(t.io==="input"?hr(_)!==void 0:_._zod.optout==="optional"))break;l--}let d=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:c&&(n.items=c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:u},c&&n.items.anyOf.push(c),l>0&&(n.minItems=l),m&&(n.maxItems=d)):(n.items=u,m?n.additionalItems=!1:c&&(n.additionalItems=c),l>0&&(n.minItems=l),m&&(n.maxItems=d));let{minimum:p,maximum:v}=ie(e);typeof p=="number"&&(n.minItems=p),typeof v=="number"&&(n.maxItems=v)};function gl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let v=e.get(t)?.def;if(!v)return t;let _=gl(e,v,r);return _===v?t:_}for(let v of["anyOf","oneOf"]){let _=t[v];if(!Array.isArray(_))continue;let S=_.map(E=>gl(e,E,r));S.some((E,k)=>E!==_[k])&&(t={...t,[v]:S})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(v=>v==="number"||v==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(v=>typeof v=="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:l,format:d,id:m,...p}=t;return p.enum?p.enum=p.enum.map(v=>typeof v=="number"?String(v):v):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?He:Wn).source)),p}var vl=new WeakMap;function pI(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 vl.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=gl(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var Bl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ie(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let l=W(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of s)se(n.patternProperties,Zg(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=vl.get(t);l||(l=[],vl.set(t,l),t.deferred.push(()=>pI(t))),l.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,c=t.io==="input"&&hr(i.valueType)!==void 0;if(u&&!i.partial&&!c){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},Gl=(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"}]},ql=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Hl=Symbol();function Vg(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"),Hl):JSON.parse(a)}var Wl=(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=Vg(n.defaultValue,e,t,r,o);a!==Hl&&(r.default=a)},Kl=(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=Vg(n.defaultValue,e,t,r,o);a!==Hl&&(r._prefault=a)},Jl=(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},Yl=(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},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,r.readOnly=!0},Ql=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Eo=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ed=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},Io={string:hl,number:_l,boolean:yl,bigint:bl,symbol:wl,null:$l,undefined:Sl,void:xl,never:Il,any:kl,unknown:El,date:Tl,enum:Al,literal:Rl,nan:Pl,template_literal:Cl,file:Ol,success:Nl,custom:Dl,function:zl,transform:Ul,map:Ll,set:jl,array:Ml,object:Fl,union:ko,intersection:Zl,tuple:Vl,record:Bl,nullable:Gl,nonoptional:ql,default:Wl,prefault:Kl,catch:Jl,pipe:Yl,readonly:Xl,promise:Ql,optional:Eo,lazy:ed};function To(e,t){if("_idmap"in e){let o=e,n=ot({...t,processors:Io}),i={};for(let u of o._idmap.entries()){let[c,l]=u;W(l,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[c,l]=u;at(n,l),se(a,c,st(n,l))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=ot({...t,processors:Io});return W(e,r),at(r,e),st(r,e)}var Ao=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ot({processors:Io,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return W(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,at(this.ctx,t);let o=st(this.ctx,t),{"~standard":n,...i}=o;return i}};var Bg={};var En={};Ve(En,{ZodAny:()=>$d,ZodArray:()=>kd,ZodBase64:()=>Wo,ZodBase64URL:()=>Ko,ZodBigInt:()=>In,ZodBigIntFormat:()=>Xo,ZodBoolean:()=>xn,ZodCIDRv4:()=>qo,ZodCIDRv6:()=>Ho,ZodCUID:()=>jo,ZodCUID2:()=>Mo,ZodCatch:()=>Hd,ZodCodec:()=>Er,ZodCreditCard:()=>fd,ZodCustom:()=>Tr,ZodCustomStringFormat:()=>zt,ZodDate:()=>wr,ZodDefault:()=>Fd,ZodDiscriminatedUnion:()=>Td,ZodE164:()=>Jo,ZodEmail:()=>Do,ZodEmoji:()=>Uo,ZodEnum:()=>wn,ZodExactOptional:()=>na,ZodFile:()=>Ud,ZodFunction:()=>rp,ZodGUID:()=>zo,ZodIBAN:()=>gd,ZodIPv4:()=>Bo,ZodIPv6:()=>Go,ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,ZodInstanceOf:()=>ap,ZodIntersection:()=>Ad,ZodJWT:()=>Yo,ZodKSUID:()=>Vo,ZodLazy:()=>ep,ZodLiteral:()=>zd,ZodMAC:()=>md,ZodMap:()=>Nd,ZodNaN:()=>Kd,ZodNanoID:()=>Lo,ZodNever:()=>xd,ZodNonOptional:()=>ra,ZodNull:()=>bd,ZodNullable:()=>Md,ZodNumber:()=>Sn,ZodNumberFormat:()=>Ut,ZodObject:()=>Sr,ZodOptional:()=>Ir,ZodPipe:()=>kr,ZodPrefault:()=>Vd,ZodPreprocess:()=>Jd,ZodPromise:()=>np,ZodReadonly:()=>Yd,ZodRecord:()=>bn,ZodSet:()=>Dd,ZodString:()=>$n,ZodStringFormat:()=>J,ZodSuccess:()=>qd,ZodSymbol:()=>_d,ZodTemplateLiteral:()=>Qd,ZodTransform:()=>Ld,ZodTuple:()=>Pd,ZodType:()=>M,ZodULID:()=>Fo,ZodURL:()=>br,ZodUUID:()=>Fe,ZodUndefined:()=>yd,ZodUnion:()=>xr,ZodUnknown:()=>Sd,ZodVoid:()=>Id,ZodXID:()=>Zo,ZodXor:()=>Ed,_ZodString:()=>No,_default:()=>Zd,_function:()=>nh,any:()=>Ov,array:()=>$r,base64:()=>mv,base64url:()=>fv,bigint:()=>Tv,boolean:()=>hd,catch:()=>Wd,check:()=>rh,cidrv4:()=>dv,cidrv6:()=>pv,codec:()=>Xv,creditCard:()=>vv,cuid:()=>rv,cuid2:()=>iv,currencyCode:()=>$v,custom:()=>ih,date:()=>Dv,describe:()=>oh,discriminatedUnion:()=>Fv,e164:()=>gv,email:()=>Hg,emoji:()=>tv,enum:()=>ea,exactOptional:()=>jd,file:()=>Wv,float32:()=>xv,float64:()=>Iv,function:()=>nh,guid:()=>Wg,hash:()=>Sv,hex:()=>wv,hostname:()=>bv,httpUrl:()=>ev,iban:()=>hv,instanceof:()=>sh,int:()=>Co,int32:()=>kv,int64:()=>Av,intersection:()=>Rd,invertCodec:()=>Qv,ipv4:()=>uv,ipv6:()=>lv,json:()=>ch,jwt:()=>_v,keyof:()=>zv,ksuid:()=>sv,lazy:()=>tp,literal:()=>Hv,looseObject:()=>jv,looseRecord:()=>Vv,mac:()=>cv,map:()=>Bv,meta:()=>ah,nan:()=>Yv,nanoid:()=>nv,nativeEnum:()=>qv,never:()=>Qo,nonoptional:()=>Gd,null:()=>wd,nullable:()=>yr,nullish:()=>Kv,number:()=>vd,object:()=>Uv,optional:()=>Nt,partialRecord:()=>Zv,pipe:()=>Oo,prefault:()=>Bd,preprocess:()=>lh,promise:()=>th,readonly:()=>Xd,record:()=>Od,refine:()=>ip,set:()=>Gv,strictObject:()=>Lv,string:()=>_r,stringFormat:()=>yv,stringbool:()=>uh,success:()=>Jv,superRefine:()=>op,symbol:()=>Pv,templateLiteral:()=>eh,transform:()=>ta,tuple:()=>Cd,uint32:()=>Ev,uint64:()=>Rv,ulid:()=>ov,undefined:()=>Cv,union:()=>kn,unknown:()=>Ot,url:()=>Qg,uuid:()=>Kg,uuidv4:()=>Jg,uuidv6:()=>Yg,uuidv7:()=>Xg,void:()=>Nv,xid:()=>av,xor:()=>Mv});var Ro={};Ve(Ro,{endsWith:()=>cn,gt:()=>je,gte:()=>Ee,includes:()=>sn,length:()=>Pt,lowercase:()=>on,lt:()=>Le,lte:()=>ke,maxLength:()=>Rt,maxSize:()=>it,mime:()=>dn,minLength:()=>We,minSize:()=>Me,multipleOf:()=>rt,negative:()=>wo,nonnegative:()=>So,nonpositive:()=>$o,normalize:()=>pn,overwrite:()=>ze,positive:()=>bo,properties:()=>ln,property:()=>xo,regex:()=>rn,size:()=>At,slugify:()=>vn,startsWith:()=>un,toLowerCase:()=>fn,toUpperCase:()=>gn,trim:()=>mn,uppercase:()=>an});var Gg=new WeakSet([Object.prototype,Error.prototype]);function Po(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var qg=(e,t)=>{es.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Gg.has(r)||(Gg.add(r),Po(r,"format",o=>n=>Bn(o,n)),Po(r,"flatten",o=>n=>Vn(o,n)),Po(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Vt,2)}),Po(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}}))},fI=g("ZodError",qg),Se=g("ZodError",qg,void 0,{Parent:Error});var td=Wt(Se),nd=Kt(Se),rd=Jt(Se),id=Yt(Se),od=oi(Se),ad=ai(Se),sd=si(Se),ud=ui(Se),cd=ci(Se),ld=li(Se),dd=di(Se),pd=pi(Se);function vI(){oe.localeError||te(Bi())}function Dt(){oe.memoizer||te({memoizer:ur()})}var M=g("ZodType",(e,t)=>(vI(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return q(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ip(e,t))},superRefine(e,t){return this.check(op(e,t))},overwrite(e){return this.check(ze(e))},optional(){return Nt(this)},exactOptional(){return jd(this)},nullable(){return yr(this)},nullish(){return Nt(yr(this))},nonoptional(e){return Gd(this,e)},array(){return $r(this)},or(e){return kn([this,e])},and(e){return Rd(this,e)},transform(e){return Oo(this,ta(e))},default(e){return Zd(this,e)},prefault(e){return Bd(this,e)},catch(e){return Wd(this,e)},pipe(e){return Oo(this,e)},readonly(){return Xd(this)},describe(e){let t=this.clone();return ue.add(t,{description:e}),t},meta(...e){if(e.length===0)return ue.get(this);let t=this.clone();return ue.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return b.hide(this,"~standard",{...Si(this),jsonSchema:{input:hn(this,"input"),output:hn(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return td(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await nd(this,t,r,{callee:e})},safeParse(e,t){return rd(this,e,t)},async safeParseAsync(e,t){return id(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return Gn(this,e,t)},validateAsync(e,t){return qn(this,e,t)},encode:function e(t,r){return od(this,t,r,{callee:e})},decode:function e(t,r){return ad(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await sd(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await ud(this,t,r,{callee:e})},safeEncode(e,t){return cd(this,e,t)},safeDecode(e,t){return ld(this,e,t)},async safeEncodeAsync(e,t){return dd(this,e,t)},async safeDecodeAsync(e,t){return pd(this,e,t)},toJSONSchema(e){return fl(this,{})(e)},get description(){return ue.get(this)?.description},get _def(){return this._zod.def}}),No=g("_ZodString",(e,t)=>{It.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hl(e,r,o,n)},b.derived({format:e=>ie(e).format??null,minLength:e=>ie(e).minimum??null,maxLength:e=>ie(e).maximum??null},{regex(...e){return this.check(rn(...e))},includes(...e){return this.check(sn(...e))},startsWith(...e){return this.check(un(...e))},endsWith(...e){return this.check(cn(...e))},min(...e){return this.check(We(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Pt(...e))},nonempty(...e){return this.check(We(1,...e))},lowercase(e){return this.check(on(e))},uppercase(e){return this.check(an(e))},trim(){return this.check(mn())},normalize(...e){return this.check(pn(...e))},toLowerCase(){return this.check(fn())},toUpperCase(){return this.check(gn())},slugify(){return this.check(vn())}})),$n=g("ZodString",(e,t)=>{It.init(e,t),No.init(e,t)},{email(e){return this.check(Xi(Do,e))},url(e){return this.check(dr(br,e))},jwt(e){return this.check(yo(Yo,e))},emoji(e){return this.check(io(Uo,e))},guid(e){return this.check(Qi(zo,e))},uuid(e){return this.check(eo(Fe,e))},uuidv4(e){return this.check(to(Fe,e))},uuidv6(e){return this.check(no(Fe,e))},uuidv7(e){return this.check(ro(Fe,e))},nanoid(e){return this.check(oo(Lo,e))},cuid(e){return this.check(ao(jo,e))},cuid2(e){return this.check(so(Mo,e))},ulid(e){return this.check(uo(Fo,e))},base64(e){return this.check(vo(Wo,e))},base64url(e){return this.check(ho(Ko,e))},xid(e){return this.check(co(Zo,e))},ksuid(e){return this.check(lo(Vo,e))},ipv4(e){return this.check(po(Bo,e))},ipv6(e){return this.check(mo(Go,e))},cidrv4(e){return this.check(fo(qo,e))},cidrv6(e){return this.check(go(Ho,e))},e164(e){return this.check(_o(Jo,e))},datetime(e){return this.check(pr(ut,e))},date(e){return this.check(mr(ct,e))},time(e){return this.check(fr(lt,e))},duration(e){return this.check(gr(dt,e))}});function _r(e){return Rc($n,e)}var J=g("ZodStringFormat",(e,t)=>{H.init(e,t),No.init(e,t)}),ut=g("ZodISODateTime",(e,t)=>{bu.init(e,t),J.init(e,t)}),ct=g("ZodISODate",(e,t)=>{wu.init(e,t),J.init(e,t)}),lt=g("ZodISOTime",(e,t)=>{$u.init(e,t),J.init(e,t)}),dt=g("ZodISODuration",(e,t)=>{Su.init(e,t),J.init(e,t)}),Do=g("ZodEmail",(e,t)=>{cu.init(e,t),J.init(e,t)});function Hg(e){return Xi(Do,e)}var zo=g("ZodGUID",(e,t)=>{su.init(e,t),J.init(e,t)});function Wg(e){return Qi(zo,e)}var Fe=g("ZodUUID",(e,t)=>{uu.init(e,t),J.init(e,t)});function Kg(e){return eo(Fe,e)}function Jg(e){return to(Fe,e)}function Yg(e){return no(Fe,e)}function Xg(e){return ro(Fe,e)}var br=g("ZodURL",(e,t)=>{pu.init(e,t),J.init(e,t)});function Qg(e){return dr(br,e)}function ev(e){return dr(br,{protocol:Hn,hostname:Ss,...b.normalizeParams(e)})}var Uo=g("ZodEmoji",(e,t)=>{mu.init(e,t),J.init(e,t)});function tv(e){return io(Uo,e)}var Lo=g("ZodNanoID",(e,t)=>{fu.init(e,t),J.init(e,t)});function nv(e){return oo(Lo,e)}var jo=g("ZodCUID",(e,t)=>{gu.init(e,t),J.init(e,t)});function rv(e){return ao(jo,e)}var Mo=g("ZodCUID2",(e,t)=>{vu.init(e,t),J.init(e,t)});function iv(e){return so(Mo,e)}var Fo=g("ZodULID",(e,t)=>{hu.init(e,t),J.init(e,t)});function ov(e){return uo(Fo,e)}var Zo=g("ZodXID",(e,t)=>{_u.init(e,t),J.init(e,t)});function av(e){return co(Zo,e)}var Vo=g("ZodKSUID",(e,t)=>{yu.init(e,t),J.init(e,t)});function sv(e){return lo(Vo,e)}var Bo=g("ZodIPv4",(e,t)=>{xu.init(e,t),J.init(e,t)});function uv(e){return po(Bo,e)}var md=g("ZodMAC",(e,t)=>{ku.init(e,t),J.init(e,t)});function cv(e){return Cc(md,e)}var Go=g("ZodIPv6",(e,t)=>{Iu.init(e,t),J.init(e,t)});function lv(e){return mo(Go,e)}var qo=g("ZodCIDRv4",(e,t)=>{Eu.init(e,t),J.init(e,t)});function dv(e){return fo(qo,e)}var Ho=g("ZodCIDRv6",(e,t)=>{Tu.init(e,t),J.init(e,t)});function pv(e){return go(Ho,e)}var Wo=g("ZodBase64",(e,t)=>{Au.init(e,t),J.init(e,t)});function mv(e){return vo(Wo,e)}var Ko=g("ZodBase64URL",(e,t)=>{Ru.init(e,t),J.init(e,t)});function fv(e){return ho(Ko,e)}var Jo=g("ZodE164",(e,t)=>{Pu.init(e,t),J.init(e,t)});function gv(e){return _o(Jo,e)}var fd=g("ZodCreditCard",(e,t)=>{Cu.init(e,t),J.init(e,t)});function vv(e){return Oc(fd,e)}var gd=g("ZodIBAN",(e,t)=>{Ou.init(e,t),J.init(e,t)});function hv(e){return Nc(gd,e)}var Yo=g("ZodJWT",(e,t)=>{Nu.init(e,t),J.init(e,t)});function _v(e){return yo(Yo,e)}var zt=g("ZodCustomStringFormat",(e,t)=>{Du.init(e,t),J.init(e,t)});function yv(e,t,r={}){return Ct(zt,e,t,r)}function bv(e){return Ct(zt,"hostname",$s,e)}function wv(e){return Ct(zt,"hex",Us,e)}function $v(e){return Ct(zt,"currency_code",Is,e)}function Sv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ce[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Ct(zt,o,n,t)}var Sn=g("ZodNumber",(e,t)=>{Oi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_l(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ie(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ie(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ie(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ie(e).format??null},{gt(e,t){return this.check(je(e,t))},gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},lt(e,t){return this.check(Le(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(Co(e))},safe(e){return this.check(Co(e))},positive(e){return this.check(je(0,e))},nonnegative(e){return this.check(Ee(0,e))},negative(e){return this.check(Le(0,e))},nonpositive(e){return this.check(ke(0,e))},multipleOf(e,t){return this.check(rt(e,t))},step(e,t){return this.check(rt(e,t))},finite(){return this}}));function vd(e){return zc(Sn,e)}var Ut=g("ZodNumberFormat",(e,t)=>{zu.init(e,t),Sn.init(e,t)});function Co(e){return Lc(Ut,e)}function xv(e){return jc(Ut,e)}function Iv(e){return Mc(Ut,e)}function kv(e){return Fc(Ut,e)}function Ev(e){return Zc(Ut,e)}var xn=g("ZodBoolean",(e,t)=>{nr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yl(e,r,o,n)});function hd(e){return Vc(xn,e)}var In=g("ZodBigInt",(e,t)=>{Ni.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bl(e,r,o,n)},b.derived({minValue:e=>ie(e).minimum??null,maxValue:e=>ie(e).maximum??null,format:e=>ie(e).format??null},{gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},gt(e,t){return this.check(je(e,t))},lt(e,t){return this.check(Le(e,t))},lte(e,t){return this.check(ke(e,t))},max(e,t){return this.check(ke(e,t))},positive(e){return this.check(je(BigInt(0),e))},negative(e){return this.check(Le(BigInt(0),e))},nonpositive(e){return this.check(ke(BigInt(0),e))},nonnegative(e){return this.check(Ee(BigInt(0),e))},multipleOf(e,t){return this.check(rt(e,t))}}));function Tv(e){return Gc(In,e)}var Xo=g("ZodBigIntFormat",(e,t)=>{Uu.init(e,t),In.init(e,t)});function Av(e){return Hc(Xo,e)}function Rv(e){return Wc(Xo,e)}var _d=g("ZodSymbol",(e,t)=>{Lu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Pv(e){return Kc(_d,e)}var yd=g("ZodUndefined",(e,t)=>{ju.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sl(e,r,o,n)});function Cv(e){return Jc(yd,e)}var bd=g("ZodNull",(e,t)=>{Mu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n)});function wd(e){return Yc(bd,e)}var $d=g("ZodAny",(e,t)=>{Fu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)});function Ov(){return Xc($d)}var Sd=g("ZodUnknown",(e,t)=>{Zu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)});function Ot(){return Qc(Sd)}var xd=g("ZodNever",(e,t)=>{Vu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function Qo(e){return el(xd,e)}var Id=g("ZodVoid",(e,t)=>{Bu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Nv(e){return tl(Id,e)}var wr=g("ZodDate",(e,t)=>{Gu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n),e.min=(r,o)=>e.check(Ee(r,o)),e.max=(r,o)=>e.check(ke(r,o))},b.derived({minDate:e=>{let{minimum:t}=ie(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ie(e);return t?new Date(t):null}},{}));function Dv(e){return nl(wr,e)}var kd=g("ZodArray",(e,t)=>{Dt(),Hu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.element=t.element},{min(e,t){return this.check(We(e,t))},nonempty(e){return this.check(We(1,e))},max(e,t){return this.check(Rt(e,t))},length(e,t){return this.check(Pt(e,t))},unwrap(){return this.element}});function $r(e,t){return ol(kd,e,t)}function zv(e){let t=e._zod.def.shape;return ea(Object.keys(t))}var Sr=g("ZodObject",(e,t)=>{Dt(),Wu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ea(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ot()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ot()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Qo()}))},strip(){return this.clone(b.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return b.extend(this,e)},safeExtend(e){return b.safeExtend(this,e)},merge(e){return b.merge(this,e)},pick(e){return b.pick(this,e)},omit(e){return b.omit(this,e)},partial(...e){return b.partial(Ir,this,e[0])},exactPartial(...e){return b.partial(na,this,e[0],"exactPartial")},required(...e){return b.required(ra,this,e[0])}});function Uv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new Sr(r)}function Lv(e,t){return new Sr({type:"object",shape:e,catchall:Qo(),...b.normalizeParams(t)})}function jv(e,t){return new Sr({type:"object",shape:e,catchall:Ot(),...b.normalizeParams(t)})}var xr=g("ZodUnion",(e,t)=>{rr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.options=t.options});function kn(e,t){return new xr({type:"union",options:e,...b.normalizeParams(t)})}var Ed=g("ZodXor",(e,t)=>{xr.init(e,t),Ku.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ko(e,r,o,n),e.options=t.options});function Mv(e,t){return new Ed({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var Td=g("ZodDiscriminatedUnion",(e,t)=>{xr.init(e,t),Yu.init(e,t)});function Fv(e,t,r){return new Td({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var Ad=g("ZodIntersection",(e,t)=>{Xu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)});function Rd(e,t){return new Ad({type:"intersection",left:e,right:t})}var Pd=g("ZodTuple",(e,t)=>{Dt(),Di.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Ir({type:"optional",innerType:t}))})}});function Cd(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new Pd({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var bn=g("ZodRecord",(e,t)=>{Dt(),Qu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Od(e,t,r){return!t||!t._zod?new bn({type:"record",keyType:_r(),valueType:e,...b.normalizeParams(t)}):new bn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function Zv(e,t,r){return new bn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Vv(e,t,r){return new bn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var Nd=g("ZodMap",(e,t)=>{Dt(),ec.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(At(...r))});function Bv(e,t,r){return new Nd({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var Dd=g("ZodSet",(e,t)=>{Dt(),tc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.min=(...r)=>e.check(Me(...r)),e.nonempty=r=>e.check(Me(1,r)),e.max=(...r)=>e.check(it(...r)),e.size=(...r)=>e.check(At(...r))});function Gv(e,t){return new Dd({type:"set",valueType:e,...b.normalizeParams(t)})}var wn=g("ZodEnum",(e,t)=>{nc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Al(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 wn({...t,checks:[],...b.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new wn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function ea(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new wn({type:"enum",entries:r,...b.normalizeParams(t)})}function qv(e,t){return new wn({type:"enum",entries:e,...b.normalizeParams(t)})}var zd=g("ZodLiteral",(e,t)=>{rc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(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 Hv(e,t){return new zd({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var Ud=g("ZodFile",(e,t)=>{ic.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.min=(r,o)=>e.check(Me(r,o)),e.max=(r,o)=>e.check(it(r,o)),e.mime=(r,o)=>e.check(dn(Array.isArray(r)?r:[r],o))});function Wv(e){return al(Ud,e)}var Ld=g("ZodTransform",(e,t)=>{Dt(),oc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new tt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(b.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push(b.issue(a))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ta(e){return new Ld({type:"transform",transform:e})}var Ir=g("ZodOptional",(e,t)=>{zi.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Eo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Nt(e){return new Ir({type:"optional",innerType:e})}var na=g("ZodExactOptional",(e,t)=>{ac.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Eo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function jd(e){return new na({type:"optional",innerType:e})}var Md=g("ZodNullable",(e,t)=>{sc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new Md({type:"nullable",innerType:e})}function Kv(e){return Nt(yr(e))}var Fd=g("ZodDefault",(e,t)=>{uc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zd(e,t){return new Fd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Vd=g("ZodPrefault",(e,t)=>{cc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bd(e,t){return new Vd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var ra=g("ZodNonOptional",(e,t)=>{lc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Gd(e,t){return new ra({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var qd=g("ZodSuccess",(e,t)=>{dc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Jv(e){return new qd({type:"success",innerType:e})}var Hd=g("ZodCatch",(e,t)=>{pc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wd(e,t){return new Hd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Kd=g("ZodNaN",(e,t)=>{mc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Yv(e){return il(Kd,e)}var kr=g("ZodPipe",(e,t)=>{Ui.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.in=t.in,e.out=t.out});function Oo(e,t){return new kr({type:"pipe",in:e,out:t})}var Er=g("ZodCodec",(e,t)=>{kr.init(e,t),ir.init(e,t)});function Xv(e,t,r){return new Er({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Qv(e){let t=e._zod.def;return new Er({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Jd=g("ZodPreprocess",(e,t)=>{kr.init(e,t),fc.init(e,t)}),Yd=g("ZodReadonly",(e,t)=>{gc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Xd(e){return new Yd({type:"readonly",innerType:e})}var Qd=g("ZodTemplateLiteral",(e,t)=>{vc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n)});function eh(e,t){return new Qd({type:"template_literal",parts:e,...b.normalizeParams(t)})}var ep=g("ZodLazy",(e,t)=>{or.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function tp(e){return new ep({type:"lazy",getter:e})}var np=g("ZodPromise",(e,t)=>{_c.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function th(e){return new np({type:"promise",innerType:e})}var rp=g("ZodFunction",(e,t)=>{hc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function nh(e){return new rp({type:"function",input:Array.isArray(e?.input)?Cd(e?.input):e?.input??$r(Ot()),output:e?.output??Ot()})}var Tr=g("ZodCustom",(e,t)=>{yc.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n)});function rh(e){let t=new Y({check:"custom"});return t._zod.check=e,t}function ih(e,t){return sl(Tr,e??(()=>!0),t)}function ip(e,t={}){return ul(Tr,e,t)}function op(e,t){return cl(e,t)}var oh=ll,ah=dl,ap=g("ZodInstanceOf",(e,t)=>{Tr.init(e,t)},{properties(e,t){return this.check(ln(e,t))}});function sh(e,t={}){let r=new ap({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...b.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var uh=(...e)=>pl({Codec:Er,Boolean:xn,String:$n},...e);function ch(e){let t=tp(()=>kn([_r(e),vd(),hd(),wd(),$r(t),Od(_r(),t)]));return t}function lh(e,t){return new Jd({type:"pipe",in:ta(e),out:t})}var hI={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 _I(e){te({customError:e})}function yI(){return te().customError}var sp;sp||(sp={});var Ar={};Ve(Ar,{ZodISODate:()=>ct,ZodISODateTime:()=>ut,ZodISODuration:()=>dt,ZodISOTime:()=>lt,date:()=>wI,datetime:()=>bI,duration:()=>SI,time:()=>$I});function bI(e){return pr(ut,e)}function wI(e){return mr(ct,e)}function $I(e){return fr(lt,e)}function SI(e){return gr(dt,e)}var T={...En,...Ro,iso:Ar},xI=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 II(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 dh(e,t){return e.map((r,o)=>o<t?r:r.optional())}function kI(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function EI(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:kI(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 TI(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 up(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=up(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=up(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 AI=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),RI=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Rr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Rr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>AI.has(t)?Rr(r):!RI.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Rr))}function ph(e){return e===1?"element":"elements"}function PI(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=up(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 ${ph(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 ${ph(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function mh(e,t){if(e!==!1)return e===void 0||e===!0?T.any():ve(e,t)}var CI=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function fh(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=EI(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 fh(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(CI)):i==="duration"?n=n.check(T.iso.duration()):i==="hostname"?n=n.check(T.hostname()):i==="ipv4"?n=n.check(T.ipv4()):i==="ipv6"?n=n.check(T.ipv6()):i==="mac"?n=n.check(T.mac()):i==="cidr"?n=n.check(T.cidrv4()):i==="cidr-v6"?n=n.check(T.cidrv6()):i==="base64"?n=n.check(T.base64()):i==="base64url"?n=n.check(T.base64url()):i==="e164"?n=n.check(T.e164()):i==="credit_card"?n=n.check(T.creditCard()):i==="iban"?n=n.check(T.iban()):i==="jwt"?n=n.check(T.jwt()):i==="emoji"?n=n.check(T.emoji()):i==="nanoid"?n=n.check(T.nanoid()):i==="cuid"?n=n.check(T.cuid()):i==="cuid2"?n=n.check(T.cuid2()):i==="ulid"?n=n.check(T.ulid()):i==="xid"?n=n.check(T.xid()):i==="ksuid"&&(n=n.check(T.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?T.number().int():T.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=T.boolean();break}case"null":{o=T.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ve(e.additionalProperties,t):void 0;for(let[d,m]of Object.entries(i)){let p=ve(m,t);se(n,d,a.has(d)?p:p.optional())}if(e.patternProperties){let d=e.patternProperties,m=Object.keys(d),p=[];for(let _ of m){let S=ve(d[_],t),E=T.string().regex(new RegExp(_));p.push(T.looseRecord(E,S))}let v=[];if(Object.keys(n).length>0&&v.push(T.object(n).passthrough()),v.push(...p),v.length===0)o=T.object({}).passthrough();else if(v.length===1)o=v[0];else{let _=T.intersection(v[0],v[1]);for(let S=2;S<v.length;S++)_=T.intersection(_,v[S]);o=_}if(e.additionalProperties===!1){let _=Object.keys(n),S=m.map(k=>new RegExp(k)),E=o;o=o.check(k=>{if(!Re(k.value))return;let A=[];for(let x of Object.keys(k.value))_.includes(x)||S.some(O=>O.test(x))||A.push(x);A.length&&k.issues.push({code:"unrecognized_keys",keys:A,input:k.value,inst:E})})}}else{let d=T.object(n);e.additionalProperties===!1?o=d.strict():s?o=d.catchall(s):o=d.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||l!==void 0){let d;if(u){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=ve(m,t)}o=TI(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=dh(s,a),c=Array.isArray(i)?void 0:mh(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=dh(s,a),c=mh(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=PI(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=fh(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&&!Rr(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&&!Rr(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))xI.has(s)||se(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function gh(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=II(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??ue};return ve(r,i)}var vh=Symbol("z.visit/resolving");function Pr(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===vh)return new or({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,vh);let u=i(a),c=r(u,u!==a);return o.set(a,c),c}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,l=Object.keys(c),d=!1,m={};for(let v of l){let _=n(c[v]);_!==c[v]&&(d=!0),m[v]=_}let p=s.catchall;return s.catchall&&(p=n(s.catchall),p!==s.catchall&&(d=!0)),d?q(a,{...s,shape:m,catchall:p}):a}case"array":{let c=n(s.element);return c===s.element?a:q(a,{...s,element:c})}case"tuple":{let c=s.items,l=!1,d=[];for(let p of c){let v=n(p);v!==p&&(l=!0),d.push(v)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(l=!0)),l?q(a,{...s,items:d,rest:m}):a}case"record":case"map":{let c=n(s.keyType),l=n(s.valueType);return c===s.keyType&&l===s.valueType?a:q(a,{...s,keyType:c,valueType:l})}case"set":{let c=n(s.valueType);return c===s.valueType?a:q(a,{...s,valueType:c})}case"union":{let c=s.options,l=!1,d=[];for(let m of c){let p=n(m);p!==m&&(l=!0),d.push(p)}return l?q(a,{...s,options:d}):a}case"intersection":{let c=n(s.left),l=n(s.right);return c===s.left&&l===s.right?a:q(a,{...s,left:c,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=n(s.innerType);return c===s.innerType?a:q(a,{...s,innerType:c})}case"pipe":{let c=n(s.in),l=n(s.out);return c===s.in&&l===s.out?a:q(a,{...s,in:c,out:l})}case"function":{let c=n(s.input),l=n(s.output);return c===s.input&&l===s.output?a:q(a,{...s,input:c,output:l})}case"lazy":{let c=s.getter,{_cachedInner:l,...d}=s;return q(a,{...d,getter:()=>n(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function hh(e){return Pr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:kn(r.options)}})}function OI(e,t){if(!t?.length)return e;let r=e._zod.def;return q(e,Ne(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function _h(e){return OI(e.out,e.checks)}function NI(e){return e.in._zod.traits.has("$ZodTransform")?_h(e):e.in}function yh(e){return Pr(e,{pipe:t=>NI(t._zod.def),default:(t,r)=>r?Nt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function bh(e){return Pr(e,{pipe:t=>_h(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var cp={};Ve(cp,{bigint:()=>LI,boolean:()=>UI,date:()=>jI,number:()=>zI,string:()=>DI});function DI(e){return Pc($n,e)}function zI(e){return Uc(Sn,e)}function UI(e){return Bc(xn,e)}function LI(e){return qc(In,e)}function jI(e){return rl(wr,e)}var MI=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(),wh=f.array(MI).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 lp(e){return new TextEncoder().encode(e).byteLength}var $h=128*1024,Sh=512*1024,xh=64,Ih=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"),kh=f.string().refine(e=>lp(e)<=$h&&!e.includes("\0"),`File contents must be text without null bytes, at most ${$h} UTF-8 bytes`),qD=f.record(Ih,kh.nullable()),dp=f.record(Ih,kh).superRefine((e,t)=>{let r=Object.keys(e);(r.length>xh||Object.values(e).reduce((o,n)=>o+lp(n),0)>Sh)&&t.addIssue({code:"custom",message:`Save at most ${xh} helper files totaling ${Sh} 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 FI=/'/g,ZI=/^[A-Za-z0-9_./:=@,+-]+$/,ia=/^[A-Za-z_][A-Za-z0-9_]*$/;function VI(e){return`'${e.replace(FI,"'\\''")}'`}function pt(e){return e===""?"''":ZI.test(e)?e:VI(e)}var BI=12,GI=10;var qI=f.object({name:f.string().regex(ia).max(128),description:f.string().trim().min(1).max(300),values:f.array(f.string().min(1).max(200)).min(2).max(GI).describe("Public non-secret setting values. Sent to QA models and shown in GitHub results.").optional()}).strict(),Eh=f.array(qI).max(BI);var Cr={Compose:"compose",Command:"command"};var Th=8,HI=64,Ph=/^\/workspace\/(?!\.+$)(?!.*\.\.)[A-Za-z0-9._-]+$/,WI=f.object({repoOwner:f.string().trim().min(1,"repoOwner is required"),repoName:f.string().trim().min(1,"repoName is required"),sandboxPath:f.string().regex(Ph,"sandboxPath must be a single path segment under /workspace").optional()}).strict();function KI(e){return e.sandboxPath??`/workspace/${e.repoName}`}var uz=f.array(WI).min(1,"at least one repo is required").max(Th,`at most ${Th} 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=KI(i);if(!Ph.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)})}),Ah=f.object({name:f.string(),envVar:f.string()}),Or=f.record(f.string().regex(ia,"must be a POSIX-style environment variable name"),f.string()),Ch=f.object({type:f.enum([Cr.Compose]),files:f.array(f.string()).optional(),service:f.string().optional(),profiles:f.array(f.string()).optional()}).strict(),pp=f.object({fixtures:wh.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:Ch.optional(),url:f.object({hostPort:f.number().int().optional(),path:f.string().optional()}).strict().optional(),portMapping:f.object({containerPort:f.number().int().optional()}).strict().optional(),additionalPorts:f.array(f.object({service:f.string().optional(),hostPort:f.number().int().optional(),containerPort:f.number().int().optional()}).strict()).optional(),runtimeVariables:Or.optional(),composeEnv:Or.optional(),generatedComposeEnv:f.record(f.string(),f.union([f.object({type:f.literal("alphanumeric"),length:f.number().int()}).strict(),f.object({type:f.literal("hex"),bytes:f.number().int()}).strict()])).optional(),env:Or.optional(),ready:f.object({path:f.string().optional(),nonEmptyPath:f.string().optional(),timeoutSeconds:f.number().int().optional()}).strict().optional(),open:f.object({path:f.string().optional()}).strict().optional(),renderedPathPrefixes:f.array(f.string().max(512)).max(HI).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(Ah).optional()}).strict().optional(),e2e:f.object({testCommand:f.string(),seedCommand:f.string().optional(),resetCommand:f.string().optional(),credentials:f.array(Ah).optional()}).strict().optional(),qaSwitches:Eh.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(),JI="dockerfile",YI=f.union([f.object({type:f.literal(Cr.Command),command:f.string().optional()}).passthrough(),f.object({type:f.literal(JI),context:f.string().optional(),dockerfile:f.string().optional(),service:f.string().optional()}).passthrough()]),Oh=pp.extend({entry:f.union([Ch,YI]).optional()}),XI=/^[a-z][a-z0-9-]*$/;var Nh=f.object({id:f.string().trim().min(1).regex(XI),description:f.string().trim().min(1),config:pp}).strict(),QI=Nh.extend({config:Oh}),ek=f.array(Nh).superRefine((e,t)=>{new Set(e.map(r=>r.id)).size!==e.length&&t.addIssue({code:"custom",message:"App runtime names must be unique"})}),Rh=["defect","walkthrough","edge-case"];var Dh=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(Rh)).min(1).max(Rh.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(),cz=f.object({sandbox:f.object({appRuntime:pp.optional(),appRuntimes:ek.optional(),helperFiles:dp.optional(),runtimeVariables:Or.optional(),iosApp:Dh.optional()}).strict().refine(e=>e.appRuntime===void 0||e.appRuntimes===void 0,{message:"Supply appRuntimes or legacy appRuntime, not both"}).optional()}).strict(),lz=f.object({sandbox:f.object({appRuntime:Oh.optional(),appRuntimes:f.array(QI).optional(),helperFiles:dp.optional(),runtimeVariables:Or.optional(),iosApp:Dh.optional()}).strict().optional()}).strict();function mp(e){if(!e)return null;let t=e.entry;if(t===void 0||t.type===Cr.Compose)return e;let{entry:r,...o}=e,n=t.type===Cr.Command?t.command?.trim():void 0,i=e.bootScript?.trim()?e.bootScript:n||e.bootScript;return{...o,...i!==void 0?{bootScript:i}:{}}}var oa=1,tk=["name","description","provisioningKind","provisioningConfig","helperFiles","cache","networkPolicy"];function nk(e){let t=e?.sandbox;if(!t)return e;let{appRuntime:r,appRuntimes:o,...n}=t;return{...e,sandbox:{...n,...r?{appRuntime:mp(r)}:{},...o?{appRuntimes:o.map(i=>({...i,config:mp(i.config)}))}:{}}}}function aa(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:nk(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 zh(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 Uh(e,t){let r={...aa(e),repos:e.repos},o={...t.environment,repos:t.repos};return[...tk,"repos"].filter(n=>zh(r[n]??null)!==zh(o[n]??null))}function Lh(e,t){let r=aa(e).helperFiles??{},o=t.environment.helperFiles??{},i=[...new Set([...Object.keys(r),...Object.keys(o)])].filter(a=>(r[a]??null)!==(o[a]??null)).sort();return i.length>0?i:void 0}var rk=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+)$/,ik=/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/,ok=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/,ak=/^(\d+)(?:\.(diff|patch))?$/i,jh=/^[A-Za-z0-9_.-]+$/,sk=/^[A-Za-z0-9_.][A-Za-z0-9_.-]*$/;function Mh(e){return typeof e!="string"||!e||e.length>100||e==="."||e===".."?!1:sk.test(e)}function uk(e,t){return Mh(e)&&Mh(t)?{owner:e,repo:t}:null}function sa(e){let t=e.match(rk)??e.match(ik)??e.match(ok);return t?uk(t[1],t[2]):null}var ck=500;function lk(e){if(typeof e!="string")return null;let t=e.trim();if(!t||t.length>ck)return null;let r;try{r=new URL(t)}catch{return null}if(r.protocol!=="https:"||r.hostname.toLowerCase()!=="github.com")return null;let o=r.pathname.split("/").filter(Boolean),n=o.length>=4?ak.exec(o[3]):null;return o[2]!=="pull"||n===null||n[2]!==void 0&&o.length!==4||!jh.test(o[0])||!jh.test(o[1])?null:`https://github.com/${o[0]}/${o[1]}/pull/${n[1]}`}function Fh(e){let t=lk(e);if(!t)return null;let r=t.slice(19).split("/"),o=Number(r[3]);return!Number.isInteger(o)||o<=0?null:{prUrl:t,owner:r[0],repo:r[1],number:o}}import{execFileSync as Zh}from"node:child_process";function Nr(e,t){try{return Zh("git",e,{encoding:"utf8",stdio:[t.input===void 0?"ignore":"pipe","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.input===void 0?{}:{input:t.input},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(r){throw new y("user",`git ${e.join(" ")} failed: ${xe(r)}`)}}function Vh(e,t){let r;try{r=Zh("git",e,{stdio:["ignore","pipe","pipe"],...t.cwd?{cwd:t.cwd}:{},...t.maxBuffer?{maxBuffer:t.maxBuffer}:{}})}catch(o){throw new y("user",`git ${e.join(" ")} failed: ${xe(o)}`)}try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new y("user","A changed file has a file name that is not valid UTF-8, so it cannot be reviewed.",{hint:"Rename the file, commit, then run the review again."})}}function Dr(e,t={}){return Nr(e,t).trim()}function Bh(e){let t=`Pass the ${e} as owner/name.`,r;try{r=Dr(["remote","get-url","origin"])}catch{throw new y("user","This directory has no git `origin` remote to read the repository from.",{hint:t})}let o=sa(r);if(!o)throw new y("user","origin remote must point at a GitHub repository",{hint:t});return{owner:o.owner,repo:o.repo}}var dk=/\.git$/;function pk(e,t){let r=sa(e);if(!r)throw new y("user",`${t} must be owner/name or a GitHub URL`);return{owner:r.owner,repo:r.repo.replace(dk,"")}}function mt(e,t="repo"){return e===void 0?Bh(t):pk(e,t)}var mk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Gh(e){return(await P(e,R("/api/environments"))).data.environments}function qh(e,t){return e.find(r=>r.scope==="team"&&r.repoOwner.toLowerCase()===t.owner.toLowerCase()&&r.repoName.toLowerCase()===t.repo.toLowerCase())}async function Hh(e,t){return qh(await Gh(e),t)??null}async function fp(e,t){let r=await Gh(e);if(t&&mk.test(t)){let i=r.find(a=>a.id===t);if(!i)throw new y("user",`No environment with id ${t}.`);return i}let o=mt(t,"environment"),n=qh(r,o);if(!n)throw new y("user",`No team environment for ${o.owner}/${o.repo}.`,{hint:"Run `arcanist environments status` first."});return n}async function Wh(e,t){return(await P(e,R("/api/environments/:id",{id:t}))).data}function vk(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!==oa||!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 ${oa}).`,{hint:"Write one with `arcanist environments export owner/repo -o <file>`."});return o}async function Kh(e,t={},r){let{config:o}=K(r,t),n=await fp(o,e),i=await Wh(o,n.id),a={version:oa,exportedFrom:{apiUrl:o.apiUrl,environmentId:i.id,configurationGeneration:i.cache.configurationGeneration,exportedAt:new Date().toISOString()},repos:i.repos,environment:aa(i)},s=`${JSON.stringify(a,null,2)}
71
71
  `;if(t.output){await gk(t.output,s,"utf8"),N(r,t,{environmentId:i.id,name:i.name,configurationGeneration:i.cache.configurationGeneration,path:t.output},u=>{console.log(`Exported "${j(u.name)}" (generation ${u.configurationGeneration}) to ${u.path}`)});return}process.stdout.write(s)}async function hk(e,t,r,o){let n=t.repos[0],i=`${n.repoOwner}/${n.repoName}`,{name:a}=t.environment;if(r.dryRun){N(o,r,{environmentId:null,name:a,created:!1,applied:!1},u=>{console.log(`Would create "${j(u.name)}" for ${i} (dry run; nothing was sent).`)});return}let s=await P(e,R("/api/environments"),{method:"POST",body:JSON.stringify({...t.environment,repos:t.repos,scope:"team"})});N(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 "${j(u.name)}" for ${i} (${u.environmentId}).`),u.buildScheduled&&console.log("A build is scheduled; watch it with `arcanist environments status --wait`.")})}async function Jh(e,t,r={},o){let n=vk(await fk(e,"utf8"),e),{config:i}=K(o,r),a=n.repos[0],s=t===void 0?await Hh(i,{owner:a.repoOwner,repo:a.repoName}):await fp(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 hk(i,n,r,o);return}let u=await Wh(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=Uh(u,n),d=Lh(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,`${R("/api/environments/:id",{id:u.id})}?dryRun=1`,{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos})}),r.dryRun||l.length===0){N(o,r,{...m,applied:!1},_=>{console.log(_.changedFields.length===0?`"${j(_.name)}" already matches ${e}; nothing to apply.`:`Would change ${_.changedFields.join(", ")} on "${j(_.name)}" (dry run).`)});return}let p=await P(i,R("/api/environments/:id",{id:u.id}),{method:"PUT",body:JSON.stringify({...n.environment,repos:n.repos,expectedWriteVersion:u.writeVersion})}),v=p.data.cache.configurationGeneration;N(o,r,{...m,applied:!0,configurationGeneration:{before:u.cache.configurationGeneration,after:v},rebuildScheduled:v!==u.cache.configurationGeneration&&p.data.cache.status==="enabled"},_=>{console.log(`Applied ${_.changedFields.join(", ")} to "${j(_.name)}" (generation ${_.configurationGeneration.before} -> ${_.configurationGeneration.after}).`),_.rebuildScheduled&&console.log("A rebuild is scheduled; watch it with `arcanist environments status --wait`.")})}var zr="GitHub could not verify your organization role because the Arcanist GitHub App needs additional permissions. Ask an organization owner to approve the pending permissions in GitHub's installed apps settings, then try again.",ua="Arcanist could not verify your GitHub account permissions. Try again. If this continues, reconnect GitHub and authorize your organization's SSO if required.";var Ur=[{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"]}],Xh=Ur.length-1,_k="Finishing up";function Yh(e){return e?Ur.findIndex(t=>t.stages.includes(e)):-1}var yk=new Set(["escalated_to_customer","question_for_customer"]);function bk(e){return e.status==="escalated"&&!yk.has(e.stage??"")}function Qh(e){return e.status==="ready"?"review":e.question?"answer_question":e.status==="failed"?e.failureReason==="installation_missing"?"authorize_github":"retry":bk(e)?"wait_for_arcanist":"wait"}function wk(e){if(e.status==="ready")return Ur.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?Xh:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=Yh(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=Yh(o)}return Math.max(t,r)}function e_(e){let t=wk(e);if(t>=Ur.length)return null;let r=[...e.history??[],e.stage];return t===Xh&&(r.includes("smoke_passed")||r.includes("completed"))?_k:Ur[t].label}async function ft(e){let t=Date.now()+e.timeoutMs,r=null;for(;Date.now()<t;){try{let o=await e.fetchStatus();if(r=null,o!==null)return o}catch(o){if(!om(o))throw o;if(r===null){let n=o instanceof Error?o.message:String(o);process.stderr.write(`Status check failed (${n}). Still waiting; retrying every ${e.pollIntervalMs}ms.
72
- `)}r=o}await qr(e.pollIntervalMs)}throw r!==null?r:new y(e.timeoutCode??"server",e.timeoutMessage)}var t_=250,ca=1e3,n_=6e4,r_=200;function i_(e){return Gp(e)}var $k=/^\d+$/;function Ze(e,t={}){let r=t.defaultMs??ca,o=t.minMs??t_,n=t.maxMs===void 0?n_:t.maxMs;if(!e)return r;if(!$k.test(e))throw new y("user","Polling interval must be a non-negative integer.");let i=Number(e);if(i<o||n!==null&&i>n){let a=n===null?`at least ${o}`:`between ${o} and ${n}`;throw new y("user",`Polling interval must be ${a} milliseconds.`)}return i}var Tn=5e3,Sk=7200*1e3;function gp(e){let t=mt(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function gt(e,t){let o=(await P(e,R("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=Ik(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${pt(o.question.id)} --answer-stdin --json`:o_(n,o.fullName);return{fullName:o.fullName,status:o.status,stage:o.stage,...o.buildStatus===void 0?{}:{buildStatus:o.buildStatus},...o.failureReason===void 0?{}:{failureReason:o.failureReason},...o.question===void 0?{}:{question:o.question},nextAction:n,command:i}}function xk(e){return e.nextAction==="wait"}function o_(e,t){switch(e){case"prepare":return`arcanist environments prepare ${t}`;case"wait":return`arcanist environments status ${t} --wait`;case"retry":return`arcanist environments retry ${t}`;case"review":return null;case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function Ik(e){return e.status==="not_started"?"prepare":Qh({...e,status:e.status})}function la(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${j(e.fullName)}: ${j(e.status)}${t?` (${j(t)})`:""}`)}async function vp(e,t,r){return ft({pollIntervalMs:r,timeoutMs:Sk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await gt(e,t);return xk(o)?null:o}})}async function hp(e,t){return(await P(e,R("/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 a_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t);await P(i,R("/api/repos"));let a=t.wait?await vp(i,n.fullName,o??Tn):await gt(i,n.fullName);N(r,t,{repository:a},({repository:s})=>la(s))}async function s_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t),[a]=await hp(i,{repositories:[n]});if(!a)throw new y("server","Environment setup returned no repository result.");if(a.status==="forbidden"&&a.reason==="installation_admin_required")throw new y("auth",`Ask a workspace admin to connect the Arcanist GitHub App for ${n.owner} before preparing ${n.fullName}.`);if(a.status==="forbidden"&&a.reason==="installation_github_admin_required")throw new y("auth",`An admin of the ${n.owner} GitHub account must connect the Arcanist GitHub App before ${n.fullName} can be prepared.`);if(a.status==="forbidden"&&a.reason==="repository_limit")throw new y("auth",`This workspace has reached its limit of repositories with an environment, so ${n.fullName} cannot be prepared. Upgrade to Team, or ask Arcanist to raise the limit.`);if(a.status==="forbidden")throw new y("auth",`You must have write access to ${n.fullName} to prepare its environment.`);if(a.status==="failed")throw a.reason==="installation_github_permissions_required"?new y("auth",zr):a.reason==="installation_github_check_failed"?new y("server",ua):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 vp(i,n.fullName,o??Tn);N(r,t,{repository:c},({repository:l})=>la(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:o_(s,a.fullName)};N(r,t,{repository:u},({repository:c})=>la(c))}async function u_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t);await P(i,R("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await vp(i,n.fullName,o??Tn):await gt(i,n.fullName);N(r,t,{repository:a},({repository:s})=>la(s))}var kk=["openai","anthropic","baseten"],c_=f.enum(kk),l_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),uU=f.object({managedFallback:f.boolean()}).strict(),cU=f.object({storeCopies:f.boolean()}).strict(),d_=f.object({name:f.string().trim().min(1).max(80)}).strict();var da=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 API 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}=K(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,`${R("/api/inference/keys")}?${n}`);N(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=d_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=K(o,r),a=await P(i,R("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});N(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}=K(o,r),i=await P(n,R("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});N(o,r,i,()=>console.log("Inference API key revoked. Existing streams may finish."))}};var pa=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");da.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("Turn fallback on or off for Arcanist-managed inference at public provider prices").action((n,i,a,s)=>e.fallback(n,i,a,s)),r.command("calls").description("List the recent calls the proxy recorded, newest first (workspace admins)").option("--workflow <id>","Only calls of this workflow ID").option("--cursor <cursor>","Continue from nextCursor").option("--limit <limit>","Page size: 10, 25, or 50","25").action((n,i)=>e.calls(n,i)),r.command("copies [on|off]").description("Show or set whether Arcanist stores copies of requests and responses (workspace admins)").action((n,i,a)=>e.copies(n,i,a)),r.command("usage").description("Show the calls the proxy recorded across all workflows (workspace admins)").option("--days <days>","Time range in days: 1, 7, or 30","7").action((n,i)=>e.usage(n,i))}static provider(t){let r=c_.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}=K(o,r),a=await P(i,t,n);N(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(R("/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=l_.safeParse({key:await Mt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(R("/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(R("/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(R("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async calls(t,r){let{config:o}=K(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),t.workflow&&n.set("workflowId",t.workflow);let i=await P(o,`${R("/api/inference/calls")}?${n}`);N(r,t,i,a=>{for(let s of a.calls)console.log([new Date(s.startedAt).toISOString(),s.id,s.workflowId,`${s.provider}/${s.model}`,`${s.outcome??"in progress"} ${s.upstreamStatus??"-"}`,`${s.inputTokens??"-"}/${s.outputTokens??"-"} tokens`,s.finishedAt===null?"-":`${s.finishedAt-s.startedAt} ms`,s.traceId===null?"no copy":`copy ${s.traceId}`].join(" "));a.nextCursor&&console.log(`Next page: --cursor ${a.nextCursor}`)})}static async copies(t,r,o){if(t!==void 0&&t!=="on"&&t!=="off")throw new y("user","Copies must be on or off.");let{config:n}=K(o,r),i=await P(n,R("/api/inference/settings"),t===void 0?void 0:{method:"PATCH",body:JSON.stringify({storeCopies:t==="on"})});N(o,r,i,a=>console.log(a.storeCopies?"Copies on: Arcanist stores a copy of each request and response.":"Copies off: new calls are not stored. Copies stored in the last 30 days stay readable."))}static async usage(t,r){let{config:o}=K(r,t),n=new URLSearchParams({days:t.days??"7"}),i=await P(o,`${R("/api/inference/usage")}?${n}`);N(r,t,i,a=>{let s=a.points.reduce((u,c)=>u+c.requests,0);console.log(`${s} recorded requests, ${a.failedRequests} failed, average latency ${a.averageLatencyMs===null?"unknown":`${a.averageLatencyMs} ms`}.`);for(let u of a.models)console.log(`${u.provider} ${u.model}: ${u.requests} requests`)})}};var p_="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 $_}from"node:child_process";import{basename as Uk,extname as Lk}from"node:path";function m_(e){return e.blocking===!0}var Ek=/[.!]+$/u,f_=["clear","issues_found","inconclusive"];var Tk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},g_="blocks merge";var v_="\u2705 Ruled out";function h_(e){return e.replace(Ek,"")}function __(e){return Tk[e==="do_not_merge"?"do_not_merge":"merge"]}function Ak(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function Rk(e){return m_(e)?"blocking":"non_blocking"}function Pk(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function y_(e){let t=Ak(e).prFindings,r=t.map(s=>({finding:s,impact:Rk(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=Pk(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var yp=3e6,_p=f.string().regex(/^[0-9a-f]{40}$/),Ck=["added","modified","removed","renamed"],Ok=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(Ck),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),Nk=f.object({sha:_p,subject:f.string(),body:f.string()}),PU=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:_p,headRef:f.string().min(1),headSha:_p,files:f.array(Ok).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(Nk),heldBackPaths:f.array(f.string())});function b_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var Dk=["running","completed","failed"],zk=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(Dk),verdict:f.enum(f_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),CU=f.object({reviews:f.array(zk),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var jk=/^origin\//,Mk=/^new file mode /m,Fk=/^deleted file mode /m,Zk=/^\.\//,Vk=/\/+$/,w_=64*1024*1024,Bk=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),Gk=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),qk=[".example",".sample",".template"];function S_(e){let t=e.cwd;if(Lr(["rev-parse","--is-inside-work-tree"],t)!=="true")throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Lr(["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&&!Lr(["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}:Hk(t),n=Dr(["rev-parse","HEAD"],{cwd:t}),i=Dr(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=Wk(Vh([...s,"--numstat","-z",a],{cwd:t,maxBuffer:w_})),c=tE(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=Kk(Nr([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:w_}));if(l.length!==u.length)throw new y("user",`git diff listed ${u.length} files but printed ${l.length} patches.`);let d=new Set((e.include??[]).map(Qk)),m=A=>d.has(A)||[...d].some(x=>A.startsWith(`${x}/`)),p=A=>A.previousPath?[A.path,A.previousPath]:[A.path],v=Xk(u.flatMap(p),t),_=[],S=[],E=[];if(u.forEach((A,x)=>{let O=l[x]??"";if(A.binary){S.push(A.path);return}if(p(A).some(G=>Yk(G)||v.has(G))&&!m(A.path)){E.push(A.path);return}_.push({path:A.path,...A.previousPath?{previousPath:A.previousPath}:{},status:Jk(O,A),additions:A.additions,deletions:A.deletions,patch:O})}),_.length===0)throw new y("user",`No reviewable changes against ${o.ref}.`,{hint:"Binary files are skipped and secret-looking files are held back; pass --include <path> to upload one."});let k={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Dr(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:b_(_),commitMessages:eE(`${i}..HEAD`,t),heldBackPaths:E.sort()};return nE(k),{payload:k,skippedBinaryPaths:S.sort(),uncommittedPaths:c}}function Hk(e){let t=[Lr(["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(Lr(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(jk,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Lr(e,t){try{return $_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).trim()}catch{return null}}function Wk(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 Kk(e){let t=[],r=null;for(let o of e.split(`
72
+ `)}r=o}await qr(e.pollIntervalMs)}throw r!==null?r:new y(e.timeoutCode??"server",e.timeoutMessage)}var t_=250,ca=1e3,n_=6e4,r_=200;function i_(e){return Gp(e)}var $k=/^\d+$/;function Ze(e,t={}){let r=t.defaultMs??ca,o=t.minMs??t_,n=t.maxMs===void 0?n_:t.maxMs;if(!e)return r;if(!$k.test(e))throw new y("user","Polling interval must be a non-negative integer.");let i=Number(e);if(i<o||n!==null&&i>n){let a=n===null?`at least ${o}`:`between ${o} and ${n}`;throw new y("user",`Polling interval must be ${a} milliseconds.`)}return i}var Tn=5e3,Sk=7200*1e3;function gp(e){let t=mt(e);return{...t,fullName:`${t.owner}/${t.repo}`}}async function gt(e,t){let o=(await P(e,R("/api/settings/repositories/onboarding"))).repositories.find(a=>a.fullName.toLowerCase()===t.toLowerCase())??{fullName:t,status:"not_started",stage:null},n=Ik(o),i=n==="answer_question"&&o.question?`arcanist environments answer ${o.fullName} --question ${pt(o.question.id)} --answer-stdin --json`:o_(n,o.fullName);return{fullName:o.fullName,status:o.status,stage:o.stage,...o.buildStatus===void 0?{}:{buildStatus:o.buildStatus},...o.failureReason===void 0?{}:{failureReason:o.failureReason},...o.question===void 0?{}:{question:o.question},nextAction:n,command:i}}function xk(e){return e.nextAction==="wait"}function o_(e,t){switch(e){case"prepare":return`arcanist environments prepare ${t}`;case"wait":return`arcanist environments status ${t} --wait`;case"retry":return`arcanist environments retry ${t}`;case"review":return null;case"answer_question":case"authorize_github":case"wait_for_arcanist":return null;default:return e}}function Ik(e){return e.status==="not_started"?"prepare":Qh({...e,status:e.status})}function la(e){let t=e.failureReason??e.stage??e.buildStatus??e.nextAction;console.log(`${j(e.fullName)}: ${j(e.status)}${t?` (${j(t)})`:""}`)}async function vp(e,t,r){return ft({pollIntervalMs:r,timeoutMs:Sk,timeoutMessage:`Timed out waiting for ${t} environment setup.`,fetchStatus:async()=>{let o=await gt(e,t);return xk(o)?null:o}})}async function hp(e,t){return(await P(e,R("/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 a_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t);await P(i,R("/api/repos"));let a=t.wait?await vp(i,n.fullName,o??Tn):await gt(i,n.fullName);N(r,t,{repository:a},({repository:s})=>la(s))}async function s_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t),[a]=await hp(i,{repositories:[n]});if(!a)throw new y("server","Environment setup returned no repository result.");if(a.status==="forbidden"&&a.reason==="installation_admin_required")throw new y("auth",`Ask a workspace admin to connect the Arcanist GitHub App for ${n.owner} before preparing ${n.fullName}.`);if(a.status==="forbidden"&&a.reason==="installation_github_admin_required")throw new y("auth",`An admin of the ${n.owner} GitHub account must connect the Arcanist GitHub App before ${n.fullName} can be prepared.`);if(a.status==="forbidden"&&a.reason==="repository_limit")throw new y("auth",`This workspace has reached its limit of repositories with an environment, so ${n.fullName} cannot be prepared. Upgrade to Team, or ask Arcanist to raise the limit.`);if(a.status==="forbidden")throw new y("auth",`You must have write access to ${n.fullName} to prepare its environment.`);if(a.status==="failed")throw a.reason==="installation_github_permissions_required"?new y("auth",zr):a.reason==="installation_github_check_failed"?new y("server",ua):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 vp(i,n.fullName,o??Tn);N(r,t,{repository:c},({repository:l})=>la(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:o_(s,a.fullName)};N(r,t,{repository:u},({repository:c})=>la(c))}async function u_(e,t={},r){let o=t.wait?Ze(t.pollInterval,{defaultMs:Tn,maxMs:null}):null,n=gp(e),{config:i}=K(r,t);await P(i,R("/api/settings/repositories/:owner/:repo/onboarding/retry",{owner:n.owner,repo:n.repo}),{method:"POST"});let a=t.wait?await vp(i,n.fullName,o??Tn):await gt(i,n.fullName);N(r,t,{repository:a},({repository:s})=>la(s))}var kk=["openai","anthropic","baseten"],c_=f.enum(kk),l_=f.object({key:f.string().trim().min(8).max(16384).regex(/^\S+$/)}).strict(),uU=f.object({managedFallback:f.boolean()}).strict(),cU=f.object({storeCopies:f.boolean()}).strict(),d_=f.object({name:f.string().trim().min(1).max(80)}).strict();var da=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 API 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}=K(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,`${R("/api/inference/keys")}?${n}`);N(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=d_.safeParse({name:t});if(!n.success)throw new y("user","Provide a name of 1\u201380 characters.");let{config:i}=K(o,r),a=await P(i,R("/api/inference/keys"),{method:"POST",body:JSON.stringify(n.data)});N(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}=K(o,r),i=await P(n,R("/api/inference/keys/:keyId",{keyId:t}),{method:"DELETE"});N(o,r,i,()=>console.log("Inference API key revoked. Existing streams may finish."))}};var pa=class e{static register(t){let r=t.command("inference").description("Workspace inference credentials and fallback preferences");da.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("Turn fallback on or off for Arcanist-managed inference at public provider prices").action((n,i,a,s)=>e.fallback(n,i,a,s)),r.command("calls").description("List the recent calls the proxy recorded, newest first (workspace admins)").option("--workflow <id>","Only calls of this workflow ID").option("--cursor <cursor>","Continue from nextCursor").option("--limit <limit>","Page size: 10, 25, or 50","25").action((n,i)=>e.calls(n,i)),r.command("copies [on|off]").description("Show or set whether Arcanist stores copies of requests and responses (workspace admins)").action((n,i,a)=>e.copies(n,i,a)),r.command("usage").description("Show the calls the proxy recorded across all workflows (workspace admins)").option("--days <days>","Time range in days: 1, 7, or 30","7").action((n,i)=>e.usage(n,i))}static provider(t){let r=c_.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}=K(o,r),a=await P(i,t,n);N(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(R("/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=l_.safeParse({key:await Mt()});if(!i.success)throw new y("user","Provide a key of 8\u201316384 characters without whitespace.");return e.settings(R("/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(R("/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(R("/api/inference/providers/:provider",{provider:i}),o,n,{method:"PATCH",body:JSON.stringify({managedFallback:r==="on"})})}static async calls(t,r){let{config:o}=K(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),t.workflow&&n.set("workflowId",t.workflow);let i=await P(o,`${R("/api/inference/calls")}?${n}`);N(r,t,i,a=>{for(let s of a.calls)console.log([new Date(s.startedAt).toISOString(),s.id,s.workflowId,`${s.provider}/${s.model}`,`${s.outcome??"in progress"} ${s.upstreamStatus??"-"}`,`${s.inputTokens??"-"}/${s.outputTokens??"-"} tokens`,s.finishedAt===null?"-":`${s.finishedAt-s.startedAt} ms`,s.traceId===null?"no copy":`copy ${s.traceId}`].join(" "));a.nextCursor&&console.log(`Next page: --cursor ${a.nextCursor}`)})}static async copies(t,r,o){if(t!==void 0&&t!=="on"&&t!=="off")throw new y("user","Copies must be on or off.");let{config:n}=K(o,r),i=await P(n,R("/api/inference/settings"),t===void 0?void 0:{method:"PATCH",body:JSON.stringify({storeCopies:t==="on"})});N(o,r,i,a=>console.log(a.storeCopies?"Copies on: Arcanist stores a copy of each request and response.":"Copies off: new calls are not stored. Copies stored in the last 30 days stay readable."))}static async usage(t,r){let{config:o}=K(r,t),n=new URLSearchParams({days:t.days??"7"}),i=await P(o,`${R("/api/inference/usage")}?${n}`);N(r,t,i,a=>{let s=a.points.reduce((u,c)=>u+c.requests,0);console.log(`${s} recorded requests, ${a.failedRequests} failed, average latency ${a.averageLatencyMs===null?"unknown":`${a.averageLatencyMs} ms`}.`);for(let u of a.models)console.log(`${u.provider} ${u.model}: ${u.requests} requests`)})}};var p_="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 $_}from"node:child_process";import{basename as Uk,extname as Lk}from"node:path";function m_(e){return e.blocking===!0}var Ek=/[.!]+$/u,f_=["clear","issues_found","inconclusive"];var Tk={merge:"Ready to merge",merge_with_follow_ups:"Ready to merge with findings",do_not_merge:"Hold off on merging"},g_="blocks merge";var v_="\u2705 Ruled out";function h_(e){return e.replace(Ek,"")}function __(e){return Tk[e==="do_not_merge"?"do_not_merge":"merge"]}function Ak(e){return e.reduce((t,r)=>(r.attribution==="repository_follow_up"?t.repositoryFollowUps.push(r):t.prFindings.push(r),t),{prFindings:[],repositoryFollowUps:[]})}function Rk(e){return m_(e)?"blocking":"non_blocking"}function Pk(e){return e.blocking>0?"do_not_merge":e.nonBlocking===0?"merge":"merge_with_follow_ups"}function y_(e){let t=Ak(e).prFindings,r=t.map(s=>({finding:s,impact:Rk(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=Pk(i);return{verdict:t.length>0?"issues_found":"clear",tier:a,counts:i,ordered:o}}var yp=3e6,_p=f.string().regex(/^[0-9a-f]{40}$/),Ck=["added","modified","removed","renamed"],Ok=f.object({path:f.string().min(1),previousPath:f.string().min(1).optional(),status:f.enum(Ck),additions:f.number().int().nonnegative(),deletions:f.number().int().nonnegative(),patch:f.string()}),Nk=f.object({sha:_p,subject:f.string(),body:f.string()}),PU=f.object({remoteUrl:f.string().min(1),baseRef:f.string().min(1),baseSha:_p,headRef:f.string().min(1),headSha:_p,files:f.array(Ok).min(1),totalPatchBytes:f.number().int().nonnegative(),commitMessages:f.array(Nk),heldBackPaths:f.array(f.string())});function b_(e){let t=new TextEncoder;return e.reduce((r,o)=>r+t.encode(o.patch).byteLength,0)}var Dk=["running","completed","failed"],zk=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(Dk),verdict:f.enum(f_).nullable(),findingCount:f.number().int().nonnegative(),blockingCount:f.number().int().nonnegative(),failureMessage:f.string().min(1).optional()}).strict(),CU=f.object({reviews:f.array(zk),emptyHistory:f.boolean().optional(),nextCursor:f.string().min(1).nullable()}).strict();var jk=/^origin\//,Mk=/^new file mode /m,Fk=/^deleted file mode /m,Zk=/^\.\//,Vk=/\/+$/,w_=64*1024*1024,Bk=new Set([".pem",".key",".p12",".pfx",".crt",".cer",".der",".jks",".keystore",".asc",".gpg"]),Gk=new Set(["id_rsa","id_dsa","id_ecdsa","id_ed25519",".netrc",".npmrc",".pypirc"]),qk=[".example",".sample",".template"];function S_(e){let t=Lr(["rev-parse","--show-toplevel"],e.cwd);if(!t)throw new y("user","Run arcanist review inside a git checkout of your repository.");let r=Lr(["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&&!Lr(["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}:Hk(t),n=Dr(["rev-parse","HEAD"],{cwd:t}),i=Dr(["merge-base",o.ref,"HEAD"],{cwd:t}),a=`${i}...HEAD`,s=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--find-renames"],u=Wk(Vh([...s,"--numstat","-z",a],{cwd:t,maxBuffer:w_})),c=tE(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=Kk(Nr([...s,"--src-prefix=a/","--dst-prefix=b/",a],{cwd:t,maxBuffer:w_}));if(l.length!==u.length)throw new y("user",`git diff listed ${u.length} files but printed ${l.length} patches.`);let d=new Set((e.include??[]).map(Qk)),m=A=>d.has(A)||[...d].some(x=>A.startsWith(`${x}/`)),p=A=>A.previousPath?[A.path,A.previousPath]:[A.path],v=Xk(u.flatMap(p),t),_=[],S=[],E=[];if(u.forEach((A,x)=>{let O=l[x]??"";if(A.binary){S.push(A.path);return}if(p(A).some(G=>Yk(G)||v.has(G))&&!m(A.path)){E.push(A.path);return}_.push({path:A.path,...A.previousPath?{previousPath:A.previousPath}:{},status:Jk(O,A),additions:A.additions,deletions:A.deletions,patch:O})}),_.length===0)throw new y("user",`No reviewable changes against ${o.ref}.`,{hint:"Binary files are skipped and secret-looking files are held back; pass --include <path> to upload one."});let k={remoteUrl:r,baseRef:o.label,baseSha:i,headRef:Dr(["rev-parse","--abbrev-ref","HEAD"],{cwd:t}),headSha:n,files:_,totalPatchBytes:b_(_),commitMessages:eE(`${i}..HEAD`,t),heldBackPaths:E.sort()};return nE(k),{payload:k,skippedBinaryPaths:S.sort(),uncommittedPaths:c}}function Hk(e){let t=[Lr(["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(Lr(["rev-parse","--verify","--quiet",`${r}^{commit}`],e))return{ref:r,label:r.replace(jk,"")};throw new y("user","Could not find the default branch on origin.",{hint:"Run `git fetch origin`, or pass --base <ref>."})}function Lr(e,t){try{return $_("git",e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t?{cwd:t}:{}}).replace(/\n$/,"")}catch{return null}}function Wk(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 Kk(e){let t=[],r=null;for(let o of e.split(`
73
73
  `))o.startsWith("diff --git ")?(r&&t.push(`${r.join(`
74
74
  `)}
75
75
  `),r=[o]):r&&r.push(o);return r&&(r[r.length-1]===""&&r.pop(),t.push(`${r.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryarcanist/cli",
3
- "version": "0.1.527",
3
+ "version": "0.1.528",
4
4
  "description": "Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",
5
5
  "type": "module",
6
6
  "bin": {