@tryarcanist/cli 0.1.484 → 0.1.485
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +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 ob=Object.defineProperty;var Ge=(e,t)=>{for(var r in t)ob(e,r,{get:t[r],enumerable:!0})};import{Command as pR,Option as mR}from"commander";var qp=["idle","running","review_starting","waiting_for_input","finalizing","review_listening","completed","superseded","needs_you","blocked","failed","stopped","archived"];var Cn=["completed","superseded","needs_you","blocked","failed","stopped","archived"],ab=new Set(Cn),bR=new Set(Cn.filter(e=>e!=="completed")),wR=Cn.filter(e=>e!=="archived"&&e!=="needs_you"&&e!=="blocked"&&e!=="stopped");function Wp(e,t){return ab.has(e)}function Hp(e){let t=e.createHelp().visibleGlobalOptions(e).map(Jp);return{...Kp(e),...t.length>0?{globalOptions:t}:{}}}function Kp(e){let t=sb(e);return{path:Ca(e),description:e.description(),aliases:e.aliases(),arguments:e.registeredArguments.map(r=>({name:r.name(),description:r.description,required:r.required,variadic:r.variadic})),options:e.createHelp().visibleOptions(e).map(Jp),...t?{notes:t}:{},subcommands:e.commands.map(Kp)}}function Jp(e){return{flags:e.flags,description:e.description,required:e.mandatory,...e.defaultValue===void 0?{}:{defaultValue:e.defaultValue}}}function Ca(e){let t=[];for(let r=e;r;r=r.parent)t.unshift(r.name());return t.join(" ")}function sb(e){let t="";return e.emit("afterHelp",{error:!1,command:e,write:r=>t+=r}),t.trim()}import{existsSync as Kb,mkdirSync as Jb,writeFileSync as Yb}from"node:fs";import{basename as Xb,join as fm,resolve as Qb}from"node:path";var ub="en-US";function Yp(e,t){let r=new Intl.DateTimeFormat(ub,{timeZone:t,month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0,timeZoneName:"short"}).formatToParts(e),o=n=>r.find(i=>i.type===n)?.value??"";return`${o("month")} ${o("day")}, ${o("year")}, ${o("hour")}:${o("minute")} ${o("dayPeriod")} ${o("timeZoneName")}`}function xe(e,t=""){return(e instanceof Error?e.message:String(e))||t}function Jr(e){return new Promise(t=>setTimeout(t,e))}var cb=/\/+$/;function tt(e){return e.replace(cb,"")}var Xp="Setup and reviews are paused for this workspace. Contact team@tryarcanist.com to resume them.";function Qp(e){if(!e||typeof e!="object")return null;let t=e,r=typeof t.code=="string"&&t.code?t.code:null,o=typeof t.message=="string"&&t.message?t.message:null;if(typeof t.error=="string"&&t.error)return{code:r??t.error,message:o??t.error,raw:t.error};if(t.error&&typeof t.error=="object"){let n=t.error,i=typeof n.code=="string"&&n.code?n.code:r,a=typeof n.message=="string"&&n.message?n.message:o;return i||a?{code:i,message:a,raw:t.error}:null}return r||o?{code:r,message:o,raw:e}:null}function Oa(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=t,o={...typeof r.repository=="string"?{repository:r.repository}:{},...typeof r.environmentsUrl=="string"?{environmentsUrl:r.environmentsUrl}:{},...typeof r.billingUrl=="string"?{billingUrl:r.billingUrl}:{}},n=Qp(t);return n?typeof n.raw=="string"&&n.raw?{...n.code?{serverCode:n.code}:{},rawError:n.raw,...n.message?{message:n.message}:{},...o}:n.message||n.code?{...n.message?{message:n.message}:{},...n.code?{serverCode:n.code,rawError:n.code}:{},...o}:null:null}catch{return null}}var lb=/^error: /,db=/^\((.*)\)$/,Ne=130,Na=5,y=class extends Error{code;exitCode;hint;requestId;data;constructor(t,r,o={}){super(r),this.name="CliError",this.code=t,this.exitCode=o.exitCode??em(t),this.hint=o.hint,this.requestId=o.requestId,this.data=o.data}},jt=class extends y{},ce=class extends y{status;body;constructor(t,r,o,n){let i=tm(t),a=Oa(r);super(i,mb(t,r,a),{exitCode:pb(t),hint:fb(t,n,a),requestId:o,data:a?.serverCode||a?.repository||a?.environmentsUrl||a?.billingUrl?{...a.serverCode?{serverCode:a.serverCode}:{},...a.repository?{repository:a.repository}:{},...a.environmentsUrl?{environmentsUrl:a.environmentsUrl}:{},...a.billingUrl?{billingUrl:a.billingUrl}:{}}:void 0}),this.name="ApiError",this.status=t,this.body=r}};function em(e){switch(e){case"auth":return 2;case"not_found":return 3;case"conflict":return 4;case"server":return 10;default:return 1}}function tm(e){return e===401||e===403?"auth":e===404?"not_found":e===409?"conflict":e>=500?"server":"user"}function pb(e){return em(tm(e))}function mb(e,t,r=Oa(t)){return r?.message?r.message:r?.serverCode?r.serverCode:t?`API error ${e}: ${t}`:`API error ${e}`}function fb(e,t,r){if(e===401)return"Run `arcanist auth login` or set `ARCANIST_TOKEN`.";if(!(e===403&&r?.message===Xp)){if(e===403&&r?.serverCode==="github_not_connected")return"This user has not connected GitHub. Open `/auth/github/connect` on the Arcanist app and approve, then retry. `arcanist onboard <owner/repo>` prints that link.";if(e===403)return"This token is not allowed to do that. `arcanist auth whoami --json` shows its tokenScope and your businessRole: a change needs a write-scope token (mint one in Settings > CLI), and a workspace-wide change also needs the admin role.";if(e===404)return t==="repo"?"Check accessible repositories with `arcanist repos list`.":t==="session"?"List sessions with `arcanist sessions list`.":void 0;if(e===409&&r?.repository){if(r.serverCode==="environment_required")return`Run \`arcanist environments prepare ${r.repository} --wait\`, then retry the review.`;if(r.serverCode==="environment_preparing"||r.serverCode==="environment_needs_attention")return`Run \`arcanist environments status ${r.repository} --wait\` for the latest setup state.`}if(e===409)return"Check the current resource state and retry the command when it is ready.";if(e>=500)return"Retry later or check the control-plane logs."}}var gb="Run `arcanist help <command>` for usage, or `arcanist help --json` for the full command tree.";function hb(e){if(!("code"in e)||typeof e.code!="string"||!e.code.startsWith("commander."))return null;let[t="",r]=e.message.replace(lb,"").split(`
|
|
5
|
-
`);return new y("user",t,{hint:r?r.replace(db,"$1"):gb})}function nm(e){if(e instanceof y)return e;if(e instanceof Error){let t=hb(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Yr(e){return JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{},...e.requestId?{requestId:e.requestId}:{},...e.data?{data:e.data}:{}}})}var rm={name:"@tryarcanist/cli",version:"0.1.
|
|
5
|
+
`);return new y("user",t,{hint:r?r.replace(db,"$1"):gb})}function nm(e){if(e instanceof y)return e;if(e instanceof Error){let t=hb(e);if(t)return t}return e instanceof Error?new y("user",e.message):new y("user",String(e))}function Yr(e){return JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{},...e.requestId?{requestId:e.requestId}:{},...e.data?{data:e.data}:{}}})}var rm={name:"@tryarcanist/cli",version:"0.1.485",description:"Command-line interface for Arcanist: inspect sessions, prepare Arcanist environments, and trigger reviews",type:"module",bin:{arcanist:"dist/index.js"},engines:{node:">=22"},files:["dist/index.js"],scripts:{build:"tsup",typecheck:"node ../../node_modules/tsrs/bin/tsrs --noEmit",prepublishOnly:"npm --prefix ../.. run guard:cli-bundle"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/tryarcanist/arcanist.git",directory:"apps/cli"},homepage:"https://www.tryarcanist.com",license:"MIT",dependencies:{commander:"^12.1.0","eventsource-parser":"3.1.1","playwright-core":"^1.65.0","proper-lockfile":"4.1.2"},devDependencies:{"@types/proper-lockfile":"^4.1.4",tsup:"^9.0.0",typescript:"^5.9.3"}};var nt=`${rm.version}`;var _b=/^\d+$/,yb=`arcanist-cli/${nt}`,bb=3e4,wb=1e3,Sb=6e5,Xr="ARCANIST_HTTP_TIMEOUT_MS";function $b(e=process.env){let t=e[Xr];if(!t)return bb;if(!_b.test(t))throw new y("user",`${Xr} must be a positive integer between 1000 and 600000.`);let r=Number(t);if(r<wb||r>Sb)throw new y("user",`${Xr} must be between 1000 and 600000 milliseconds.`);return r}function Da(e){return e instanceof DOMException&&e.name==="AbortError"}function xb(e){let t=e instanceof Error?e.cause:null;return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:null}function Ua(e){return new jt("server",`Network timeout after ${e}ms.`,{hint:`Increase ${Xr} for slow links, or check the API connection.`})}function Eb(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 za(e,t,r,o){let{fetchInit:n,timeoutMs:i}=Eb(r),a=new AbortController,s=setTimeout(()=>a.abort(),i);try{let u=new Headers(n?.headers);u.set("Content-Type","application/json"),u.set("User-Agent",yb),e.token&&u.set("Authorization",`Bearer ${e.token}`);let c=await fetch(`${tt(e.apiUrl)}${t}`,{...n,headers:u,signal:a.signal}).catch(l=>{throw Da(l)?Ua(i):new jt("server",`Network error: could not reach ${tt(e.apiUrl)} (${xb(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(Da(d))throw Ua(i);return""});throw new ce(c.status,l,c.headers.get("x-request-id")??void 0,Ib(t))}return await o(c)}catch(u){throw u instanceof y?u:Da(u)?Ua(i):u instanceof TypeError?new jt("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 Ib(e){if(e.startsWith("/api/repos"))return"repo";if(e.startsWith("/api/sessions"))return"session"}async function R(e,t,r){return za(e,t,r,o=>o.json())}async function im(e,t,r){return za(e,t,r,o=>o.text())}async function om(e,t,r){return za(e,t,r,async o=>new Uint8Array(await o.arrayBuffer()))}var kb=/:([A-Za-z]+)/g,B={getCurrentUser:{method:"GET",pattern:"/api/auth/whoami"},exchangeCliLogin:{method:"POST",pattern:"/api/cli-login/exchange"},getGithubInstallation:{method:"GET",pattern:"/api/onboarding/github-installation"},answerOnboardingQuestion:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/question"},answerEnvironmentSecretRequest:{method:"POST",pattern:"/api/environments/:id/secret-requests/:requestId"},listRepositories:{method:"GET",pattern:"/api/repos"},listSessions:{method:"GET",pattern:"/api/sessions"},getSession:{method:"GET",pattern:"/api/sessions/:sessionId"},getSessionView:{method:"GET",pattern:"/api/sessions/:sessionId/view"},getSessionPrompts:{method:"GET",pattern:"/api/sessions/:sessionId/prompts"},getSessionEvents:{method:"GET",pattern:"/api/sessions/:sessionId/events"},getSessionEventHistory:{method:"GET",pattern:"/api/sessions/:sessionId/events/history"},exportSession:{method:"GET",pattern:"/api/sessions/:sessionId/export"},listSessionArtifacts:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/list"},viewSessionArtifact:{method:"GET",pattern:"/api/sessions/:sessionId/artifacts/:artifactId/view"},createReview:{method:"POST",pattern:"/api/pr-reviews"},getReviewRequest:{method:"GET",pattern:"/api/pr-reviews/requests/:requestId"},getReviewRequestStatuses:{method:"POST",pattern:"/api/pr-reviews/requests/status-batch"},createLocalReview:{method:"POST",pattern:"/api/local-reviews"},getLocalReview:{method:"GET",pattern:"/api/local-reviews/:requestId"},getRepositoryOnboarding:{method:"GET",pattern:"/api/settings/repositories/onboarding"},prepareRepository:{method:"POST",pattern:"/api/settings/repositories/onboarding"},retryRepositoryOnboarding:{method:"POST",pattern:"/api/settings/repositories/:owner/:repo/onboarding/retry"},listEnvironments:{method:"GET",pattern:"/api/environments"},getEnvironment:{method:"GET",pattern:"/api/environments/:id"},updateEnvironment:{method:"PUT",pattern:"/api/environments/:id"},createEnvironment:{method:"POST",pattern:"/api/environments"},getEnvironmentBrowserState:{method:"GET",pattern:"/api/environments/:id/browser-state"},setEnvironmentBrowserState:{method:"PUT",pattern:"/api/environments/:id/browser-state"},deleteEnvironmentBrowserState:{method:"DELETE",pattern:"/api/environments/:id/browser-state"}};function A(e,t={}){return am(e,t)}function am(e,t){return e.replace(kb,(r,o)=>{let n=t[o];if(n===void 0)throw new Error(`apiPath(${e}) is missing the ${o} parameter`);return encodeURIComponent(n)})}var tP=[{...B.getCurrentUser,command:"auth whoami"},{...B.exchangeCliLogin,command:"auth login",public:!0},{...B.getGithubInstallation,command:"onboard"},{...B.answerOnboardingQuestion,command:"environments answer"},{...B.answerEnvironmentSecretRequest,command:"environments secrets"},{...B.listRepositories,command:"repos list"},{...B.listSessions,command:"sessions list"},{...B.getSession,command:"sessions get"},{...B.getSessionView,command:"sessions view"},{...B.getSessionPrompts,command:"sessions events --follow"},{...B.getSessionEvents,command:"sessions events --follow"},{...B.getSessionEventHistory,command:"sessions events"},{...B.exportSession,command:"sessions transcript"},{...B.listSessionArtifacts,command:"sessions artifacts"},{...B.viewSessionArtifact,command:"sessions artifacts get"},{...B.createReview,command:"review <pr-url>"},{...B.getReviewRequest,command:"review <pr-url>"},{...B.getReviewRequest,command:"reviews get"},{...B.getReviewRequestStatuses,command:"reviews get"},{...B.createLocalReview,command:"review"},{...B.getLocalReview,command:"review --request"},{...B.getRepositoryOnboarding,command:"environments status"},{...B.prepareRepository,command:"environments prepare"},{...B.retryRepositoryOnboarding,command:"environments retry"},{...B.listEnvironments,command:"environments login"},{...B.getEnvironment,command:"environments login"},{...B.updateEnvironment,command:"environments login --validate-path"},{...B.listEnvironments,command:"environments export"},{...B.getEnvironment,command:"environments export"},{...B.listEnvironments,command:"environments import"},{...B.getEnvironment,command:"environments import"},{...B.updateEnvironment,command:"environments import"},{...B.createEnvironment,command:"environments import --create"},{...B.getEnvironmentBrowserState,command:"environments login"},{...B.setEnvironmentBrowserState,command:"environments login"},{...B.deleteEnvironmentBrowserState,command:"environments login --clear"}];import{createHash as um}from"node:crypto";import{existsSync as On,mkdirSync as Cb,readFileSync as La,statSync as Ob}from"node:fs";import{homedir as Nb}from"node:os";import{dirname as cm,join as yt,resolve as Db}from"node:path";import{randomUUID as Tb}from"node:crypto";import{renameSync as Ab,rmSync as Rb,writeFileSync as Pb}from"node:fs";function _t(e,t){let r=`${e}.${Tb()}.tmp`;try{Pb(r,JSON.stringify(t,null,2)+`
|
|
6
6
|
`,{mode:384,flag:"wx"}),Ab(r,e)}finally{Rb(r,{force:!0})}}var Ub=/\r?\n/,zb=/^\[|\]$/g,lm=yt(Nb(),".arcanist"),dm=yt(lm,"config.json"),rt=".arcanist-cli.json",Lb="https://app.tryarcanist.com";function Ma(){try{return JSON.parse(La(dm,"utf-8"))}catch{return null}}function Nn(e={}){let t=Mb(e);if(t)return sm(t);let r=ja(),o=Za(e,r!==null),n=Ma(),i=o?.apiUrl??r?.apiUrl??n?.apiUrl,a=r&&n?.apiUrl===r.apiUrl&&n.token&&n.supersededProjectTokenHash===um("sha256").update(r.token).digest("hex")?n.token:r?.token,s=o?.token??a??n?.token;if(!i||!s)return null;let u=sm({apiUrl:i,token:s});return r&&!o&&!e.json&&process.stderr.write(`using ${rt} -> ${u.apiUrl}
|
|
7
7
|
`),u}function Qr(e,t){let r=ti(e.apiUrl);if(r)throw new y("user",r);Cb(lm,{recursive:!0,mode:448});let o=tt(e.apiUrl),n=Ma(),i=t?um("sha256").update(t).digest("hex"):n?.apiUrl===o?n.supersededProjectTokenHash:void 0,a={...e,apiUrl:o,...i?{supersededProjectTokenHash:i}:{}};_t(dm,a)}function _e(e){let t=Nn(e);if(!t)throw new y("auth","Not logged in.",{hint:"Run `arcanist auth login` or set `ARCANIST_TOKEN`."});return t}function ei(e){let t=e??process.env.ARCANIST_API_URL??Ma()?.apiUrl??Lb,r=ti(t);if(r)throw new y("user",r);return tt(t)}function ja(e=process.cwd()){let t=jb(e);if(!t)return null;let r=e;for(;;){let o=yt(r,rt);if(On(o))return Bb(o);if(r===t)return null;let n=cm(r);if(n===r)return null;r=n}}function ti(e){let t;try{t=new URL(e)}catch{return"Invalid URL format"}return t.username||t.password?"API URL must not include embedded credentials. Use --token or ARCANIST_TOKEN to authenticate.":t.protocol!=="https:"&&!pm(t)?"API URL must use HTTPS for non-local hosts":null}function Za(e,t){let r=e.apiUrl??process.env.ARCANIST_API_URL,o=e.token??process.env.ARCANIST_TOKEN;if(!t)return!r&&!o?null:{apiUrl:r,token:o};if(r&&!o||!r&&o)throw new y("user",`${rt} is active; set both ARCANIST_API_URL and ARCANIST_TOKEN, pass both --api-url and --token, or set neither.`);return!r||!o?null:{apiUrl:r,token:o}}function Mb(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=ti(e.apiUrl);if(t)throw new y("user",t);return{apiUrl:tt(e.apiUrl),token:e.token}}function jb(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(!On(t))return!1;try{let r=Ob(t);if(r.isDirectory())return On(yt(t,"HEAD"))&&On(yt(t,"config"));if(!r.isFile())return!1;let o=Fb(t);return o?On(yt(Db(e,o),"HEAD")):!1}catch{return!1}}function Fb(e){let t=La(e,"utf-8").split(Ub).find(o=>o.startsWith("gitdir:"));return t&&t.slice(7).trim()||null}function Bb(e){let t;try{t=JSON.parse(La(e,"utf-8"))}catch{throw new y("user",`${rt} is not valid JSON.`)}if(!t||typeof t!="object")throw new y("user",`${rt} must contain both apiUrl and token.`);let r=t;if(typeof r.apiUrl!="string"||typeof r.token!="string"||!r.apiUrl||!r.token)throw new y("user",`${rt} must contain both apiUrl and token.`);let o;try{o=new URL(r.apiUrl)}catch{throw new y("user",`${rt} apiUrl must be a valid URL.`)}if(!pm(o))throw new y("user",`${rt} apiUrl must be a loopback host.`);let n=ti(r.apiUrl);if(n)throw new y("user",n);return{apiUrl:tt(r.apiUrl),token:r.token}}function pm(e){let t=e.hostname.replace(zb,"");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 Ee(e,t={}){return ee(e,t).json===!0}function qe(e){process.stdout.write(`${JSON.stringify(e)}
|
|
8
8
|
`)}function U(e,t,r,o){if(Ee(e,t)){qe(r);return}o(r)}function X(e,t={}){let r=ee(e,t);return{runtime:r,config:_e(r)}}async function Vb(){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 Dn(){return(await Vb()).trim()}function mm(e){(e.noColor===!0||!process.stdout.isTTY)&&(process.env.NO_COLOR="1")}var Gb=/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,qb=/\u001b\[[0-?]*[ -\/]*[@-~]/g,Wb=/[\u0000-\u001f\u007f]/g,Hb=/\r?\n/;function O(e){return e.replace(Gb,"").replace(qb,"").replace(Wb,"")}function De(e){return e.split(Hb).map(O).join(`
|
|
@@ -83,7 +83,7 @@ ${n.message}
|
|
|
83
83
|
Hint: ${n.hint??""}
|
|
84
84
|
`),process.exit(Ne)};for(let n of P_)process.once(n,t);let r=Date.now(),o=r;try{return await Tn({pollIntervalMs:e.pollIntervalMs,timeoutMs:Ip,timeoutMessage:kp,fetchStatus:async()=>{let n=z_(await U_(e.config,e.requestId)),i=Date.now();if(n===null&&i-o>=Ak){o=i;let a=Math.floor((i-r)/6e4);e.note(`Still reviewing (${a}m). Get the result later with \`${e.resumeCommand}\`.`)}return n}})}catch(n){throw n instanceof y&&n.message===kp?new y("server",kp,{hint:`The review may still finish. Get its result with \`${e.resumeCommand}\`.`}):n}finally{for(let n of P_)process.off(n,t)}}function C_(e,t,r){let o=De(t.failure?.message??"").trim(),n=t.failure?.code;return new y(e,o.length>0?o:r,{...n?{data:{serverCode:n}}:{}})}async function L_(e,t,r){try{return await(r===void 0?R(e,t):R(e,t,r))}catch(o){if(!(o instanceof ce))throw o;let n=o.data?.serverCode,i=n==="active_request_exists"?Ok(o.body):null,a=Ck(o,n,t,i),s=i?{...o.data,requestId:i}:o.data;throw new y(o.code,De(o.message),{exitCode:o.exitCode,...a?{hint:a}:{},...o.requestId?{requestId:o.requestId}:{},...s?{data:s}:{}})}}function Ck(e,t,r,o){switch(t){case"active_request_exists":return o?`Get its result with \`arcanist review --request ${o}\`.`:"Wait for your running review to finish, then retry.";case"paid_plan_required":case"review_limit_exceeded":return e.data?.billingUrl?`A workspace admin can change the plan at ${De(e.data.billingUrl)}.`:"Ask a workspace admin about your Arcanist plan.";case"repository_not_connected":return"Check accessible repositories with `arcanist repos list`.";case"payload_too_large":return"Review a smaller range with --base <ref>.";case"base_commit_not_found":return"Run `git fetch origin`, or pass --base <ref> with a ref that is on GitHub.";default:return e.status===404?r===N_?void 0:"Check the id passed to --request.":e.hint}}function Ok(e){try{let t=JSON.parse(e);if(typeof t.requestId!="string")return null;let r=O(t.requestId).trim();return r.length>0?r:null}catch{return null}}function Nk(e,t){return e?.optsWithGlobals?.()?.quiet===!0||t.quiet===!0?()=>{}:o=>{process.stderr.write(`${o}
|
|
85
85
|
`)}}function Dk(e,t){let r=[["Committed but not uploaded for review (pass --include <path> to upload)",t.payload.heldBackPaths],["Skipped binary files",t.skippedBinaryPaths],["Uncommitted changes are not reviewed",t.uncommittedPaths]];for(let[o,n]of r)n.length>0&&e(`${o}: ${n.map(O).join(", ")}`)}function Uk(e){let t=e.findings??[];console.log(Gr(e.verdict??"unknown",t)),e.environmentDegradedReason&&console.log(f_);let r=De(e.summary??"").trim();r.length>0&&console.log(r);for(let o of Lt(t,{withBody:!0}))console.log(o);for(let o of T_(e.alsoChecked??[]))console.log(o)}function O_(e){let t=O(e.requestId);console.log("Arcanist review is still running."),console.log(`Check again with \`arcanist review --request ${t} --no-wait\`, or wait for it with \`arcanist review --request ${t}\`.`)}import{spawn as zk}from"node:child_process";import{createHash as Lk,randomBytes as Mk}from"node:crypto";var M_="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function va(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`arcanist-cli-login-approval-code:${e}`))),r="";for(let o=0;o<8;o+=1)r+=M_[t[o]%M_.length];return`${r.slice(0,4)}-${r.slice(4)}`}var jk=2e3,Zk=10*6e4;async function j_(e,t){let r=ee(t,e),o=ei(r.apiUrl),n=Za(r,!1),i=null,a=null;if(e.tokenStdin?i=await Dn():n?.token&&(i=n.token),!i){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new y("user","No token provided.",{hint:"Pipe a token with --token-stdin or set ARCANIST_TOKEN. In a terminal, `arcanist auth login` opens the browser."});({token:i,scope:a}=await Bk(o,Fk(e.scope)))}if(!i.startsWith("arc_"))throw new y("user","Invalid token format. Token must start with 'arc_'.");try{await R({apiUrl:o,token:i},A("/api/auth/whoami"));let s={apiUrl:o,token:i};return Qr(s),e.emitResult===!1||(r.json?qe({ok:!0,apiUrl:o,...a?{scope:a}:{}}):r.quiet||(console.log(`Logged in. API: ${o}`),console.log("Token verified."))),s}catch(s){throw s instanceof ce&&(s.status===401||s.status===403)?new y("auth","Token could not be verified. It may be invalid or expired."):s}}function Fk(e){let t=e??"read";if(t!=="read"&&t!=="write")throw new y("user",`Invalid scope "${t}". Use read or write.`);return t}async function Bk(e,t){let r=Mk(32).toString("hex"),o=Lk("sha256").update(r).digest("hex"),n=`${e}/cli/login?challenge=${o}&scope=${t}`;console.error(`Your code: ${await va(o)}`),console.error("Opening your browser to sign in. Enter this code on the page to approve."),console.error(`If it does not open, open this URL:
|
|
86
|
-
${n}`),Vk(n);let i=Date.now()+Zk,a=()=>{process.exit(Ne)};process.once("SIGINT",a);try{for(;Date.now()<i;){let s;try{s=await R({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:r})})}catch(u){throw u instanceof ce&&(u.status===409||u.status===410)?new y("user",u.message):u}if(s.token)return{token:s.token,scope:s.scope??t};await new Promise(u=>setTimeout(u,jk))}}finally{process.off("SIGINT",a)}throw new y("user","Login timed out. Run arcanist auth login again.")}function Vk(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]],o=zk(t,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}var qr=[{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"]}],F_=qr.length-1,Gk="Finishing up";function Z_(e){return e?qr.findIndex(t=>t.stages.includes(e)):-1}function qk(e){if(e.status==="ready")return qr.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?F_:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=Z_(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=Z_(o)}return Math.max(t,r)}function B_(e){let t=qk(e);if(t>=qr.length)return null;let r=[...e.history??[],e.stage];return t===F_&&(r.includes("smoke_passed")||r.includes("completed"))?Gk:qr[t].label}import{createHash as Wk,randomUUID as Hk}from"node:crypto";import{mkdirSync as Kk,readFileSync as Jk,rmSync as Tp}from"node:fs";import{homedir as Yk}from"node:os";import{join as V_}from"node:path";import Xk from"proper-lockfile";var Qk=f.union([f.object({requestId:f.string().min(1),idempotencyKey:f.string().min(1).optional()}),f.object({requestId:f.undefined().optional(),idempotencyKey:f.string().min(1)})]);async function G_(e,t,r){let o=V_(Yk(),".arcanist");Kk(o,{recursive:!0,mode:448});let n=Wk("sha256").update(JSON.stringify({apiUrl:e.apiUrl,...t})).digest("hex"),i=V_(o,`onboarding-review-${n}.json`),a;try{a=await Xk.lock(i,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(s){throw s.code==="ELOCKED"?new y("conflict","Another review command is running or recovering. Retry this command shortly."):s}try{r&&Tp(i,{force:!0});let s=null;try{s=Qk.parse(JSON.parse(Jk(i,"utf8")))}catch(u){if(u.code!=="ENOENT")throw u}if(s||(s={requestId:void 0,idempotencyKey:Hk()},_t(i,s)),s.requestId===void 0){let u=await R(e,A("/api/pr-reviews"),{method:"POST",headers:{"Idempotency-Key":s.idempotencyKey},body:JSON.stringify({prUrl:t.prUrl})});if(!u.requestId)throw new y("server","The review did not return a request ID.");s={...s,requestId:u.requestId},_t(i,s)}try{let u=await R(e,A("/api/pr-reviews/requests/:requestId",{requestId:s.requestId}));return(u.status==="cancelled"||u.status==="admission_rejected")&&Tp(i,{force:!0}),u}catch(u){throw u instanceof ce&&u.status===404&&Tp(i,{force:!0}),u}}finally{await a()}}import{createHash as q_,randomBytes as eT}from"node:crypto";import{chmodSync as tT,mkdirSync as nT,readFileSync as rT,rmSync as iT}from"node:fs";import{homedir as oT}from"node:os";import{join as W_}from"node:path";import aT from"proper-lockfile";var sT=f.object({verifier:f.string().regex(/^[a-f0-9]{64}$/),expiresAt:f.number()}),uT=10*6e4;async function H_(e,t,r){let o=W_(oT(),".arcanist");nT(o,{recursive:!0,mode:448});let n=W_(o,`login-${q_("sha256").update(e).digest("hex")}.json`),i;try{i=await aT.lock(n,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(a){throw a.code==="ELOCKED"?new y("conflict","Another sign-in command is running or recovering. Retry this command shortly."):a}try{let a=Nn({json:!0});if(a?.apiUrl===e&&a.token!==r)return{status:"approved",config:a};let s=null;try{s=sT.parse(JSON.parse(rT(n,"utf8")))}catch(c){if(c.code!=="ENOENT")throw c}if(s){tT(n,384);try{let c=await R({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:s.verifier})});if(c.token){let l={apiUrl:e,token:c.token};return Qr(l,t),iT(n,{force:!0}),{status:"approved",config:l}}s.expiresAt<=Date.now()&&(s=null)}catch(c){if(!(c instanceof ce)||c.status!==410)throw c;s=null}}s||(s={verifier:eT(32).toString("hex"),expiresAt:Date.now()+uT},_t(n,s));let u=q_("sha256").update(s.verifier).digest("hex");return{status:"approval_required",authorizationUrl:`${e}/cli/login?challenge=${u}&scope=write`,approvalCode:await va(u),expiresAt:s.expiresAt}}finally{await i()}}async function _a(e,t,r){let o=ee(r,t),n=We(e),i=`${n.owner}/${n.repo}`;if(t.restartReview&&!t.pr)throw new y("user","--restart-review requires --pr.");let a=t.pr===void 0?null:Pm(t.pr);if(t.pr!==void 0&&(!a||`${a.owner}/${a.repo}`.toLowerCase()!==i.toLowerCase()))throw new y("user","--pr must be a GitHub pull request URL in the repository being onboarded.");let s=`arcanist onboard ${i}${a?` --pr ${a.prUrl}`:""}${o.apiUrl?` --api-url ${Qe(o.apiUrl)}`:""} --json`,u=Nn(o),c=u?.token,l=u?.apiUrl??ei(o.apiUrl),d=null;if(u)try{d=await R(u,A("/api/auth/whoami")),d.tokenScope!=="write"&&(u=null)}catch(b){if(!(b instanceof ce)||b.status!==401)throw b;u=null}if(!u){if(o.token||process.env.ARCANIST_TOKEN)throw new y("auth","The explicit token was rejected or lacks write access. Replace or unset it before onboarding.");let b=ja(),x=await H_(l,b?.apiUrl===l?b.token:void 0,c);if(x.status==="approval_required"){U(r,t,{...x,message:`One quick approval, then your agent can take it from here. Open this link, enter code ${x.approvalCode} to connect Arcanist, then return to your agent.`,command:s},k=>{console.log(k.message),console.log(k.authorizationUrl),console.log(`Code: ${k.approvalCode}`),console.log(`Then run: ${k.command}`)});return}u=x.config,d=await R(u,A("/api/auth/whoami"))}if(!d?.businessId||d.tokenScope!=="write")throw new y("auth","Onboarding needs write access to a workspace. Run arcanist onboard again to request it.");let m=(b,x,k=s)=>{U(r,t,{status:"github_approval_required",authorizationUrl:b,command:k,resumeCommand:s,message:x},C=>{console.log(C.message),console.log(C.authorizationUrl),console.log(`Then run: ${C.command}`)})},p;try{p=await et(u,i)}catch(b){if(!(b instanceof ce)||b.data?.serverCode!=="github_not_connected")throw b;let x=new URL("/auth/github/connect",u.apiUrl);x.searchParams.set("returnTo","/cli/onboarding"),m(x.toString(),"Connect your GitHub account, then resume onboarding.");return}let g=`Approve Arcanist access to ${i} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(p.nextAction==="prepare"){let[b]=await wp(u,{repositories:[n]});if(!b)throw new y("server","Environment setup returned no repository result.");if(b.status==="failed"&&b.reason==="installation_github_permissions_required"){if(d.businessRole!=="admin")throw new y("auth",Zr);g=Zr,p={...p,nextAction:"authorize_github"}}else if(b.status==="forbidden"){if(b.reason==="repository_limit"||d.businessRole!=="admin")throw new y("auth",`Cannot prepare ${i}: ${b.reason??"repository access required"}.`);p={...p,nextAction:"authorize_github"}}else{if(b.status==="failed"&&b.reason==="installation_github_check_failed")throw new y("server",ma);if(b.status==="failed")throw new y("server",`Could not start setup for ${i}.`);p=await et(u,i)}}if(p.nextAction==="authorize_github"){let b=await R(u,A("/api/onboarding/github-installation"));m(b.authorizationUrl,g,p.status==="failed"?`arcanist environments retry ${i}${o.apiUrl?` --api-url ${Qe(u.apiUrl)}`:""} --json`:s);return}if(p.command&&o.apiUrl&&(p={...p,command:`${p.command} --api-url ${Qe(u.apiUrl)}`}),p.nextAction==="review"&&a){let b=await G_(u,{businessId:d.businessId,userId:d.userId,prUrl:a.prUrl},t.restartReview===!0);if(b.status==="cancelled"||b.status==="admission_rejected")throw new y("user",b.terminalReason??`First review ${b.status}.`);let x=b.status==="completed"&&(b.verdict==="clear"||b.verdict==="issues_found")&&!!b.headSha,k=x?`You're set. Arcanist has completed its first review of ${i}. ${b.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:b.status==="completed"?"The first review needs attention before setup can be verified. Your agent can inspect the result and help with the next step.":`Arcanist is reviewing ${i}. Your agent can follow its progress; nothing is needed from you right now.`;U(r,t,{message:k,status:x?"complete":b.status==="completed"?"review_needs_attention":"review_pending",repository:p,reviewVerified:x,review:b,pullRequestUrl:a.prUrl,command:b.status==="completed"?null:s},C=>{console.log(C.message),console.log(a.prUrl),C.command&&console.log(`Continue with: ${C.command}`)});return}let E={review:`${i} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${B_({...p,status:p.status==="not_started"?"pending":p.status})??"Configuring the environment"} for ${i}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${i}. Your agent will share the question and continue with your answer.`,add_credentials:`${i} needs credentials to finish setup. Your agent will explain which ones are needed and help you provide them.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${i}. Your progress is saved.`,retry:`Setup for ${i} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${i}.`,authorize_github:`GitHub access is needed for ${i}.`}[p.nextAction];U(r,t,{message:E,status:p.nextAction==="review"?"repository_ready":p.nextAction==="wait"?"setup_pending":"action_required",repository:p,reviewVerified:!1,command:p.nextAction==="wait"?s:p.command,resumeCommand:s},b=>{console.log(b.message),b.command&&console.log(`Continue with: ${b.command}`)})}async function K_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await Dn();if(!o)throw new y("user","The answer must not be empty.");let n=We(e),{config:i}=X(r,t);if((await et(i,`${n.owner}/${n.repo}`)).question?.id!==t.question)throw new y("conflict","That question is no longer pending. Run arcanist onboard again.");let s=await R(i,A("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});U(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function J_(e,t,r){if(!t.entriesStdin)throw new y("user","Supply a JSON object of requested credentials through --entries-stdin.");let o;try{o=f.record(f.string(),f.string()).parse(JSON.parse(await Dn()))}catch{throw new y("user","Expected a JSON object mapping credential names to string values on stdin.")}let n=We(e),{config:i}=X(r,t),a=await et(i,`${n.owner}/${n.repo}`);if(a.secretRequest?.id!==t.request)throw new y("conflict","That credential request is no longer pending. Run arcanist onboard again.");await R(i,A("/api/environments/:id/secret-requests/:requestId",{id:a.secretRequest.environmentId,requestId:t.request}),{method:"POST",body:JSON.stringify({entries:o,...t.comment?{comment:t.comment}:{}})}),U(r,t,{ok:!0},()=>console.log("Credentials submitted. Run arcanist onboard to continue."))}async function Y_(e={},t){let{config:r}=X(t,e),o=await R(r,A("/api/repos"));U(t,e,{repos:o.repos,ssoOrgs:o.ssoOrgs},n=>{for(let i of n.repos)console.log(`${String(i.fullName??i.name??i.repo??"")} ${String(i.defaultBranch??"")}`);n.ssoOrgs.length>0&&console.log(`SSO withheld orgs: ${n.ssoOrgs.length}`)})}async function X_(e,t,r){let o=ee(r,t),n=_e(o),[i,a]=await Promise.all([R(n,A("/api/pr-reviews/requests/:requestId",{requestId:e})),R(n,A("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);U(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(De(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of Lt(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=O(l);console.log(`Next: arcanist sessions view ${d}`)}})}var Q_=["published","publish_failed","gate_rejected"],ey=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var ty=["bundle","ledger","disposition","lineage"];var ny=/^req-[0-9a-f]{8}$/;var cT=/^\d{1,3}$/,lT=/^fe[89ab]/,dT=/^f[cd]/,pT=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,mT=/^\[/,fT=/\]$/;var ry=300,Wr=500,Rp=3,gT=6e3;var iy=/^dl-[0-9a-f]{8}$/,hT=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function Ap(e){let t=e.split(".");if(t.length===4&&t.every(r=>cT.test(r)&&Number(r)<=255)){let[r,o]=t.map(Number);return r===0||r===10||r===127||r===169&&o===254||r===172&&o>=16&&o<=31||r===192&&o===168||r===100&&o>=64&&o<=127||r===198&&(o===18||o===19)}if(e.includes(":")){let r=e.toLowerCase();if(r==="::"||r==="::1"||lT.test(r)||dT.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(pT);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return Ap(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return Ap(o)}return!1}return!1}function vT(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(mT,"").replace(fT,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!hT.has(r)&&!Ap(r)}catch{return!1}}var aL=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(ry)}).strict(),f.object({kind:f.literal("fetch"),url:f.string().url().max(Wr).refine(vT,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(ry).optional(),offset:f.number().int().min(0).optional()}).strict()]),_T=f.object({url:f.string().max(Wr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(gT)}).strict(),sL=f.object({results:f.array(_T).max(Rp)}).strict();var cL=10*6e4,lL=14*6e4,dL=8*6e4,pL=19*6e4,mL=15*6e4,fL=4*6e4,gL=5*6e4;var hL=10*6e4,vL=5*6e4,_L=10*6e4;var oy=8;var yL=256*1024,bL=64*1024*1024,wL=15.5*6e4;var SL=5*6e4;var $L=256*1024;var ay=64*1024,xL=64*1024;var yT=30,Pp=oy*yT,Rn=f.string().trim().min(1).max(4e3),bT=f.object({id:f.string().regex(/^[a-zA-Z0-9._:-]+$/).max(80).describe("Stable id you choose for this work item; reuse it to update the item."),changedPath:Rn.describe("Changed file path from the admitted diff."),producer:Rn.describe("Code that produces the changed value or behavior."),consumer:Rn.describe("Actual code that consumes it."),inputState:Rn.describe("Concrete input or state that reaches the consumer."),status:f.enum(["pending","settled","refuted","below_bar","external","environment","budget_exhausted"]).describe("pending while open; any other status closes the item and needs reason. below_bar: verified and non-blocking; still filed as a finding."),evidence:f.array(Rn).max(Pp).describe("Source or probe references. Required for settled, refuted, below_bar."),reason:Rn.describe("Why the item has this status. Optional only while pending."),candidateIds:f.array(f.string().min(1).max(80)).max(Pp).describe("Delivered scout candidate ids this item covers."),findingIds:f.array(f.string().min(1).max(80)).max(Pp).describe("Ids of findings this item supports.")}).strict(),wT=bT.refine(e=>!["settled","refuted","below_bar"].includes(e.status)||e.evidence.length>0,{message:"A settled decision needs source or probe evidence."}),sy=f.string().regex(/^q-[1-9][0-9]*$/).max(16),TL=f.object({baseSha:f.string().nullable(),headSha:f.string().nullable(),items:f.array(wT),unreadRanges:f.array(f.object({path:f.string(),start:f.number().int(),end:f.number().int()})),reconciliationUsed:f.boolean().optional(),budgetExhausted:f.boolean().optional(),pendingPaths:f.array(f.string()),omittedRangeCount:f.number().int().nonnegative(),omittedPendingPathCount:f.number().int().nonnegative()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=ay,{message:"Investigation ledger exceeds the transport budget."});var NL=f.object({requestId:f.string().regex(ny),method:f.enum(["GET","HEAD"]),path:f.string().min(1).max(2e3),status:f.number().int().min(100).max(599).nullable(),authenticated:f.boolean(),redirected:f.object({location:f.string().max(2e3)}).strict().nullable(),contentType:f.string().max(200).nullable(),bodySha256:f.string().regex(/^[0-9a-f]{64}$/i).nullable(),bodyExcerpt:f.string().max(2e3).nullable(),promptId:f.string().min(1),bodyOmitted:f.enum(["binary","too_large","unreadable"]).optional()}).strict(),Cp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],DL=f.object({lookupId:f.string().regex(iy),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(Wr),status:f.enum(Cp),resultUrls:f.array(f.string().max(Wr)).max(Rp),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:sy.optional()}).strict(),ST=["ok","no_snapshot","invalid_input","unavailable","not_found","forbidden","unreadable"];var UL=f.object({spaceId:f.string().nullable(),path:f.string().max(500),status:f.enum(ST),promptId:f.string().min(1)}).strict(),zL=f.object({spaceId:f.string(),revision:f.string(),loadedPathCount:f.number().int().nonnegative(),unavailablePathCount:f.number().int().nonnegative(),designMemory:f.boolean()}).strict();var Op="zeus_telemetry";var uy=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],cy={state:{kind:"string_enum",values:["no_notification","turn_completed","command_running","tool_running","model_output_open","awaiting_model_output"]},lastNotificationMethod:"string",maxNotificationGapMs:"number",modelResponseCount:"number",streamRetryCount:"number",itemsInFlight:"number",oldestItemInFlight:{kind:"object",fields:{type:"string",tool:"string",msSinceStarted:"number"}},recentNotifications:"string_array"},$T={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},YL={"zeus.verification_observed":{observedCount:"number",hasObservedCommand:"boolean",matchedNoTestsCount:"number",runnerMismatchCount:"number",runnerResolved:"boolean",resolvedPackageManager:{kind:"string_enum",values:["npm","pnpm","yarn","bun"]}},"zeus.publish_rejected":{reason:"string",checkCount:"number",findingCount:"number",verdict:"string",firstAttempt:"boolean",attemptOrdinal:"number",contractVersion:"string",schemaPath:"string",schemaIssue:"string",schemaValue:"string"},"zeus.publish_secret_value_redacted":{count:"number"},"zeus.publish_notes_unverified":{attemptOrdinal:"number",findingCount:"number",contractVersion:"string"},"zeus.publish_empty_review_unattested":{attemptOrdinal:"number",noteCount:"number",contractVersion:"string"},"zeus.publish_blocking_downgraded":{detail:{kind:"string_enum",values:["no_base_run","no_matched_pair"]},blockingCount:"number",attemptOrdinal:"number"},"zeus.scout.health":{health:{kind:"string_enum",values:ey},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:Q_},candidateTotal:"number",expectedScoutCount:"number",observedScoutCount:"number",statuses:"string_array"},"zeus.scout.agreement":{candidateCount:"number",publishedCandidateCount:"number",examinedRejectedCount:"number",notExaminedCount:"number",notExaminedEnvironmentCount:"number",notExaminedExternalCount:"number",notExaminedNoneCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",verifierReportedPublishedCount:"number"},"zeus.candidate_ledger":{conserved:"boolean",candidateCount:"number",droppedCount:"number",publishedCandidateCount:"number",rejectedCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",violationStage:{kind:"string_enum",values:["none",...ty]}},"zeus.stage.peer_triage_completed":{reason:"string",threads:"number",stageStatus:{kind:"string_enum",values:["ok","failed","skipped"]}},"zeus.verifier.terminal":{verifierStatus:{kind:"string_enum",values:uy},effort:"string",stall:{kind:"object",fields:cy},codexTcpSockets:{kind:"object",fields:$T}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:uy},stall:{kind:"object",fields:cy},investigationId:"string",effort:"string",theme:"string"},"zeus.scout.completion":{role:"string",status:"string",durationMs:"number",inputTokens:"number",outputTokens:"number",candidateCount:"number"},"zeus.scout.bundle_omitted":{omittedCandidateCount:"number",droppedExcerptCount:"number"},"zeus.scout.patch_truncated":{role:"string",sampleIndex:"number",investigationId:"string",ownedFileCount:"number",truncatedFileCount:"number",omittedFileCount:"number",withheldChars:"number"},"zeus.scout.patch_unavailable":{role:"string",sampleIndex:"number",reason:"string",ownedFileCount:"number",patchedFileCount:"number"},"zeus.doc_lookup":{kind:{kind:"string_enum",values:["search","fetch"]},status:{kind:"string_enum",values:Cp},thread:{kind:"string_enum",values:["primary","scout"]},investigationId:"string",durationMs:"number",resultCount:"number"},"zeus.review.prompt_budget_truncated":{excessChars:"number",reviewContextPacketTruncated:"boolean",droppedSectionNames:"string_array",truncatedSectionNames:"string_array",beforeChars:"number",afterChars:"number"},"zeus.review.prompt_budget_externalized":{beforeChars:"number",afterChars:"number",budgetChars:"number",externalizedSectionNames:"string_array"},"zeus.scout.investigations_completed":{dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},aggregate_outcome:"string",candidate_total:"number",rate_limited_scout_count:"number",duration_ms:"number",prompt_id:"string",session_id:"string"}};var ly=["prompt.started","context.selected","files.inspected","tools.run","files.edited","commands.run","publish_gate.result","verification.result","git.commit","git.push","pr.open","onboarding.discovery_delivered","onboarding.discovery_tool_blocked"],dy=["observed"],py=["sandbox_bridge","control_plane"],my=["started","completed","failed","skipped","blocked"];var xT=["session.create","sandbox.spawn","bridge.connect","bridge.event","prompt.enqueue","prompt.context","prompt.dispatch","agent.session.create","tool.call","tool.update","tool.result","text.delta","prompt.complete","git.push","pr.open","timeline","error","user_question","idle"],Np=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Te(e){return typeof e=="number"&&Number.isFinite(e)}function Y(e){return e===void 0||typeof e=="string"}function fy(e){return e===void 0||z(e)}function ya(e){return e==null||typeof e=="string"}function Me(e,t){return typeof e=="string"&&t.includes(e)}function ET(e){return typeof e=="string"||z(e)&&typeof e.label=="string"&&Y(e.description)}function ue(e){return z(e)?Y(e.bridgeEventType)&&!gy(e)&&fy(e.bridgeData):!1}function gy(e){return z(e)?typeof e.bridgeEventType=="string"&&Np.has(e.bridgeEventType):!1}function ba(e,t){if(!z(t))return!1;switch(e){case"session.create":return ue(t)&&Me(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||Me(t.sessionKind,["repo"]));case"sandbox.spawn":return ue(t)&&Me(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Te(t.attempt))&&Y(t.reason);case"bridge.connect":return ue(t)&&Me(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!gy(t)&&fy(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ue(t)&&ya(t.actorUserId)&&Y(t.agent)&&ya(t.model);case"prompt.context":return ue(t);case"prompt.dispatch":return ue(t)&&ya(t.startupAttemptId);case"agent.session.create":return ue(t)&&Me(t.status,["started","complete","failed"])&&Y(t.agentSessionId)&&Y(t.agent);case"tool.call":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&Y(t.summary)&&(t.args===void 0||z(t.args));case"tool.result":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&Y(t.error);case"text.delta":return ue(t)&&Me(t.channel,["output","reasoning"])&&typeof t.text=="string"&&Y(t.partId);case"prompt.complete":return ue(t)&&typeof t.success=="boolean"&&Y(t.error)&&Y(t.errorCode);case"git.push":return ue(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&Y(t.error);case"pr.open":return ue(t)&&typeof t.success=="boolean"&&Y(t.prUrl)&&(t.prNumber===void 0||Te(t.prNumber))&&Y(t.error);case"timeline":return ue(t)&&Me(t.eventType,ly)&&Me(t.source,dy)&&Me(t.observer,py)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||Me(t.status,my))&&(t.metadata===void 0||z(t.metadata));case"error":return ue(t)&&typeof t.message=="string"&&Y(t.code);case"user_question":return ue(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(ET));case"idle":return ue(t)&&(t.sessionEditCount===void 0||Te(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Te(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function IT(e){return typeof e=="string"&&xT.includes(e)}function hy(e){if(!z(e))throw new Error("Invalid ArcanistEvent");if(!IT(e.phase))throw new Error("Invalid phase");if(typeof e.timestampMs!="number"||!Number.isFinite(e.timestampMs))throw new Error("Invalid timestampMs");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("Invalid sessionId");if(e.promptId!==void 0&&typeof e.promptId!="string")throw new Error("Invalid promptId");if(e.sandboxId!==void 0&&typeof e.sandboxId!="string")throw new Error("Invalid sandboxId");if(!z(e.payload))throw new Error("Invalid payload");if(e.formatVersion!==void 0&&e.formatVersion!==2)throw new Error("Invalid formatVersion");if(e.formatVersion===2&&["type","timestamp","content","messageId","bridgeData","bridgeEventType"].some(r=>r in e))throw new Error("Legacy fields in version 2 envelope");if(!(e.formatVersion===2||!("bridgeData"in e.payload||"bridgeEventType"in e.payload)?kT(e.phase,e.payload):ba(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function kT(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Te(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Te(t[o]))return!1;if(!Y(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return TT(t);case"tool.update":return typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.status=="string";case"bridge.connect":return typeof t.status=="string"&&(t.kind===void 0||t.kind==="heartbeat")&&Y(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return ya(t.startupAttemptId);case"prompt_accepted":return Y(t.startupAttemptId);case"agent_prompt_sent":return Y(t.startupAttemptId)&&Y(t.agentSessionId)&&Y(t.agentRuntimeBackend);case"prompt_activity":return Me(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&Y(t.detail)&&(t.childWorkActive===void 0||t.childWorkActive===!0);case"agent_progress":return typeof t.step=="string"&&typeof t.label=="string"&&(t.terminal===void 0||typeof t.terminal=="boolean");default:return!1}case"text.delta":return ba(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return ba(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&Y(t.btSpanId);default:return ba(e,t)}}function TT(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return Y(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return z(e.runtime);case"sandbox_undersized":return Te(e.oomKills);case"sandbox_enospc":return typeof e.source=="string";case"qa_memory_maintenance_codex_policy_probe":return typeof e.completed=="boolean"&&(e.codexHomeWriteStatus==="allowed"||e.codexHomeWriteStatus==="denied"||e.codexHomeWriteStatus==="missing")&&(e.checkoutWriteStatus==="allowed"||e.checkoutWriteStatus==="denied"||e.checkoutWriteStatus==="missing")&&typeof e.draftUnderDreamerDrafts=="boolean"&&typeof e.draftSubmissionMatched=="boolean";case"sandbox_resource_sample":return["memoryUsedBytes","memoryLimitBytes","memoryUsedPercent","swapUsedBytes","cpuUsedPercent","pidsCurrent","pidsLimit"].every(t=>e[t]===void 0||Te(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Te(e[t]));case"estimated_input_composition":return z(e.components);case"retry_status":return Te(e.attempt)&&typeof e.message=="string";case"tool_truncated":return typeof e.callId=="string"&&typeof e.tool=="string";case"compaction_start":return e.contextTokens===void 0||Te(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Te(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Te(e[t]));case"prompt_result":return!0;case"raw_agent_runtime":return!0;case"todo_update":return Array.isArray(e.todos)&&e.todos.every(t=>z(t)&&typeof t.id=="string"&&typeof t.content=="string"&&typeof t.status=="string");case"zeus_telemetry":return typeof e.eventName=="string";default:return!1}}function vy(e){switch(e.phase){case"bridge.event":return e.payload.kind==="raw_agent_runtime"&&e.payload.runtimeEventType==="codex_event"?"codex_event":e.payload.kind;case"bridge.connect":return e.payload.kind==="heartbeat"?"heartbeat":e.phase;case"prompt.dispatch":return e.payload.kind??"prompt_accepted";case"text.delta":return e.payload.finalAnswer?"final_answer":e.payload.channel==="reasoning"?"reasoning":"token";case"tool.call":return"tool_call";case"tool.update":return"tool_update";case"tool.result":return"tool_result";case"prompt.complete":return"execution_complete";case"user_question":return"question";case"error":return"error";case"idle":return"session_idle";case"agent.session.create":return"agent_session_created";case"timeline":return"agent_timeline";case"git.push":return e.payload.success?"push_complete":"push_error";default:return e.phase}}function Dp(e,t){if(!z(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return hy(e);if(typeof e.phase=="string"&&z(e.payload)){let m=e,p=e.payload;if(!z(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let g=z(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:E,...b}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...g,...b}};let x=typeof p.bridgeEventType=="string"?p.bridgeEventType:vy(m),k=m.phase==="text.delta"&&x==="text"?"token":m.phase==="prompt.dispatch"&&x==="prompt_processing"?"prompt_accepted":x,C=Dp({...g,type:k,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??g.messageId,promptId:m.promptId??g.promptId,ackId:e.ackId},m.sessionId??"");return C.phase==="bridge.connect"&&C.payload.kind==="heartbeat"&&delete b.status,b.startupAttemptId===null&&delete b.startupAttemptId,{...C,payload:{...C.payload,...b}}}if(typeof e.type!="string"||Np.has(e.type))throw new Error("Removed or invalid bridge event");if(t===void 0)throw new Error("Missing sessionId for legacy event");let{type:r,timestamp:o,messageId:n,promptId:i,sandboxId:a,ackId:s,...u}=e,c={sessionId:t,timestampMs:typeof o=="number"?o:Number.isFinite(Date.parse(String(o)))?Date.parse(String(o)):Date.now(),...typeof i=="string"?{promptId:i}:typeof n=="string"?{promptId:n}:{},...typeof a=="string"?{sandboxId:a}:{},...typeof s=="string"?{ackId:s}:{}},l,d;switch(r){case"heartbeat":l="bridge.connect",d={...u,kind:"heartbeat"};break;case"prompt_activity":{let{phase:m,...p}=u;l="prompt.dispatch",d={...p,kind:r,activityPhase:m};break}case"prompt_accepted":case"agent_progress":case"agent_prompt_sent":l="prompt.dispatch",d={...u,kind:r};break;case"token":case"reasoning":case"final_answer":{let{content:m,...p}=u;l="text.delta",d={...p,channel:r==="reasoning"?"reasoning":"output",text:m,...r==="final_answer"?{finalAnswer:!0,partId:u.partId??`${n}:final_answer`}:{}};break}case"tool_call":{let{args:m,...p}=u;l="tool.call",d=z(m)?{...p,args:m}:p;break}case"tool_update":l="tool.update",d=u;break;case"tool_result":l="tool.result",d={...u,ok:u.error===void 0};break;case"execution_complete":l="prompt.complete",d=u;break;case"error":case"session_error":{let{error:m,errorDetails:p,...g}=u;l="error",d={...g,message:m,...p!==void 0?{details:p}:{}};break}case"question":l="user_question",d=u;break;case"session_idle":l="idle",d=u;break;case"agent_session_created":l="agent.session.create",d={...u,status:"complete"};break;case"agent_timeline":l="timeline",d=u;break;case"codex_event":l="bridge.event",d={kind:"raw_agent_runtime",runtimeEventType:r,...u};break;case"zeus_telemetry":{let{kind:m,...p}=u;l="bridge.event",d={...p,kind:r,...m!==void 0?{lookupKind:m}:{}};break}case"patch":case"prompt_telemetry_start":case"post_execution":case"runtime_info":case"sandbox_undersized":case"sandbox_enospc":case"sandbox_resource_sample":case"usage":case"estimated_input_composition":case"retry_status":case"tool_truncated":case"compaction_start":case"compaction_complete":case"context_fill_warning":case"prompt_result":case"raw_agent_runtime":case"todo_update":l="bridge.event",d={...u,kind:r};break;default:l="bridge.event",d={...u,kind:"raw_agent_runtime",runtimeEventType:r}}return{...c,phase:l,payload:d}}var _y=["repo_scan_started","stack_detected","dependencies_resolved","setup_authored","runtime_profile_authored","boot_attempt_started","boot_verified","environment_saved","build_started","smoke_started","smoke_passed","smoke_failed","escalated_to_engineer","engineer_unblocked","escalated_to_customer","question_for_customer","customer_unblocked","completed","failed"],dM=_y.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),AT=["started","succeeded","failed"],RT=200;function PT(e){return typeof e=="string"&&_y.includes(e)}function CT(e){return typeof e=="string"&&AT.includes(e)}function yy(e){if(!z(e))return null;let t=e;if(!PT(t.stage))return null;let r=CT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,RT);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var OT="Arcanist blocked this malformed search command before execution.",NT=/\/bin\/bash:\s+-c:\s+line\s+\d+:\s+unexpected EOF while looking for matching [`'\"][`'\"]?/i,DT=24,UT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function wa(e){return"phase"in e&&typeof e.phase=="string"}var by=new WeakMap;function Sa(e){let t=by.get(e);return t||(t=Dp(e),by.set(e,t)),t}function $a(e){return Sa(e).payload}function zT(e){let t=$a(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function Iy(e){return $a(e).kind}function ky(e){return Sa(e).promptId}function de(e,t){let r=ky(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function LT(e,t,r){switch(t){case"tool_call":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{},...z(r.args)&&r.input===void 0?{input:r.args}:{}});case"tool_update":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{}});default:return de(e,r)}}function Hr(e){return wa(e)?ky(e):z(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function Pn(e){if(!wa(e))return e.type;let t=$a(e),r=Iy(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(Sa(e).phase){case"text.delta":return t.channel==="reasoning"?"reasoning":"text";case"tool.call":return"tool_call";case"tool.update":case"tool.result":return"tool_update";case"prompt.enqueue":return"prompt_enqueued";case"prompt.dispatch":return"prompt_processing";case"prompt.complete":return t.success===!1?"prompt_failed":"prompt_completed";case"user_question":return"question";case"error":return"session_error";case"bridge.event":return r??e.phase;case"timeline":return r??"agent_timeline";case"idle":return r??"session_idle";default:return r??e.phase}}function MT(e){if(wa(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=z(e.data)?e.data.timestamp:void 0;if(typeof t=="string"&&t.length>0||typeof t=="number"){let o=new Date(t);if(Number.isFinite(o.getTime()))return o.toISOString()}let r=e.timestamp;if(typeof r=="string"&&r.length>0||typeof r=="number"){let o=new Date(r);if(Number.isFinite(o.getTime()))return o.toISOString()}}function jT(e){let t=MT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function zp(e){if(!wa(e))return z(e.data)?e.data:void 0;let t=$a(e),r=Iy(e),o=de(e,zT(e));switch(Sa(e).phase){case"text.delta":return de(e,{...o,...typeof t.partId=="string"&&t.partId.length>0?{id:t.partId}:{},text:t.text});case"tool.call":return de(e,{...o,id:t.callId,tool:t.tool,input:z(t.args)?t.args:{},summary:typeof t.summary=="string"?t.summary:""});case"tool.update":return de(e,{...o,id:t.callId,status:t.status});case"tool.result":return de(e,{...o,id:t.callId,status:typeof o.status=="string"?o.status:t.ok?"completed":"error"});case"prompt.enqueue":return de(e,{...o,source:t.source,...t.actorUserId!==void 0?{actorUserId:t.actorUserId}:{},...typeof t.agent=="string"?{agent:t.agent}:{},...t.model!==void 0?{model:t.model}:{}});case"prompt.dispatch":return de(e,{...o,...t.startupAttemptId!==void 0?{startupAttemptId:t.startupAttemptId}:{}});case"prompt.complete":return de(e,{...o,success:t.success,...typeof t.error=="string"?{error:t.error}:{},...typeof t.errorCode=="string"?{code:t.errorCode}:{},...t.errorDetails!==void 0?{errorDetails:t.errorDetails}:{}});case"user_question":return de(e,{...o,id:t.questionId,question:t.question,...Array.isArray(t.options)?{options:t.options}:{}});case"error":return de(e,{...o,error:t.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.command=="string"?{command:t.command}:{},...t.details!==void 0?{errorDetails:t.details}:{}});case"bridge.event":return LT(e,r,o);case"timeline":return de(e,{...o,...typeof t.eventType=="string"?{eventType:t.eventType}:{},...typeof t.source=="string"?{source:t.source}:{},...typeof t.observer=="string"?{observer:t.observer}:{},...typeof t.summary=="string"?{summary:t.summary}:{},...typeof t.status=="string"?{status:t.status}:{},...z(t.metadata)?{metadata:t.metadata}:{}});case"idle":return de(e,{...o,...typeof t.sessionEditCount=="number"?{sessionEditCount:t.sessionEditCount}:{},...typeof t.sessionPromptCount=="number"?{sessionPromptCount:t.sessionPromptCount}:{}});default:return de(e,o)}}function Ty(e){let t=zp(e);return{raw:e,type:Pn(e),data:t,promptId:Hr(e)}}function wy(e){return e.map(t=>Ty(t))}function ZT(e,t){return t?t.length<DT?!0:!e.endsWith(t):!1}function FT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function BT(e,t){return`${e}:${t}`}function Sy(e,t){return t===0?e:`${e}#${t}`}function Mt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function VT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function GT(e){switch(e.type){case"agent_progress":case"retry_status":case"zeus_telemetry":case"agent_timeline":return!0;default:return!1}}function qT(e,t,r,o){if(o===e.length-1)return!0;let n=Math.max(o+1,t.interstitialScanEndByStreamId.get(r)??o+1);for(let i=n;i<e.length;i++)if(!GT(e[i]))return!1;return t.interstitialScanEndByStreamId.set(r,e.length),!0}function V(e){return typeof e?.promptId=="string"?e.promptId:void 0}function WT(e,t,r,o,n,i,a){let s=BT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=ZT(u,n);if(c!==void 0){let p=e[c];if(p.type===r&&l&&qT(e,t,s,c))return p.text+=n,t.concatByStreamId.set(s,u+n),!p.promptId&&i&&(p.promptId=i),p.type==="reasoning"&&a!==void 0&&(p.startedAtMs===void 0&&(p.startedAtMs=a),p.endedAtMs=a),!0;if(c===e.length-1||!l)return!1}if(u&&!l)return!1;let d=t.segmentOrdinalByStreamId.get(s),m=d===void 0?0:d+1;return t.segmentOrdinalByStreamId.set(s,m),t.streamableIndexById.set(s,e.length),t.concatByStreamId.set(s,u+n),t.interstitialScanEndByStreamId.set(s,e.length+1),r==="text"?e.push({type:"text",id:Sy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:Sy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{},...a!==void 0?{startedAtMs:a,endedAtMs:a}:{}}),!0}function HT(e,t){return{...e,...t,tool:t.tool??e.tool,summary:t.summary??e.summary,...t.promptId===void 0&&e.promptId!==void 0?{promptId:e.promptId}:{},...t.input===void 0&&e.input!==void 0?{input:e.input}:{},...t.toolStatus===void 0&&e.toolStatus!==void 0?{toolStatus:e.toolStatus}:{},...t.truncated===void 0&&e.truncated!==void 0?{truncated:e.truncated}:{},...t.inputEstimatedTokens===void 0&&e.inputEstimatedTokens!==void 0?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...t.outputEstimatedTokens===void 0&&e.outputEstimatedTokens!==void 0?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...t.outputChars===void 0&&e.outputChars!==void 0?{outputChars:e.outputChars}:{},...t.failure===void 0&&e.failure!==void 0?{failure:e.failure}:{},...t.duplicateCount===void 0&&e.duplicateCount!==void 0?{duplicateCount:e.duplicateCount}:{}}}function Up(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function KT(e,t){let r=Up(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...z(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function JT(){return{merged:[],streams:FT(),toolCallIndexById:new Map,agentProgressIndexByKey:new Map,questionIndexById:new Map,narrationIndex:null,malformedSearchBlockedPromptIds:new Set,malformedSearchBlockedWithoutPrompt:!1}}function YT(e){return typeof e=="string"&&e.includes(OT)}function XT(e){return NT.test(e)}function QT(e){return e.malformedSearchBlockedPromptIds.size===0&&!e.malformedSearchBlockedWithoutPrompt?e.merged:e.merged.filter(t=>t.type!=="text"?!0:!((t.promptId?e.malformedSearchBlockedPromptIds.has(t.promptId):e.malformedSearchBlockedWithoutPrompt)&&XT(t.text)))}function Oe(e,t){t&&e.merged.push(t)}function eA(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function tA(e,t){return{type:"compaction_complete",id:`cc-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokensBefore=="number"?{contextTokensBefore:e.contextTokensBefore}:{},...typeof e?.contextTokensAfter=="number"?{contextTokensAfter:e.contextTokensAfter}:{}}}function nA(e,t){return{type:"context_fill_warning",id:`cfw-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},fillPercent:typeof e?.fillPercent=="number"?e.fillPercent:Number(e?.fillPercent??0),...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{},...typeof e?.contextWindow=="number"?{contextWindow:e.contextWindow}:{}}}function rA(e,t){return{type:"tool_truncated",id:typeof e?.callId=="string"?e.callId:String(t),tool:typeof e?.tool=="string"?e.tool:"",...e?.reason==="truncation_marker"||e?.reason==="size_threshold"?{reason:e.reason}:{},...V(e)?{promptId:V(e)}:{}}}function iA(e,t){return{type:"retry_status",id:`rs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},attempt:typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),message:typeof e?.message=="string"?e.message:"Retrying...",...typeof e?.nextRetryAt=="string"?{nextRetryAt:e.nextRetryAt}:{},...typeof e?.provider=="string"?{provider:e.provider}:{},...typeof e?.errorCode=="string"?{errorCode:e.errorCode}:{},...typeof e?.scope=="string"?{scope:e.scope}:{},...typeof e?.maxAttempts=="number"?{maxAttempts:e.maxAttempts}:{},...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.retryAfterMs=="number"?{retryAfterMs:e.retryAfterMs}:{},...typeof e?.fallbackModel=="string"?{fallbackModel:e.fallbackModel}:{}}}function oA(e){return e==="spawn_provider_error"?{message:"Sandbox failed to start; retrying on a fresh sandbox",scope:"sandbox_spawn"}:e==="spawn_deadline_no_object"||e==="spawn_deadline_no_bridge"||e==="spawn_timeout"?{message:"Sandbox did not start in time; retrying on a fresh sandbox",scope:"sandbox_spawn"}:{message:"Sandbox dropped mid-task; retrying on a fresh sandbox",scope:"sandbox_disconnect"}}function aA(e,t){let r=typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),o=typeof e?.cap=="number"?e.cap:void 0,n=typeof e?.retryPromptId=="string"?e.retryPromptId:V(e),i=typeof e?.reason=="string"?e.reason:void 0,{message:a,scope:s}=oA(i);return{type:"retry_status",id:`pr-retry-${n??t}`,...n?{promptId:n}:{},attempt:r,message:a,scope:s,...o!==void 0?{maxAttempts:o}:{},...i?{reason:i}:{}}}function sA(e,t){let r=typeof e?.eventName=="string"?e.eventName:Op;return{type:Op,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function uA(e,t){return{type:"agent_timeline",id:`atl-${t}-${typeof e?.eventType=="string"?e.eventType:"unknown"}`,eventType:typeof e?.eventType=="string"?e.eventType:"unknown",source:typeof e?.source=="string"?e.source:"observed",observer:typeof e?.observer=="string"?e.observer:"unknown",summary:typeof e?.summary=="string"?e.summary:"Observed agent timeline event.",...typeof e?.status=="string"?{status:e.status}:{},...z(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function cA(e,t){let r=V(e);return{type:"agent_progress",id:Mt(e,"ap",t),step:typeof e?.step=="string"?e.step:"unknown",label:typeof e?.label=="string"?e.label:"Working",terminal:e?.terminal===!0,...r?{promptId:r}:{}}}function lA(e,t){let r=cA(e,t.merged.length),o=`${r.promptId??""}\0${r.step}`,n=t.agentProgressIndexByKey.get(o);if(n!==void 0){let i=t.merged[n];t.merged[n]=i.type==="agent_progress"?{...r,id:i.id}:r;return}t.agentProgressIndexByKey.set(o,t.merged.length),t.merged.push(r)}function dA(e,t){return{type:"session_error",id:Mt(e,"err",t),error:typeof e?.error=="string"?e.error:"Unknown error",...V(e)?{promptId:V(e)}:{},...typeof e?.code=="string"?{code:e.code}:{},...typeof e?.command=="string"?{command:e.command}:{}}}function pA(e,t){if(e?.code!=="malformed_search_command"&&!YT(e?.error))return;let r=V(e);r?t.malformedSearchBlockedPromptIds.add(r):t.malformedSearchBlockedWithoutPrompt=!0}function mA(e,t){return{type:"session_resumed_cold",id:Mt(e,"rescold",t),...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.lostSnapshotImageId=="string"?{lostSnapshotImageId:e.lostSnapshotImageId}:e?.lostSnapshotImageId===null?{lostSnapshotImageId:null}:{},...V(e)?{promptId:V(e)}:{}}}function fA(e,t){let r=typeof e?.partType=="string"?e.partType:void 0,o=typeof e?.eventType=="string"?e.eventType:void 0;return r==="text"||o&&UT.has(o)?null:{type:"raw_agent_runtime",id:Mt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function gA(e,t){let r=Array.isArray(e?.files)?e.files.filter(o=>typeof o=="string"):[];return r.length===0?null:{type:"patch",id:`patch-${t}`,files:r,...V(e)?{promptId:V(e)}:{}}}function $y(e,t,r,o){WT(r.merged,r.streams,e,Mt(t,e,r.merged.length),VT(t),V(t),o)}function hA(e,t){let r=Mt(e,"tool",t.merged.length),o=t.toolCallIndexById.get(r);if(o!==void 0){let n=t.merged[o];if(n.type==="tool_call"){let i=Up(e?.toolStatus),a=z(e?.input)?e.input:void 0,s={type:"tool_call",id:r,...typeof e?.tool=="string"?{tool:e.tool}:typeof e?.toolName=="string"?{tool:e.toolName}:{},...typeof e?.summary=="string"&&e.summary.length>0?{summary:e.summary}:{},...V(e)?{promptId:V(e)}:{},...a&&Object.keys(a).length>0?{input:a}:{},...i?{toolStatus:i}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...z(e?.failure)?{failure:e.failure}:{}};t.merged[o]=HT(n,s)}}else{let n=Up(e?.toolStatus),i={type:"tool_call",id:r,tool:typeof e?.tool=="string"?e.tool:typeof e?.toolName=="string"?e.toolName:"unknown",summary:typeof e?.summary=="string"?e.summary:"",...V(e)?{promptId:V(e)}:{},...z(e?.input)?{input:e.input}:{},...n?{toolStatus:n}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...z(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function vA(e,t){let r=typeof e?.id=="string"?e.id:"",o=t.toolCallIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n.type==="tool_call"&&(t.merged[o]=KT(n,e))}function _A(e,t){let r={type:"question",id:Mt(e,"question",t.merged.length),question:typeof e?.question=="string"?e.question:"",answer:e?.answer==null?null:String(e.answer),...V(e)?{promptId:V(e)}:{},...Array.isArray(e?.options)?{options:e.options}:{}};t.questionIndexById.set(r.id,t.merged.length),t.merged.push(r)}function yA(e,t){let r=typeof e?.id=="string"?e.id:void 0;if(!r)return;let o=t.questionIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n?.type==="question"&&(t.merged[o]={...n,answer:e?.answer==null?null:String(e.answer)})}function bA(e,t){let r=Array.isArray(e?.todos)?e.todos:[];if(r.length!==0)for(let o=t.merged.length-1;o>=0;o--){let n=t.merged[o];if(n.type==="tool_call"&&n.tool.toLowerCase()==="todowrite"){t.merged[o]={...n,input:{...n.input,todos:r}};break}}}function wA(e,t){let r=yy(e);if(!r)return;let o=V(e);t.merged.push({type:"onboarding_status",id:`onboarding_status:${t.merged.length}`,stage:r.stage,status:r.status,...r.detail?{detail:r.detail}:{},...o?{promptId:o}:{}})}function SA(e,t){let r=typeof e?.text=="string"?e.text.trim():"";if(!r)return;let o=V(e),n={type:"narration",id:"narration",text:r,...o?{promptId:o}:{}};t.narrationIndex===null?(t.narrationIndex=t.merged.length,t.merged.push(n)):t.merged[t.narrationIndex]=n}function Ay(e){let t=JT();for(let r of e){let o=Ty(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Oe(t,eA(i,t.merged.length));break;case"sandbox_compaction_complete":Oe(t,tA(i,t.merged.length));break;case"sandbox_context_fill_warning":Oe(t,nA(i,t.merged.length));break;case"sandbox_tool_truncated":Oe(t,rA(i,t.merged.length));break;case"retry_status":Oe(t,iA(i,t.merged.length));break;case"prompt_retrying":Oe(t,aA(i,t.merged.length));break;case"zeus_telemetry":Oe(t,sA(i,t.merged.length));break;case"agent_timeline":Oe(t,uA(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":lA(i,t);break;case"session_error":pA(i,t),Oe(t,dA(i,t.merged.length));break;case"session_resumed_cold":Oe(t,mA(i,t.merged.length));break;case"raw_agent_runtime":Oe(t,fA(i,t.merged.length));break;case"reasoning":$y("reasoning",i,t,jT(o.raw));break;case"text":$y("text",i,t);break;case"patch":Oe(t,gA(i,t.merged.length));break;case"todo_update":bA(i,t);break;case"answer":yA(i,t);break;case"tool_call":hA(i,t);break;case"tool_update":vA(i,t);break;case"question":_A(i,t);break;case"narration":SA(i,t);break;case"onboarding_status":wA(i,t);break}}return QT(t)}function Ry(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Hr(i),s=typeof a=="string"&&r.has(a)?a:null;Pn(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function $A(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="prompt_completed"&&r.type!=="prompt_failed")continue;let o=r.data?.history;return!Array.isArray(o)||o.length===0?null:o}return null}function xy(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function Ey(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function Py(e){let t=wy(e),r=$A(t),o=t.filter(b=>b.type==="prompt_activity"),n=t.filter(b=>b.type==="agent_progress");if(!r)return{events:e,diagnostics:{embeddedHistoryPresent:!1,durablePromptActivityCount:o.length,embeddedPromptActivityCount:0,mergedDurablePromptActivityCount:0,duplicateDurablePromptActivityCount:0,durableAgentProgressCount:n.length,embeddedAgentProgressCount:0,mergedDurableAgentProgressCount:0,duplicateDurableAgentProgressCount:0}};let i=wy(r),a=i.filter(b=>b.type==="prompt_activity"),s=i.filter(b=>b.type==="agent_progress"),u=new Set(a.map(xy)),c=new Set(s.map(Ey)),l=a.length,d=s.length,m=0,p=0,g=o.filter(b=>{let x=xy(b);return u.has(x)?(m+=1,!1):(u.add(x),!0)}),_=n.filter(b=>{let x=Ey(b);return c.has(x)?(p+=1,!1):(c.add(x),!0)}),E=[...g,..._].map(b=>b.raw);return{events:E.length>0?[...E,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:g.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var Cy=1e3;async function Oy(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>Cy)throw new y("user",`${e} exceeded ${Cy} pages without reaching the end.`);let u=await o(i);n.push(...u.items),a=u.nextCursor,i=a??void 0}while(t&&a);return{items:n,nextCursor:t?null:a}}import{createParser as LA}from"eventsource-parser";function xa(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function Ny(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function Ea(e){switch(e){case"no_diff":return{state:"no_changes",tone:"info",title:"Completed without code changes.",detail:null};case"no_staged_files":return{state:"no_changes",tone:"info",title:"Completed without publishable code changes.",detail:null};case"prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed before changes could be prepared.",detail:null};case"post_prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed after changes were prepared.",detail:null};default:return{state:"no_change_abnormal",tone:"error",title:"Completed without code changes, but finalization did not report a clean no-op reason.",detail:null}}}var xA="## Previously declined findings on this repository (calibration)",EA="## Findings already reported by other reviewers",IA="## Graphite stack neighbours",Dy=[xA,EA,IA,"## Independent review suggestions"];var zy=/\r?\n/,kA=/\n{3,}/g,TA=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,AA=[/^IMPORTANT: The content above is /i,/^Previous Slack message\b/i,/^Current Slack message author:/i,/^Current Slack channel:/i,/^Thread context(?:\s*\([^)]*\))?\s*[.:]/i,/^Repository:\s+\S+$/i,/^Issue (?:title|body|description|metadata)\s*:/i,/^Triggering comment\s*:/i,/^Review body\s*:/i,/^Recent comments\s*:/i,/^<\/?(?:user_content|instruction_content)\b/i],RA=[/<\/?(?:user_content|instruction_content)\b/i,/^IMPORTANT: The content above is /im,/^Previous Slack message\b/im,/^Current Slack message author:/im,/^Current Slack channel:/im,/^Repository:\s+\S+$/im],PA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function CA(e){let t=e.split(zy),r=[],o=[];if(t.forEach((a,s)=>{let u=Dy.findIndex(c=>a.trim()===c);u!==-1&&(r.push(u),o.push(s))}),o.length===0||!r.every((a,s)=>s===0||a>(r[s-1]??-1)))return e.trim();let i=o[0]??0;return t.slice(0,i).join(`
|
|
86
|
+
${n}`),Vk(n);let i=Date.now()+Zk,a=()=>{process.exit(Ne)};process.once("SIGINT",a);try{for(;Date.now()<i;){let s;try{s=await R({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:r})})}catch(u){throw u instanceof ce&&(u.status===409||u.status===410)?new y("user",u.message):u}if(s.token)return{token:s.token,scope:s.scope??t};await new Promise(u=>setTimeout(u,jk))}}finally{process.off("SIGINT",a)}throw new y("user","Login timed out. Run arcanist auth login again.")}function Vk(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]],o=zk(t,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}var qr=[{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"]}],F_=qr.length-1,Gk="Finishing up";function Z_(e){return e?qr.findIndex(t=>t.stages.includes(e)):-1}function qk(e){if(e.status==="ready")return qr.length;let t=e.buildStatus==="smoke_testing"||e.buildStatus==="trialing"?F_:e.buildStatus==="building"||e.status==="succeeded"?1:0,r=Z_(e.stage);for(let o of[...e.history??[]].reverse()){if(r>=0)break;r=Z_(o)}return Math.max(t,r)}function B_(e){let t=qk(e);if(t>=qr.length)return null;let r=[...e.history??[],e.stage];return t===F_&&(r.includes("smoke_passed")||r.includes("completed"))?Gk:qr[t].label}import{createHash as Wk,randomUUID as Hk}from"node:crypto";import{mkdirSync as Kk,readFileSync as Jk,rmSync as Tp}from"node:fs";import{homedir as Yk}from"node:os";import{join as V_}from"node:path";import Xk from"proper-lockfile";var Qk=f.union([f.object({requestId:f.string().min(1),idempotencyKey:f.string().min(1).optional()}),f.object({requestId:f.undefined().optional(),idempotencyKey:f.string().min(1)})]);async function G_(e,t,r){let o=V_(Yk(),".arcanist");Kk(o,{recursive:!0,mode:448});let n=Wk("sha256").update(JSON.stringify({apiUrl:e.apiUrl,...t})).digest("hex"),i=V_(o,`onboarding-review-${n}.json`),a;try{a=await Xk.lock(i,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(s){throw s.code==="ELOCKED"?new y("conflict","Another review command is running or recovering. Retry this command shortly."):s}try{r&&Tp(i,{force:!0});let s=null;try{s=Qk.parse(JSON.parse(Jk(i,"utf8")))}catch(u){if(u.code!=="ENOENT")throw u}if(s||(s={requestId:void 0,idempotencyKey:Hk()},_t(i,s)),s.requestId===void 0){let u=await R(e,A("/api/pr-reviews"),{method:"POST",headers:{"Idempotency-Key":s.idempotencyKey},body:JSON.stringify({prUrl:t.prUrl})});if(!u.requestId)throw new y("server","The review did not return a request ID.");s={...s,requestId:u.requestId},_t(i,s)}try{let u=await R(e,A("/api/pr-reviews/requests/:requestId",{requestId:s.requestId}));return(u.status==="cancelled"||u.status==="admission_rejected")&&Tp(i,{force:!0}),u}catch(u){throw u instanceof ce&&u.status===404&&Tp(i,{force:!0}),u}}finally{await a()}}import{createHash as q_,randomBytes as eT}from"node:crypto";import{chmodSync as tT,mkdirSync as nT,readFileSync as rT,rmSync as iT}from"node:fs";import{homedir as oT}from"node:os";import{join as W_}from"node:path";import aT from"proper-lockfile";var sT=f.object({verifier:f.string().regex(/^[a-f0-9]{64}$/),expiresAt:f.number()}),uT=10*6e4;async function H_(e,t,r){let o=W_(oT(),".arcanist");nT(o,{recursive:!0,mode:448});let n=W_(o,`login-${q_("sha256").update(e).digest("hex")}.json`),i;try{i=await aT.lock(n,{realpath:!1,retries:{retries:10,minTimeout:25,maxTimeout:100}})}catch(a){throw a.code==="ELOCKED"?new y("conflict","Another sign-in command is running or recovering. Retry this command shortly."):a}try{let a=Nn({json:!0});if(a?.apiUrl===e&&a.token!==r)return{status:"approved",config:a};let s=null;try{s=sT.parse(JSON.parse(rT(n,"utf8")))}catch(c){if(c.code!=="ENOENT")throw c}if(s){tT(n,384);try{let c=await R({apiUrl:e},A("/api/cli-login/exchange"),{method:"POST",body:JSON.stringify({verifier:s.verifier})});if(c.token){let l={apiUrl:e,token:c.token};return Qr(l,t),iT(n,{force:!0}),{status:"approved",config:l}}s.expiresAt<=Date.now()&&(s=null)}catch(c){if(!(c instanceof ce)||c.status!==410)throw c;s=null}}s||(s={verifier:eT(32).toString("hex"),expiresAt:Date.now()+uT},_t(n,s));let u=q_("sha256").update(s.verifier).digest("hex");return{status:"approval_required",authorizationUrl:`${e}/cli/login?challenge=${u}&scope=write`,approvalCode:await va(u),expiresAt:s.expiresAt}}finally{await i()}}async function _a(e,t,r){let o=ee(r,t),n=We(e),i=`${n.owner}/${n.repo}`;if(t.restartReview&&!t.pr)throw new y("user","--restart-review requires --pr.");let a=t.pr===void 0?null:Pm(t.pr);if(t.pr!==void 0&&(!a||`${a.owner}/${a.repo}`.toLowerCase()!==i.toLowerCase()))throw new y("user","--pr must be a GitHub pull request URL in the repository being onboarded.");let s=`arcanist onboard ${i}${a?` --pr ${a.prUrl}`:""}${o.apiUrl?` --api-url ${Qe(o.apiUrl)}`:""} --json`,u=Nn(o),c=u?.token,l=u?.apiUrl??ei(o.apiUrl),d=null;if(u)try{d=await R(u,A("/api/auth/whoami")),d.tokenScope!=="write"&&(u=null)}catch(b){if(!(b instanceof ce)||b.status!==401)throw b;u=null}if(!u){if(o.token||process.env.ARCANIST_TOKEN)throw new y("auth","The explicit token was rejected or lacks write access. Replace or unset it before onboarding.");let b=ja(),x=await H_(l,b?.apiUrl===l?b.token:void 0,c);if(x.status==="approval_required"){U(r,t,{...x,message:`One quick approval, then your agent can take it from here. Open this link, enter code ${x.approvalCode} to connect Arcanist, then return to your agent.`,command:s},k=>{console.log(k.message),console.log(k.authorizationUrl),console.log(`Code: ${k.approvalCode}`),console.log(`Then run: ${k.command}`)});return}u=x.config,d=await R(u,A("/api/auth/whoami"))}if(!d?.businessId||d.tokenScope!=="write")throw new y("auth","Onboarding needs write access to a workspace. Run arcanist onboard again to request it.");let m=(b,x,k=s)=>{U(r,t,{status:"github_approval_required",authorizationUrl:b,command:k,resumeCommand:s,message:x},C=>{console.log(C.message),console.log(C.authorizationUrl),console.log(`Then run: ${C.command}`)})},p;try{p=await et(u,i)}catch(b){if(!(b instanceof ce)||b.data?.serverCode!=="github_not_connected")throw b;let x=new URL("/auth/github/connect",u.apiUrl);x.searchParams.set("returnTo","/cli/onboarding"),m(x.toString(),"Connect your GitHub account, then resume onboarding.");return}let g=`Approve Arcanist access to ${i} on GitHub, then resume. If access is already granted, confirm this is the right workspace and that you can write to the repository.`;if(p.nextAction==="prepare"){let[b]=await wp(u,{repositories:[n]});if(!b)throw new y("server","Environment setup returned no repository result.");if(b.status==="failed"&&b.reason==="installation_github_permissions_required"){if(d.businessRole!=="admin")throw new y("auth",Zr);g=Zr,p={...p,nextAction:"authorize_github"}}else if(b.status==="forbidden"){if(b.reason==="repository_limit"||d.businessRole!=="admin")throw new y("auth",`Cannot prepare ${i}: ${b.reason??"repository access required"}.`);p={...p,nextAction:"authorize_github"}}else{if(b.status==="failed"&&b.reason==="installation_github_check_failed")throw new y("server",ma);if(b.status==="failed")throw new y("server",`Could not start setup for ${i}.`);p=await et(u,i)}}if(p.nextAction==="authorize_github"){let b=await R(u,A("/api/onboarding/github-installation"));m(b.authorizationUrl,g,p.status==="failed"?`arcanist environments retry ${i}${o.apiUrl?` --api-url ${Qe(u.apiUrl)}`:""} --json`:s);return}if(p.command&&o.apiUrl&&(p={...p,command:`${p.command} --api-url ${Qe(u.apiUrl)}`}),p.nextAction==="review"&&a){let b=await G_(u,{businessId:d.businessId,userId:d.userId,prUrl:a.prUrl},t.restartReview===!0);if(b.status==="cancelled"||b.status==="admission_rejected")throw new y("user",b.terminalReason??`First review ${b.status}.`);let x=b.status==="completed"&&(b.verdict==="clear"||b.verdict==="issues_found")&&!!b.headSha,k=x?`You're set. Arcanist has completed its first review of ${i}. ${b.verdict==="issues_found"?"The review found issues to look at.":"No issues were found in this review."}`:b.status==="completed"?"The first review needs attention before setup can be verified. Your agent can inspect the result and help with the next step.":`Arcanist is reviewing ${i}. Your agent can follow its progress; nothing is needed from you right now.`;U(r,t,{message:k,status:x?"complete":b.status==="completed"?"review_needs_attention":"review_pending",repository:p,reviewVerified:x,review:b,pullRequestUrl:a.prUrl,command:b.status==="completed"?null:s},C=>{console.log(C.message),console.log(a.prUrl),C.command&&console.log(`Continue with: ${C.command}`)});return}let E={review:`${i} is ready for its first review. Choose an existing pull request to see Arcanist in action.`,wait:`${B_({...p,status:p.status==="not_started"?"pending":p.status})??"Configuring the environment"} for ${i}. Your agent can keep checking; nothing is needed from you right now.`,answer_question:`One detail is needed to finish setting up ${i}. Your agent will share the question and continue with your answer.`,add_credentials:`${i} needs credentials to finish setup. Your agent will explain which ones are needed and help you provide them.`,wait_for_arcanist:`The Arcanist team needs to help with setup for ${i}. Your progress is saved.`,retry:`Setup for ${i} could not finish. Your agent can check what happened and retry from the saved setup.`,prepare:`Ready to start setting up ${i}.`,authorize_github:`GitHub access is needed for ${i}.`}[p.nextAction];U(r,t,{message:E,status:p.nextAction==="review"?"repository_ready":p.nextAction==="wait"?"setup_pending":"action_required",repository:p,reviewVerified:!1,command:p.nextAction==="wait"?s:p.command,resumeCommand:s},b=>{console.log(b.message),b.command&&console.log(`Continue with: ${b.command}`)})}async function K_(e,t,r){if(!t.answerStdin)throw new y("user","Supply the answer through --answer-stdin.");let o=await Dn();if(!o)throw new y("user","The answer must not be empty.");let n=We(e),{config:i}=X(r,t);if((await et(i,`${n.owner}/${n.repo}`)).question?.id!==t.question)throw new y("conflict","That question is no longer pending. Run arcanist onboard again.");let s=await R(i,A("/api/settings/repositories/:owner/:repo/onboarding/question",n),{method:"POST",body:JSON.stringify({questionId:t.question,answer:o})});U(r,t,s,()=>console.log("Answer submitted. Run arcanist onboard to continue."))}async function J_(e,t,r){if(!t.entriesStdin)throw new y("user","Supply a JSON object of requested credentials through --entries-stdin.");let o;try{o=f.record(f.string(),f.string()).parse(JSON.parse(await Dn()))}catch{throw new y("user","Expected a JSON object mapping credential names to string values on stdin.")}let n=We(e),{config:i}=X(r,t),a=await et(i,`${n.owner}/${n.repo}`);if(a.secretRequest?.id!==t.request)throw new y("conflict","That credential request is no longer pending. Run arcanist onboard again.");await R(i,A("/api/environments/:id/secret-requests/:requestId",{id:a.secretRequest.environmentId,requestId:t.request}),{method:"POST",body:JSON.stringify({entries:o,...t.comment?{comment:t.comment}:{}})}),U(r,t,{ok:!0},()=>console.log("Credentials submitted. Run arcanist onboard to continue."))}async function Y_(e={},t){let{config:r}=X(t,e),o=await R(r,A("/api/repos"));U(t,e,{repos:o.repos,ssoOrgs:o.ssoOrgs},n=>{for(let i of n.repos)console.log(`${String(i.fullName??i.name??i.repo??"")} ${String(i.defaultBranch??"")}`);n.ssoOrgs.length>0&&console.log(`SSO withheld orgs: ${n.ssoOrgs.length}`)})}async function X_(e,t,r){let o=ee(r,t),n=_e(o),[i,a]=await Promise.all([R(n,A("/api/pr-reviews/requests/:requestId",{requestId:e})),R(n,A("/api/pr-reviews/requests/status-batch"),{method:"POST",body:JSON.stringify({requestIds:[e]})})]);U(r,o,{review:i,requestStatus:a},s=>{if(o.quiet)return;let{findings:u,...c}=s.review;console.log(De(JSON.stringify({review:c,requestStatus:s.requestStatus},null,2)));for(let d of Lt(u,{withBody:!0}))console.log(d);let l=i.sessionId??a.requests[0]?.activeSessionId;if(l){let d=O(l);console.log(`Next: arcanist sessions view ${d}`)}})}var Q_=["published","publish_failed","gate_rejected"],ey=["not_applicable","never_ran","all_empty","completed_empty","yielded"];var ty=["bundle","ledger","disposition","lineage"];var ny=/^req-[0-9a-f]{8}$/;var cT=/^\d{1,3}$/,lT=/^fe[89ab]/,dT=/^f[cd]/,pT=/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/,mT=/^\[/,fT=/\]$/;var ry=300,Wr=500,Rp=3,gT=6e3;var iy=/^dl-[0-9a-f]{8}$/,hT=new Set(["localhost","localhost.localdomain","metadata","metadata.google.internal","instance-data","instance-data.ec2.internal"]);function Ap(e){let t=e.split(".");if(t.length===4&&t.every(r=>cT.test(r)&&Number(r)<=255)){let[r,o]=t.map(Number);return r===0||r===10||r===127||r===169&&o===254||r===172&&o>=16&&o<=31||r===192&&o===168||r===100&&o>=64&&o<=127||r===198&&(o===18||o===19)}if(e.includes(":")){let r=e.toLowerCase();if(r==="::"||r==="::1"||lT.test(r)||dT.test(r))return!0;if(r.startsWith("::ffff:")){let o=r.slice(7),n=o.match(pT);if(n){let i=Number.parseInt(n[1],16),a=Number.parseInt(n[2],16);return Ap(`${i>>8}.${i&255}.${a>>8}.${a&255}`)}return Ap(o)}return!1}return!1}function vT(e){try{let t=new URL(e),r=t.hostname.toLowerCase().replace(mT,"").replace(fT,"");return(t.protocol==="http:"||t.protocol==="https:")&&t.username===""&&t.password===""&&!hT.has(r)&&!Ap(r)}catch{return!1}}var aL=f.discriminatedUnion("kind",[f.object({kind:f.literal("search"),query:f.string().trim().min(3).max(ry)}).strict(),f.object({kind:f.literal("fetch"),url:f.string().url().max(Wr).refine(vT,{message:"url must be http(s) without credentials"}),query:f.string().trim().min(3).max(ry).optional(),offset:f.number().int().min(0).optional()}).strict()]),_T=f.object({url:f.string().max(Wr),title:f.string().max(300).nullable(),publishedDate:f.string().max(40).nullable(),text:f.string().max(gT)}).strict(),sL=f.object({results:f.array(_T).max(Rp)}).strict();var cL=10*6e4,lL=14*6e4,dL=8*6e4,pL=19*6e4,mL=20*6e4,fL=15*6e4,gL=4*6e4,hL=5*6e4;var vL=10*6e4,_L=5*6e4,yL=10*6e4;var oy=8;var bL=256*1024,wL=64*1024*1024,SL=15.5*6e4;var $L=5*6e4;var xL=256*1024;var ay=64*1024,EL=64*1024;var yT=30,Pp=oy*yT,Rn=f.string().trim().min(1).max(4e3),bT=f.object({id:f.string().regex(/^[a-zA-Z0-9._:-]+$/).max(80).describe("Stable id you choose for this work item; reuse it to update the item."),changedPath:Rn.describe("Changed file path from the admitted diff."),producer:Rn.describe("Code that produces the changed value or behavior."),consumer:Rn.describe("Actual code that consumes it."),inputState:Rn.describe("Concrete input or state that reaches the consumer."),status:f.enum(["pending","settled","refuted","below_bar","external","environment","budget_exhausted"]).describe("pending while open; any other status closes the item and needs reason. below_bar: verified and non-blocking; still filed as a finding."),evidence:f.array(Rn).max(Pp).describe("Source or probe references. Required for settled, refuted, below_bar."),reason:Rn.describe("Why the item has this status. Optional only while pending."),candidateIds:f.array(f.string().min(1).max(80)).max(Pp).describe("Delivered scout candidate ids this item covers."),findingIds:f.array(f.string().min(1).max(80)).max(Pp).describe("Ids of findings this item supports.")}).strict(),wT=bT.refine(e=>!["settled","refuted","below_bar"].includes(e.status)||e.evidence.length>0,{message:"A settled decision needs source or probe evidence."}),sy=f.string().regex(/^q-[1-9][0-9]*$/).max(16),AL=f.object({baseSha:f.string().nullable(),headSha:f.string().nullable(),items:f.array(wT),unreadRanges:f.array(f.object({path:f.string(),start:f.number().int(),end:f.number().int()})),reconciliationUsed:f.boolean().optional(),budgetExhausted:f.boolean().optional(),pendingPaths:f.array(f.string()),omittedRangeCount:f.number().int().nonnegative(),omittedPendingPathCount:f.number().int().nonnegative()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=ay,{message:"Investigation ledger exceeds the transport budget."});var DL=f.object({requestId:f.string().regex(ny),method:f.enum(["GET","HEAD"]),path:f.string().min(1).max(2e3),status:f.number().int().min(100).max(599).nullable(),authenticated:f.boolean(),redirected:f.object({location:f.string().max(2e3)}).strict().nullable(),contentType:f.string().max(200).nullable(),bodySha256:f.string().regex(/^[0-9a-f]{64}$/i).nullable(),bodyExcerpt:f.string().max(2e3).nullable(),promptId:f.string().min(1),bodyOmitted:f.enum(["binary","too_large","unreadable"]).optional()}).strict(),Cp=["ok","empty","rate_limited","upstream_error","invalid_input","budget_exhausted","page_unavailable","unavailable"],UL=f.object({lookupId:f.string().regex(iy),kind:f.enum(["search","fetch"]),input:f.string().min(1).max(Wr),status:f.enum(Cp),resultUrls:f.array(f.string().max(Wr)).max(Rp),durationMs:f.number().int().nonnegative(),promptId:f.string().min(1),thread:f.enum(["primary","scout"]),investigationId:sy.optional()}).strict(),ST=["ok","no_snapshot","invalid_input","unavailable","not_found","forbidden","unreadable"];var zL=f.object({spaceId:f.string().nullable(),path:f.string().max(500),status:f.enum(ST),promptId:f.string().min(1)}).strict(),LL=f.object({spaceId:f.string(),revision:f.string(),loadedPathCount:f.number().int().nonnegative(),unavailablePathCount:f.number().int().nonnegative(),designMemory:f.boolean()}).strict();var Op="zeus_telemetry";var uy=["succeeded","succeeded_empty","no_output","unparseable_output","failed","timed_out","aborted","hung","released_early"],cy={state:{kind:"string_enum",values:["no_notification","turn_completed","command_running","tool_running","model_output_open","awaiting_model_output"]},lastNotificationMethod:"string",maxNotificationGapMs:"number",modelResponseCount:"number",streamRetryCount:"number",itemsInFlight:"number",oldestItemInFlight:{kind:"object",fields:{type:"string",tool:"string",msSinceStarted:"number"}},recentNotifications:"string_array"},$T={unavailable:{kind:"string_enum",values:["no_pid","unsupported_platform","no_process"]},sockets:{kind:"object_array",fields:{remote:"string",state:"string",txQueueBytes:"number",rxQueueBytes:"number"}}},XL={"zeus.verification_observed":{observedCount:"number",hasObservedCommand:"boolean",matchedNoTestsCount:"number",runnerMismatchCount:"number",runnerResolved:"boolean",resolvedPackageManager:{kind:"string_enum",values:["npm","pnpm","yarn","bun"]}},"zeus.publish_rejected":{reason:"string",checkCount:"number",findingCount:"number",verdict:"string",firstAttempt:"boolean",attemptOrdinal:"number",contractVersion:"string",schemaPath:"string",schemaIssue:"string",schemaValue:"string"},"zeus.publish_secret_value_redacted":{count:"number"},"zeus.publish_notes_unverified":{attemptOrdinal:"number",findingCount:"number",contractVersion:"string"},"zeus.publish_empty_review_unattested":{attemptOrdinal:"number",noteCount:"number",contractVersion:"string"},"zeus.publish_blocking_downgraded":{detail:{kind:"string_enum",values:["no_base_run","no_matched_pair"]},blockingCount:"number",attemptOrdinal:"number"},"zeus.scout.health":{health:{kind:"string_enum",values:ey},dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},unresolvedInvestigationCount:"number",publishOutcome:{kind:"string_enum",values:Q_},candidateTotal:"number",expectedScoutCount:"number",observedScoutCount:"number",statuses:"string_array"},"zeus.scout.agreement":{candidateCount:"number",publishedCandidateCount:"number",examinedRejectedCount:"number",notExaminedCount:"number",notExaminedEnvironmentCount:"number",notExaminedExternalCount:"number",notExaminedNoneCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",verifierReportedPublishedCount:"number"},"zeus.candidate_ledger":{conserved:"boolean",candidateCount:"number",droppedCount:"number",publishedCandidateCount:"number",rejectedCount:"number",notDeliveredCount:"number",notSelectedCount:"number",verifierRefutedCount:"number",reproWithheldCount:"number",verifierReportedCount:"number",violationStage:{kind:"string_enum",values:["none",...ty]}},"zeus.stage.peer_triage_completed":{reason:"string",threads:"number",stageStatus:{kind:"string_enum",values:["ok","failed","skipped"]}},"zeus.verifier.terminal":{verifierStatus:{kind:"string_enum",values:uy},effort:"string",stall:{kind:"object",fields:cy},codexTcpSockets:{kind:"object",fields:$T}},"zeus.scout.terminal":{scoutStatus:{kind:"string_enum",values:uy},stall:{kind:"object",fields:cy},investigationId:"string",effort:"string",theme:"string"},"zeus.scout.completion":{role:"string",status:"string",durationMs:"number",inputTokens:"number",outputTokens:"number",candidateCount:"number"},"zeus.scout.bundle_omitted":{omittedCandidateCount:"number",droppedExcerptCount:"number"},"zeus.scout.patch_truncated":{role:"string",sampleIndex:"number",investigationId:"string",ownedFileCount:"number",truncatedFileCount:"number",omittedFileCount:"number",withheldChars:"number"},"zeus.scout.patch_unavailable":{role:"string",sampleIndex:"number",reason:"string",ownedFileCount:"number",patchedFileCount:"number"},"zeus.doc_lookup":{kind:{kind:"string_enum",values:["search","fetch"]},status:{kind:"string_enum",values:Cp},thread:{kind:"string_enum",values:["primary","scout"]},investigationId:"string",durationMs:"number",resultCount:"number"},"zeus.review.prompt_budget_truncated":{excessChars:"number",reviewContextPacketTruncated:"boolean",droppedSectionNames:"string_array",truncatedSectionNames:"string_array",beforeChars:"number",afterChars:"number"},"zeus.review.prompt_budget_externalized":{beforeChars:"number",afterChars:"number",budgetChars:"number",externalizedSectionNames:"string_array"},"zeus.scout.investigations_completed":{dispatch_mode:{kind:"string_enum",values:["targeted","broad"]},aggregate_outcome:"string",candidate_total:"number",rate_limited_scout_count:"number",duration_ms:"number",prompt_id:"string",session_id:"string"}};var ly=["prompt.started","context.selected","files.inspected","tools.run","files.edited","commands.run","publish_gate.result","verification.result","git.commit","git.push","pr.open","onboarding.discovery_delivered","onboarding.discovery_tool_blocked"],dy=["observed"],py=["sandbox_bridge","control_plane"],my=["started","completed","failed","skipped","blocked"];var xT=["session.create","sandbox.spawn","bridge.connect","bridge.event","prompt.enqueue","prompt.context","prompt.dispatch","agent.session.create","tool.call","tool.update","tool.result","text.delta","prompt.complete","git.push","pr.open","timeline","error","user_question","idle"],Np=new Set(["step_start","step_finish","branch_changed","subagent_start","subagent_complete","subagent_text","subagent_tool_call","memory_usage","memory_recall_usage"]);function Te(e){return typeof e=="number"&&Number.isFinite(e)}function Y(e){return e===void 0||typeof e=="string"}function fy(e){return e===void 0||z(e)}function ya(e){return e==null||typeof e=="string"}function Me(e,t){return typeof e=="string"&&t.includes(e)}function ET(e){return typeof e=="string"||z(e)&&typeof e.label=="string"&&Y(e.description)}function ue(e){return z(e)?Y(e.bridgeEventType)&&!gy(e)&&fy(e.bridgeData):!1}function gy(e){return z(e)?typeof e.bridgeEventType=="string"&&Np.has(e.bridgeEventType):!1}function ba(e,t){if(!z(t))return!1;switch(e){case"session.create":return ue(t)&&Me(t.source,["ui","cli","slack","api"])&&(t.sessionKind===void 0||Me(t.sessionKind,["repo"]));case"sandbox.spawn":return ue(t)&&Me(t.status,["requested","started","ready","failed"])&&(t.attempt===void 0||Te(t.attempt))&&Y(t.reason);case"bridge.connect":return ue(t)&&Me(t.status,["connected","disconnected","reconnecting"]);case"bridge.event":return typeof t.bridgeEventType=="string"&&!gy(t)&&fy(t.bridgeData)&&(t.intermediate===void 0||typeof t.intermediate=="boolean");case"prompt.enqueue":return ue(t)&&ya(t.actorUserId)&&Y(t.agent)&&ya(t.model);case"prompt.context":return ue(t);case"prompt.dispatch":return ue(t)&&ya(t.startupAttemptId);case"agent.session.create":return ue(t)&&Me(t.status,["started","complete","failed"])&&Y(t.agentSessionId)&&Y(t.agent);case"tool.call":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&Y(t.summary)&&(t.args===void 0||z(t.args));case"tool.result":return ue(t)&&typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.ok=="boolean"&&Y(t.error);case"text.delta":return ue(t)&&Me(t.channel,["output","reasoning"])&&typeof t.text=="string"&&Y(t.partId);case"prompt.complete":return ue(t)&&typeof t.success=="boolean"&&Y(t.error)&&Y(t.errorCode);case"git.push":return ue(t)&&typeof t.branch=="string"&&typeof t.success=="boolean"&&Y(t.error);case"pr.open":return ue(t)&&typeof t.success=="boolean"&&Y(t.prUrl)&&(t.prNumber===void 0||Te(t.prNumber))&&Y(t.error);case"timeline":return ue(t)&&Me(t.eventType,ly)&&Me(t.source,dy)&&Me(t.observer,py)&&typeof t.summary=="string"&&t.summary.trim().length>0&&(t.status===void 0||Me(t.status,my))&&(t.metadata===void 0||z(t.metadata));case"error":return ue(t)&&typeof t.message=="string"&&Y(t.code);case"user_question":return ue(t)&&typeof t.questionId=="string"&&typeof t.question=="string"&&(t.options===void 0||Array.isArray(t.options)&&t.options.every(ET));case"idle":return ue(t)&&(t.sessionEditCount===void 0||Te(t.sessionEditCount))&&(t.sessionPromptCount===void 0||Te(t.sessionPromptCount));case"tool.update":return!1;default:return!1}}function IT(e){return typeof e=="string"&&xT.includes(e)}function hy(e){if(!z(e))throw new Error("Invalid ArcanistEvent");if(!IT(e.phase))throw new Error("Invalid phase");if(typeof e.timestampMs!="number"||!Number.isFinite(e.timestampMs))throw new Error("Invalid timestampMs");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("Invalid sessionId");if(e.promptId!==void 0&&typeof e.promptId!="string")throw new Error("Invalid promptId");if(e.sandboxId!==void 0&&typeof e.sandboxId!="string")throw new Error("Invalid sandboxId");if(!z(e.payload))throw new Error("Invalid payload");if(e.formatVersion!==void 0&&e.formatVersion!==2)throw new Error("Invalid formatVersion");if(e.formatVersion===2&&["type","timestamp","content","messageId","bridgeData","bridgeEventType"].some(r=>r in e))throw new Error("Legacy fields in version 2 envelope");if(!(e.formatVersion===2||!("bridgeData"in e.payload||"bridgeEventType"in e.payload)?kT(e.phase,e.payload):ba(e.phase,e.payload)))throw new Error(`Invalid payload for phase ${e.phase}`);return e}function kT(e,t){if("bridgeData"in t||"bridgeEventType"in t||["startedAt","completedAt","inputEstimatedTokens","outputEstimatedTokens","outputChars","sessionEditCount","sessionPromptCount","connectionGeneration"].some(o=>t[o]!==void 0&&!Te(t[o])))return!1;for(let o of["exitCode","durationMs","startedAtMs"])if(t[o]!==void 0&&t[o]!==null&&!Te(t[o]))return!1;if(!Y(t.protocolStatus)||t.startObserved!==void 0&&typeof t.startObserved!="boolean")return!1;switch(e){case"bridge.event":return TT(t);case"tool.update":return typeof t.callId=="string"&&typeof t.tool=="string"&&typeof t.status=="string";case"bridge.connect":return typeof t.status=="string"&&(t.kind===void 0||t.kind==="heartbeat")&&Y(t.echoNonce);case"prompt.dispatch":switch(t.kind){case void 0:return ya(t.startupAttemptId);case"prompt_accepted":return Y(t.startupAttemptId);case"agent_prompt_sent":return Y(t.startupAttemptId)&&Y(t.agentSessionId)&&Y(t.agentRuntimeBackend);case"prompt_activity":return Me(t.activityPhase,["agent_runtime_initializing","session_creating","event_subscribing","prompt_preparing","prompt_dispatching","waiting_for_agent_event"])&&Y(t.detail)&&(t.childWorkActive===void 0||t.childWorkActive===!0);case"agent_progress":return typeof t.step=="string"&&typeof t.label=="string"&&(t.terminal===void 0||typeof t.terminal=="boolean");default:return!1}case"text.delta":return ba(e,t)&&(t.finalAnswer===void 0||t.finalAnswer===!0);case"prompt.complete":return ba(e,t)&&(t.idleObserved===void 0||typeof t.idleObserved=="boolean")&&Y(t.btSpanId);default:return ba(e,t)}}function TT(e){switch(e.kind){case"patch":return Array.isArray(e.files)&&e.files.every(t=>typeof t=="string");case"prompt_telemetry_start":return Y(e.btSpanId);case"post_execution":return typeof e.hasChanges=="boolean"&&(e.promptIntendsChange===void 0||typeof e.promptIntendsChange=="boolean");case"runtime_info":return z(e.runtime);case"sandbox_undersized":return Te(e.oomKills);case"sandbox_enospc":return typeof e.source=="string";case"qa_memory_maintenance_codex_policy_probe":return typeof e.completed=="boolean"&&(e.codexHomeWriteStatus==="allowed"||e.codexHomeWriteStatus==="denied"||e.codexHomeWriteStatus==="missing")&&(e.checkoutWriteStatus==="allowed"||e.checkoutWriteStatus==="denied"||e.checkoutWriteStatus==="missing")&&typeof e.draftUnderDreamerDrafts=="boolean"&&typeof e.draftSubmissionMatched=="boolean";case"sandbox_resource_sample":return["memoryUsedBytes","memoryLimitBytes","memoryUsedPercent","swapUsedBytes","cpuUsedPercent","pidsCurrent","pidsLimit"].every(t=>e[t]===void 0||Te(e[t]));case"usage":return["inputTokens","outputTokens","contextTokens"].every(t=>Te(e[t]));case"estimated_input_composition":return z(e.components);case"retry_status":return Te(e.attempt)&&typeof e.message=="string";case"tool_truncated":return typeof e.callId=="string"&&typeof e.tool=="string";case"compaction_start":return e.contextTokens===void 0||Te(e.contextTokens);case"compaction_complete":return["contextTokensBefore","contextTokensAfter"].every(t=>e[t]===void 0||Te(e[t]));case"context_fill_warning":return["fillPercent","contextTokens","contextWindow"].every(t=>Te(e[t]));case"prompt_result":return!0;case"raw_agent_runtime":return!0;case"todo_update":return Array.isArray(e.todos)&&e.todos.every(t=>z(t)&&typeof t.id=="string"&&typeof t.content=="string"&&typeof t.status=="string");case"zeus_telemetry":return typeof e.eventName=="string";default:return!1}}function vy(e){switch(e.phase){case"bridge.event":return e.payload.kind==="raw_agent_runtime"&&e.payload.runtimeEventType==="codex_event"?"codex_event":e.payload.kind;case"bridge.connect":return e.payload.kind==="heartbeat"?"heartbeat":e.phase;case"prompt.dispatch":return e.payload.kind??"prompt_accepted";case"text.delta":return e.payload.finalAnswer?"final_answer":e.payload.channel==="reasoning"?"reasoning":"token";case"tool.call":return"tool_call";case"tool.update":return"tool_update";case"tool.result":return"tool_result";case"prompt.complete":return"execution_complete";case"user_question":return"question";case"error":return"error";case"idle":return"session_idle";case"agent.session.create":return"agent_session_created";case"timeline":return"agent_timeline";case"git.push":return e.payload.success?"push_complete":"push_error";default:return e.phase}}function Dp(e,t){if(!z(e))throw new Error("Invalid event");if(e.formatVersion!==void 0)return hy(e);if(typeof e.phase=="string"&&z(e.payload)){let m=e,p=e.payload;if(!z(p))throw new Error("Invalid payload");if(!("bridgeData"in p||"bridgeEventType"in p))return m;let g=z(p.bridgeData)?p.bridgeData:{},{bridgeData:_,bridgeEventType:E,...b}=p;if(["session.create","sandbox.spawn","prompt.enqueue","pr.open","git.push"].includes(m.phase))return{...m,payload:{...g,...b}};let x=typeof p.bridgeEventType=="string"?p.bridgeEventType:vy(m),k=m.phase==="text.delta"&&x==="text"?"token":m.phase==="prompt.dispatch"&&x==="prompt_processing"?"prompt_accepted":x,C=Dp({...g,type:k,timestamp:m.timestampMs,sandboxId:m.sandboxId,messageId:m.promptId??g.messageId,promptId:m.promptId??g.promptId,ackId:e.ackId},m.sessionId??"");return C.phase==="bridge.connect"&&C.payload.kind==="heartbeat"&&delete b.status,b.startupAttemptId===null&&delete b.startupAttemptId,{...C,payload:{...C.payload,...b}}}if(typeof e.type!="string"||Np.has(e.type))throw new Error("Removed or invalid bridge event");if(t===void 0)throw new Error("Missing sessionId for legacy event");let{type:r,timestamp:o,messageId:n,promptId:i,sandboxId:a,ackId:s,...u}=e,c={sessionId:t,timestampMs:typeof o=="number"?o:Number.isFinite(Date.parse(String(o)))?Date.parse(String(o)):Date.now(),...typeof i=="string"?{promptId:i}:typeof n=="string"?{promptId:n}:{},...typeof a=="string"?{sandboxId:a}:{},...typeof s=="string"?{ackId:s}:{}},l,d;switch(r){case"heartbeat":l="bridge.connect",d={...u,kind:"heartbeat"};break;case"prompt_activity":{let{phase:m,...p}=u;l="prompt.dispatch",d={...p,kind:r,activityPhase:m};break}case"prompt_accepted":case"agent_progress":case"agent_prompt_sent":l="prompt.dispatch",d={...u,kind:r};break;case"token":case"reasoning":case"final_answer":{let{content:m,...p}=u;l="text.delta",d={...p,channel:r==="reasoning"?"reasoning":"output",text:m,...r==="final_answer"?{finalAnswer:!0,partId:u.partId??`${n}:final_answer`}:{}};break}case"tool_call":{let{args:m,...p}=u;l="tool.call",d=z(m)?{...p,args:m}:p;break}case"tool_update":l="tool.update",d=u;break;case"tool_result":l="tool.result",d={...u,ok:u.error===void 0};break;case"execution_complete":l="prompt.complete",d=u;break;case"error":case"session_error":{let{error:m,errorDetails:p,...g}=u;l="error",d={...g,message:m,...p!==void 0?{details:p}:{}};break}case"question":l="user_question",d=u;break;case"session_idle":l="idle",d=u;break;case"agent_session_created":l="agent.session.create",d={...u,status:"complete"};break;case"agent_timeline":l="timeline",d=u;break;case"codex_event":l="bridge.event",d={kind:"raw_agent_runtime",runtimeEventType:r,...u};break;case"zeus_telemetry":{let{kind:m,...p}=u;l="bridge.event",d={...p,kind:r,...m!==void 0?{lookupKind:m}:{}};break}case"patch":case"prompt_telemetry_start":case"post_execution":case"runtime_info":case"sandbox_undersized":case"sandbox_enospc":case"sandbox_resource_sample":case"usage":case"estimated_input_composition":case"retry_status":case"tool_truncated":case"compaction_start":case"compaction_complete":case"context_fill_warning":case"prompt_result":case"raw_agent_runtime":case"todo_update":l="bridge.event",d={...u,kind:r};break;default:l="bridge.event",d={...u,kind:"raw_agent_runtime",runtimeEventType:r}}return{...c,phase:l,payload:d}}var _y=["repo_scan_started","stack_detected","dependencies_resolved","setup_authored","runtime_profile_authored","boot_attempt_started","boot_verified","environment_saved","build_started","smoke_started","smoke_passed","smoke_failed","escalated_to_engineer","engineer_unblocked","escalated_to_customer","question_for_customer","customer_unblocked","completed","failed"],pM=_y.filter(e=>e!=="runtime_profile_authored"&&e!=="boot_attempt_started"&&e!=="boot_verified"),AT=["started","succeeded","failed"],RT=200;function PT(e){return typeof e=="string"&&_y.includes(e)}function CT(e){return typeof e=="string"&&AT.includes(e)}function yy(e){if(!z(e))return null;let t=e;if(!PT(t.stage))return null;let r=CT(t.status)?t.status:"started",n=(typeof t.detail=="string"?t.detail.trim():"").slice(0,RT);return{stage:t.stage,status:r,...n?{detail:n}:{}}}var OT="Arcanist blocked this malformed search command before execution.",NT=/\/bin\/bash:\s+-c:\s+line\s+\d+:\s+unexpected EOF while looking for matching [`'\"][`'\"]?/i,DT=24,UT=new Set(["session.updated","session.diff","server.heartbeat","session.idle","lsp.updated","lsp.client.diagnostics"]);function wa(e){return"phase"in e&&typeof e.phase=="string"}var by=new WeakMap;function Sa(e){let t=by.get(e);return t||(t=Dp(e),by.set(e,t)),t}function $a(e){return Sa(e).payload}function zT(e){let t=$a(e);return{...t,...t.activityPhase?{phase:t.activityPhase}:{}}}function Iy(e){return $a(e).kind}function ky(e){return Sa(e).promptId}function de(e,t){let r=ky(e);return r&&t.promptId===void 0?{...t,promptId:r}:t}function LT(e,t,r){switch(t){case"tool_call":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{},...z(r.args)&&r.input===void 0?{input:r.args}:{}});case"tool_update":return de(e,{...r,...typeof r.callId=="string"&&r.callId.length>0&&!(typeof r.id=="string"&&r.id.length>0)?{id:r.callId}:{}});default:return de(e,r)}}function Hr(e){return wa(e)?ky(e):z(e.data)&&typeof e.data.promptId=="string"&&e.data.promptId.length>0?e.data.promptId:void 0}function Pn(e){if(!wa(e))return e.type;let t=$a(e),r=Iy(e);if(r==="prompt_activity")return"prompt_activity";if(r==="agent_progress")return"agent_progress";switch(Sa(e).phase){case"text.delta":return t.channel==="reasoning"?"reasoning":"text";case"tool.call":return"tool_call";case"tool.update":case"tool.result":return"tool_update";case"prompt.enqueue":return"prompt_enqueued";case"prompt.dispatch":return"prompt_processing";case"prompt.complete":return t.success===!1?"prompt_failed":"prompt_completed";case"user_question":return"question";case"error":return"session_error";case"bridge.event":return r??e.phase;case"timeline":return r??"agent_timeline";case"idle":return r??"session_idle";default:return r??e.phase}}function MT(e){if(wa(e))return Number.isFinite(e.timestampMs)&&Number.isFinite(new Date(e.timestampMs).getTime())?new Date(e.timestampMs).toISOString():void 0;let t=z(e.data)?e.data.timestamp:void 0;if(typeof t=="string"&&t.length>0||typeof t=="number"){let o=new Date(t);if(Number.isFinite(o.getTime()))return o.toISOString()}let r=e.timestamp;if(typeof r=="string"&&r.length>0||typeof r=="number"){let o=new Date(r);if(Number.isFinite(o.getTime()))return o.toISOString()}}function jT(e){let t=MT(e);if(!t)return;let r=Date.parse(t);return Number.isFinite(r)?r:void 0}function zp(e){if(!wa(e))return z(e.data)?e.data:void 0;let t=$a(e),r=Iy(e),o=de(e,zT(e));switch(Sa(e).phase){case"text.delta":return de(e,{...o,...typeof t.partId=="string"&&t.partId.length>0?{id:t.partId}:{},text:t.text});case"tool.call":return de(e,{...o,id:t.callId,tool:t.tool,input:z(t.args)?t.args:{},summary:typeof t.summary=="string"?t.summary:""});case"tool.update":return de(e,{...o,id:t.callId,status:t.status});case"tool.result":return de(e,{...o,id:t.callId,status:typeof o.status=="string"?o.status:t.ok?"completed":"error"});case"prompt.enqueue":return de(e,{...o,source:t.source,...t.actorUserId!==void 0?{actorUserId:t.actorUserId}:{},...typeof t.agent=="string"?{agent:t.agent}:{},...t.model!==void 0?{model:t.model}:{}});case"prompt.dispatch":return de(e,{...o,...t.startupAttemptId!==void 0?{startupAttemptId:t.startupAttemptId}:{}});case"prompt.complete":return de(e,{...o,success:t.success,...typeof t.error=="string"?{error:t.error}:{},...typeof t.errorCode=="string"?{code:t.errorCode}:{},...t.errorDetails!==void 0?{errorDetails:t.errorDetails}:{}});case"user_question":return de(e,{...o,id:t.questionId,question:t.question,...Array.isArray(t.options)?{options:t.options}:{}});case"error":return de(e,{...o,error:t.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.command=="string"?{command:t.command}:{},...t.details!==void 0?{errorDetails:t.details}:{}});case"bridge.event":return LT(e,r,o);case"timeline":return de(e,{...o,...typeof t.eventType=="string"?{eventType:t.eventType}:{},...typeof t.source=="string"?{source:t.source}:{},...typeof t.observer=="string"?{observer:t.observer}:{},...typeof t.summary=="string"?{summary:t.summary}:{},...typeof t.status=="string"?{status:t.status}:{},...z(t.metadata)?{metadata:t.metadata}:{}});case"idle":return de(e,{...o,...typeof t.sessionEditCount=="number"?{sessionEditCount:t.sessionEditCount}:{},...typeof t.sessionPromptCount=="number"?{sessionPromptCount:t.sessionPromptCount}:{}});default:return de(e,o)}}function Ty(e){let t=zp(e);return{raw:e,type:Pn(e),data:t,promptId:Hr(e)}}function wy(e){return e.map(t=>Ty(t))}function ZT(e,t){return t?t.length<DT?!0:!e.endsWith(t):!1}function FT(){return{streamableIndexById:new Map,segmentOrdinalByStreamId:new Map,concatByStreamId:new Map,interstitialScanEndByStreamId:new Map}}function BT(e,t){return`${e}:${t}`}function Sy(e,t){return t===0?e:`${e}#${t}`}function Mt(e,t,r){return typeof e?.id=="string"?e.id:`${t}-${r}`}function VT(e){let t=e?.text;if(typeof t=="string")return t;let r=e?.content;return typeof r=="string"?r:""}function GT(e){switch(e.type){case"agent_progress":case"retry_status":case"zeus_telemetry":case"agent_timeline":return!0;default:return!1}}function qT(e,t,r,o){if(o===e.length-1)return!0;let n=Math.max(o+1,t.interstitialScanEndByStreamId.get(r)??o+1);for(let i=n;i<e.length;i++)if(!GT(e[i]))return!1;return t.interstitialScanEndByStreamId.set(r,e.length),!0}function V(e){return typeof e?.promptId=="string"?e.promptId:void 0}function WT(e,t,r,o,n,i,a){let s=BT(r,o),u=t.concatByStreamId.get(s)??"",c=t.streamableIndexById.get(s),l=ZT(u,n);if(c!==void 0){let p=e[c];if(p.type===r&&l&&qT(e,t,s,c))return p.text+=n,t.concatByStreamId.set(s,u+n),!p.promptId&&i&&(p.promptId=i),p.type==="reasoning"&&a!==void 0&&(p.startedAtMs===void 0&&(p.startedAtMs=a),p.endedAtMs=a),!0;if(c===e.length-1||!l)return!1}if(u&&!l)return!1;let d=t.segmentOrdinalByStreamId.get(s),m=d===void 0?0:d+1;return t.segmentOrdinalByStreamId.set(s,m),t.streamableIndexById.set(s,e.length),t.concatByStreamId.set(s,u+n),t.interstitialScanEndByStreamId.set(s,e.length+1),r==="text"?e.push({type:"text",id:Sy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{}}):e.push({type:"reasoning",id:Sy(o,m),...m>0?{streamId:o}:{},text:n,...i?{promptId:i}:{},...a!==void 0?{startedAtMs:a,endedAtMs:a}:{}}),!0}function HT(e,t){return{...e,...t,tool:t.tool??e.tool,summary:t.summary??e.summary,...t.promptId===void 0&&e.promptId!==void 0?{promptId:e.promptId}:{},...t.input===void 0&&e.input!==void 0?{input:e.input}:{},...t.toolStatus===void 0&&e.toolStatus!==void 0?{toolStatus:e.toolStatus}:{},...t.truncated===void 0&&e.truncated!==void 0?{truncated:e.truncated}:{},...t.inputEstimatedTokens===void 0&&e.inputEstimatedTokens!==void 0?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...t.outputEstimatedTokens===void 0&&e.outputEstimatedTokens!==void 0?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...t.outputChars===void 0&&e.outputChars!==void 0?{outputChars:e.outputChars}:{},...t.failure===void 0&&e.failure!==void 0?{failure:e.failure}:{},...t.duplicateCount===void 0&&e.duplicateCount!==void 0?{duplicateCount:e.duplicateCount}:{}}}function Up(e){return e==="running"||e==="completed"||e==="error"?e:void 0}function KT(e,t){let r=Up(t?.status);return{...e,...r?{toolStatus:r}:{},...typeof t?.outputEstimatedTokens=="number"?{outputEstimatedTokens:t.outputEstimatedTokens}:{},...typeof t?.outputChars=="number"?{outputChars:t.outputChars}:{},...z(t?.failure)?{failure:t.failure}:{},...typeof t?.truncated=="boolean"?{truncated:t.truncated}:{}}}function JT(){return{merged:[],streams:FT(),toolCallIndexById:new Map,agentProgressIndexByKey:new Map,questionIndexById:new Map,narrationIndex:null,malformedSearchBlockedPromptIds:new Set,malformedSearchBlockedWithoutPrompt:!1}}function YT(e){return typeof e=="string"&&e.includes(OT)}function XT(e){return NT.test(e)}function QT(e){return e.malformedSearchBlockedPromptIds.size===0&&!e.malformedSearchBlockedWithoutPrompt?e.merged:e.merged.filter(t=>t.type!=="text"?!0:!((t.promptId?e.malformedSearchBlockedPromptIds.has(t.promptId):e.malformedSearchBlockedWithoutPrompt)&&XT(t.text)))}function Oe(e,t){t&&e.merged.push(t)}function eA(e,t){return{type:"compaction_start",id:`cs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{}}}function tA(e,t){return{type:"compaction_complete",id:`cc-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},...typeof e?.contextTokensBefore=="number"?{contextTokensBefore:e.contextTokensBefore}:{},...typeof e?.contextTokensAfter=="number"?{contextTokensAfter:e.contextTokensAfter}:{}}}function nA(e,t){return{type:"context_fill_warning",id:`cfw-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},fillPercent:typeof e?.fillPercent=="number"?e.fillPercent:Number(e?.fillPercent??0),...typeof e?.contextTokens=="number"?{contextTokens:e.contextTokens}:{},...typeof e?.contextWindow=="number"?{contextWindow:e.contextWindow}:{}}}function rA(e,t){return{type:"tool_truncated",id:typeof e?.callId=="string"?e.callId:String(t),tool:typeof e?.tool=="string"?e.tool:"",...e?.reason==="truncation_marker"||e?.reason==="size_threshold"?{reason:e.reason}:{},...V(e)?{promptId:V(e)}:{}}}function iA(e,t){return{type:"retry_status",id:`rs-${e?.timestamp??t}`,...V(e)?{promptId:V(e)}:{},attempt:typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),message:typeof e?.message=="string"?e.message:"Retrying...",...typeof e?.nextRetryAt=="string"?{nextRetryAt:e.nextRetryAt}:{},...typeof e?.provider=="string"?{provider:e.provider}:{},...typeof e?.errorCode=="string"?{errorCode:e.errorCode}:{},...typeof e?.scope=="string"?{scope:e.scope}:{},...typeof e?.maxAttempts=="number"?{maxAttempts:e.maxAttempts}:{},...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.retryAfterMs=="number"?{retryAfterMs:e.retryAfterMs}:{},...typeof e?.fallbackModel=="string"?{fallbackModel:e.fallbackModel}:{}}}function oA(e){return e==="spawn_provider_error"?{message:"Sandbox failed to start; retrying on a fresh sandbox",scope:"sandbox_spawn"}:e==="spawn_deadline_no_object"||e==="spawn_deadline_no_bridge"||e==="spawn_timeout"?{message:"Sandbox did not start in time; retrying on a fresh sandbox",scope:"sandbox_spawn"}:{message:"Sandbox dropped mid-task; retrying on a fresh sandbox",scope:"sandbox_disconnect"}}function aA(e,t){let r=typeof e?.attempt=="number"?e.attempt:Number(e?.attempt??0),o=typeof e?.cap=="number"?e.cap:void 0,n=typeof e?.retryPromptId=="string"?e.retryPromptId:V(e),i=typeof e?.reason=="string"?e.reason:void 0,{message:a,scope:s}=oA(i);return{type:"retry_status",id:`pr-retry-${n??t}`,...n?{promptId:n}:{},attempt:r,message:a,scope:s,...o!==void 0?{maxAttempts:o}:{},...i?{reason:i}:{}}}function sA(e,t){let r=typeof e?.eventName=="string"?e.eventName:Op;return{type:Op,id:`zeus-tel-${e?.timestamp??t}-${r}`,eventName:r,...V(e)?{promptId:V(e)}:{}}}function uA(e,t){return{type:"agent_timeline",id:`atl-${t}-${typeof e?.eventType=="string"?e.eventType:"unknown"}`,eventType:typeof e?.eventType=="string"?e.eventType:"unknown",source:typeof e?.source=="string"?e.source:"observed",observer:typeof e?.observer=="string"?e.observer:"unknown",summary:typeof e?.summary=="string"?e.summary:"Observed agent timeline event.",...typeof e?.status=="string"?{status:e.status}:{},...z(e?.metadata)?{metadata:e.metadata}:{},...V(e)?{promptId:V(e)}:{}}}function cA(e,t){let r=V(e);return{type:"agent_progress",id:Mt(e,"ap",t),step:typeof e?.step=="string"?e.step:"unknown",label:typeof e?.label=="string"?e.label:"Working",terminal:e?.terminal===!0,...r?{promptId:r}:{}}}function lA(e,t){let r=cA(e,t.merged.length),o=`${r.promptId??""}\0${r.step}`,n=t.agentProgressIndexByKey.get(o);if(n!==void 0){let i=t.merged[n];t.merged[n]=i.type==="agent_progress"?{...r,id:i.id}:r;return}t.agentProgressIndexByKey.set(o,t.merged.length),t.merged.push(r)}function dA(e,t){return{type:"session_error",id:Mt(e,"err",t),error:typeof e?.error=="string"?e.error:"Unknown error",...V(e)?{promptId:V(e)}:{},...typeof e?.code=="string"?{code:e.code}:{},...typeof e?.command=="string"?{command:e.command}:{}}}function pA(e,t){if(e?.code!=="malformed_search_command"&&!YT(e?.error))return;let r=V(e);r?t.malformedSearchBlockedPromptIds.add(r):t.malformedSearchBlockedWithoutPrompt=!0}function mA(e,t){return{type:"session_resumed_cold",id:Mt(e,"rescold",t),...typeof e?.reason=="string"?{reason:e.reason}:{},...typeof e?.lostSnapshotImageId=="string"?{lostSnapshotImageId:e.lostSnapshotImageId}:e?.lostSnapshotImageId===null?{lostSnapshotImageId:null}:{},...V(e)?{promptId:V(e)}:{}}}function fA(e,t){let r=typeof e?.partType=="string"?e.partType:void 0,o=typeof e?.eventType=="string"?e.eventType:void 0;return r==="text"||o&&UT.has(o)?null:{type:"raw_agent_runtime",id:Mt(e,"raw",t),...V(e)?{promptId:V(e)}:{},...r?{partType:r}:{},...o?{eventType:o}:{},data:e??{}}}function gA(e,t){let r=Array.isArray(e?.files)?e.files.filter(o=>typeof o=="string"):[];return r.length===0?null:{type:"patch",id:`patch-${t}`,files:r,...V(e)?{promptId:V(e)}:{}}}function $y(e,t,r,o){WT(r.merged,r.streams,e,Mt(t,e,r.merged.length),VT(t),V(t),o)}function hA(e,t){let r=Mt(e,"tool",t.merged.length),o=t.toolCallIndexById.get(r);if(o!==void 0){let n=t.merged[o];if(n.type==="tool_call"){let i=Up(e?.toolStatus),a=z(e?.input)?e.input:void 0,s={type:"tool_call",id:r,...typeof e?.tool=="string"?{tool:e.tool}:typeof e?.toolName=="string"?{tool:e.toolName}:{},...typeof e?.summary=="string"&&e.summary.length>0?{summary:e.summary}:{},...V(e)?{promptId:V(e)}:{},...a&&Object.keys(a).length>0?{input:a}:{},...i?{toolStatus:i}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...z(e?.failure)?{failure:e.failure}:{}};t.merged[o]=HT(n,s)}}else{let n=Up(e?.toolStatus),i={type:"tool_call",id:r,tool:typeof e?.tool=="string"?e.tool:typeof e?.toolName=="string"?e.toolName:"unknown",summary:typeof e?.summary=="string"?e.summary:"",...V(e)?{promptId:V(e)}:{},...z(e?.input)?{input:e.input}:{},...n?{toolStatus:n}:{},...typeof e?.truncated=="boolean"?{truncated:e.truncated}:{},...typeof e?.inputEstimatedTokens=="number"?{inputEstimatedTokens:e.inputEstimatedTokens}:{},...typeof e?.outputEstimatedTokens=="number"?{outputEstimatedTokens:e.outputEstimatedTokens}:{},...typeof e?.outputChars=="number"?{outputChars:e.outputChars}:{},...z(e?.failure)?{failure:e.failure}:{}};t.toolCallIndexById.set(r,t.merged.length),t.merged.push(i)}}function vA(e,t){let r=typeof e?.id=="string"?e.id:"",o=t.toolCallIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n.type==="tool_call"&&(t.merged[o]=KT(n,e))}function _A(e,t){let r={type:"question",id:Mt(e,"question",t.merged.length),question:typeof e?.question=="string"?e.question:"",answer:e?.answer==null?null:String(e.answer),...V(e)?{promptId:V(e)}:{},...Array.isArray(e?.options)?{options:e.options}:{}};t.questionIndexById.set(r.id,t.merged.length),t.merged.push(r)}function yA(e,t){let r=typeof e?.id=="string"?e.id:void 0;if(!r)return;let o=t.questionIndexById.get(r);if(o===void 0)return;let n=t.merged[o];n?.type==="question"&&(t.merged[o]={...n,answer:e?.answer==null?null:String(e.answer)})}function bA(e,t){let r=Array.isArray(e?.todos)?e.todos:[];if(r.length!==0)for(let o=t.merged.length-1;o>=0;o--){let n=t.merged[o];if(n.type==="tool_call"&&n.tool.toLowerCase()==="todowrite"){t.merged[o]={...n,input:{...n.input,todos:r}};break}}}function wA(e,t){let r=yy(e);if(!r)return;let o=V(e);t.merged.push({type:"onboarding_status",id:`onboarding_status:${t.merged.length}`,stage:r.stage,status:r.status,...r.detail?{detail:r.detail}:{},...o?{promptId:o}:{}})}function SA(e,t){let r=typeof e?.text=="string"?e.text.trim():"";if(!r)return;let o=V(e),n={type:"narration",id:"narration",text:r,...o?{promptId:o}:{}};t.narrationIndex===null?(t.narrationIndex=t.merged.length,t.merged.push(n)):t.merged[t.narrationIndex]=n}function Ay(e){let t=JT();for(let r of e){let o=Ty(r),{type:n}=o,i=o.data;switch(n){case"sandbox_compaction_start":Oe(t,eA(i,t.merged.length));break;case"sandbox_compaction_complete":Oe(t,tA(i,t.merged.length));break;case"sandbox_context_fill_warning":Oe(t,nA(i,t.merged.length));break;case"sandbox_tool_truncated":Oe(t,rA(i,t.merged.length));break;case"retry_status":Oe(t,iA(i,t.merged.length));break;case"prompt_retrying":Oe(t,aA(i,t.merged.length));break;case"zeus_telemetry":Oe(t,sA(i,t.merged.length));break;case"agent_timeline":Oe(t,uA(i,t.merged.length));break;case"prompt_activity":break;case"agent_progress":lA(i,t);break;case"session_error":pA(i,t),Oe(t,dA(i,t.merged.length));break;case"session_resumed_cold":Oe(t,mA(i,t.merged.length));break;case"raw_agent_runtime":Oe(t,fA(i,t.merged.length));break;case"reasoning":$y("reasoning",i,t,jT(o.raw));break;case"text":$y("text",i,t);break;case"patch":Oe(t,gA(i,t.merged.length));break;case"todo_update":bA(i,t);break;case"answer":yA(i,t);break;case"tool_call":hA(i,t);break;case"tool_update":vA(i,t);break;case"question":_A(i,t);break;case"narration":SA(i,t);break;case"onboarding_status":wA(i,t);break}}return QT(t)}function Ry(e,t){let r=new Set(t),o=new Map(t.map(i=>[i,[]])),n=null;for(let i of e){let a=Hr(i),s=typeof a=="string"&&r.has(a)?a:null;Pn(i)==="prompt_processing"&&(n=s);let u=s??n;if(u){let c=o.get(u);c&&c.push(i)}}return o}function $A(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="prompt_completed"&&r.type!=="prompt_failed")continue;let o=r.data?.history;return!Array.isArray(o)||o.length===0?null:o}return null}function xy(e){let t=e.data;return[e.promptId??"",typeof t?.phase=="string"?t.phase:"",typeof t?.detail=="string"?t.detail:""].join("\0")}function Ey(e){let t=e.data;return[e.promptId??"",typeof t?.step=="string"?t.step:""].join("\0")}function Py(e){let t=wy(e),r=$A(t),o=t.filter(b=>b.type==="prompt_activity"),n=t.filter(b=>b.type==="agent_progress");if(!r)return{events:e,diagnostics:{embeddedHistoryPresent:!1,durablePromptActivityCount:o.length,embeddedPromptActivityCount:0,mergedDurablePromptActivityCount:0,duplicateDurablePromptActivityCount:0,durableAgentProgressCount:n.length,embeddedAgentProgressCount:0,mergedDurableAgentProgressCount:0,duplicateDurableAgentProgressCount:0}};let i=wy(r),a=i.filter(b=>b.type==="prompt_activity"),s=i.filter(b=>b.type==="agent_progress"),u=new Set(a.map(xy)),c=new Set(s.map(Ey)),l=a.length,d=s.length,m=0,p=0,g=o.filter(b=>{let x=xy(b);return u.has(x)?(m+=1,!1):(u.add(x),!0)}),_=n.filter(b=>{let x=Ey(b);return c.has(x)?(p+=1,!1):(c.add(x),!0)}),E=[...g,..._].map(b=>b.raw);return{events:E.length>0?[...E,...r]:r,diagnostics:{embeddedHistoryPresent:!0,durablePromptActivityCount:o.length,embeddedPromptActivityCount:l,mergedDurablePromptActivityCount:g.length,duplicateDurablePromptActivityCount:m,durableAgentProgressCount:n.length,embeddedAgentProgressCount:d,mergedDurableAgentProgressCount:_.length,duplicateDurableAgentProgressCount:p}}}var Cy=1e3;async function Oy(e,t,r,o){let n=[],i=r,a=null,s=0;do{if(s+=1,t&&s>Cy)throw new y("user",`${e} exceeded ${Cy} pages without reaching the end.`);let u=await o(i);n.push(...u.items),a=u.nextCursor,i=a??void 0}while(t&&a);return{items:n,nextCursor:t?null:a}}import{createParser as LA}from"eventsource-parser";function xa(e){return typeof e=="object"&&e!==null&&"noChanges"in e&&e.noChanges===!0}function Ny(e){for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return e[t].result;return null}function Ea(e){switch(e){case"no_diff":return{state:"no_changes",tone:"info",title:"Completed without code changes.",detail:null};case"no_staged_files":return{state:"no_changes",tone:"info",title:"Completed without publishable code changes.",detail:null};case"prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed before changes could be prepared.",detail:null};case"post_prep_failed":return{state:"no_change_abnormal",tone:"error",title:"Finalization failed after changes were prepared.",detail:null};default:return{state:"no_change_abnormal",tone:"error",title:"Completed without code changes, but finalization did not report a clean no-op reason.",detail:null}}}var xA="## Previously declined findings on this repository (calibration)",EA="## Findings already reported by other reviewers",IA="## Graphite stack neighbours",Dy=[xA,EA,IA,"## Independent review suggestions"];var zy=/\r?\n/,kA=/\n{3,}/g,TA=/<(user_content|instruction_content)\b[^>]*>[\s\S]*?<\/\1>/gi,AA=[/^IMPORTANT: The content above is /i,/^Previous Slack message\b/i,/^Current Slack message author:/i,/^Current Slack channel:/i,/^Thread context(?:\s*\([^)]*\))?\s*[.:]/i,/^Repository:\s+\S+$/i,/^Issue (?:title|body|description|metadata)\s*:/i,/^Triggering comment\s*:/i,/^Review body\s*:/i,/^Recent comments\s*:/i,/^<\/?(?:user_content|instruction_content)\b/i],RA=[/<\/?(?:user_content|instruction_content)\b/i,/^IMPORTANT: The content above is /im,/^Previous Slack message\b/im,/^Current Slack message author:/im,/^Current Slack channel:/im,/^Repository:\s+\S+$/im],PA=/^Review pull request \S+ at (?:its current head|admitted head \S+ against admitted base \S+)\./;function CA(e){let t=e.split(zy),r=[],o=[];if(t.forEach((a,s)=>{let u=Dy.findIndex(c=>a.trim()===c);u!==-1&&(r.push(u),o.push(s))}),o.length===0||!r.every((a,s)=>s===0||a>(r[s-1]??-1)))return e.trim();let i=o[0]??0;return t.slice(0,i).join(`
|
|
87
87
|
`).trim()}function Uy(e){return RA.some(t=>t.test(e))}function OA(e){return e.replace(TA,"").split(zy).filter(o=>!AA.some(n=>n.test(o.trim()))).join(`
|
|
88
88
|
`).replace(kA,`
|
|
89
89
|
|