progon-agent 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/supervisor/cli.js +44 -44
  2. package/extension-bundle.json +3 -3
  3. package/extension-dist/background/background.js +88 -89
  4. package/extension-dist/card/card.css +1 -1
  5. package/extension-dist/card/card.html +8 -9
  6. package/extension-dist/card/card.js +3 -9
  7. package/extension-dist/chunks/shared-73iHxv_g.js +1 -0
  8. package/extension-dist/chunks/shared-BRaGK72I.css +1 -0
  9. package/extension-dist/chunks/shared-Beih6ywL.js +1 -0
  10. package/extension-dist/chunks/shared-BgEO6Nif.js +39 -0
  11. package/extension-dist/chunks/shared-ByZxg79I.js +1 -0
  12. package/extension-dist/chunks/shared-C7IWMwZY.js +1 -0
  13. package/extension-dist/chunks/shared-CFEBqIm7.js +21 -0
  14. package/extension-dist/chunks/shared-CKtbh_44.js +199 -0
  15. package/extension-dist/chunks/shared-CSBwVLDL.js +1 -0
  16. package/extension-dist/chunks/shared-CeI71eLt.js +134 -0
  17. package/extension-dist/chunks/shared-CfjrOLG1.js +336 -0
  18. package/extension-dist/chunks/shared-CgUMEof2.js +1 -0
  19. package/extension-dist/chunks/{shared-BgsXTfSV.js → shared-CwsTFlbT.js} +1 -1
  20. package/extension-dist/chunks/shared-D-c-eSoI.js +1 -0
  21. package/extension-dist/chunks/shared-DXp1f_Ub.css +1 -0
  22. package/extension-dist/chunks/shared-RcZD4SR-.js +1 -0
  23. package/extension-dist/chunks/shared-lM00HeT6.js +98 -0
  24. package/extension-dist/chunks/shared-t8TH2XkL.js +239 -0
  25. package/extension-dist/content/content.css +1 -1
  26. package/extension-dist/content/content.js +216 -231
  27. package/extension-dist/manifest.json +29 -30
  28. package/extension-dist/offscreen/offscreen.html +2 -3
  29. package/extension-dist/offscreen/offscreen.js +1 -1
  30. package/extension-dist/popup/popup.html +8 -8
  31. package/extension-dist/popup/popup.js +3 -3
  32. package/extension-dist/sidepanel/sidepanel.html +11 -10
  33. package/extension-dist/sidepanel/sidepanel.js +1 -1
  34. package/extension-dist/workspace/workspace.html +11 -11
  35. package/extension-dist/workspace/workspace.js +46 -83
  36. package/package.json +2 -2
  37. package/extension-dist/chunks/shared-B4EisBUi.js +0 -1
  38. package/extension-dist/chunks/shared-B7QwPadt.js +0 -98
  39. package/extension-dist/chunks/shared-BEB011Tg.js +0 -1
  40. package/extension-dist/chunks/shared-BQF2LG1p.js +0 -377
  41. package/extension-dist/chunks/shared-BpcMA-xb.js +0 -135
  42. package/extension-dist/chunks/shared-BvwA-cm2.css +0 -1
  43. package/extension-dist/chunks/shared-BwS34Mep.js +0 -111
  44. package/extension-dist/chunks/shared-CAKh7jnb.css +0 -1
  45. package/extension-dist/chunks/shared-CCOKrUJ3.js +0 -1
  46. package/extension-dist/chunks/shared-COCbj3mN.js +0 -1
  47. package/extension-dist/chunks/shared-Co5HfH-n.js +0 -1
  48. package/extension-dist/chunks/shared-Cs6uBr12.js +0 -1
  49. package/extension-dist/chunks/shared-D7SUgUlB.js +0 -1
  50. package/extension-dist/chunks/shared-DGDE0AeD.js +0 -1
  51. package/extension-dist/chunks/shared-DjlOTYdL.js +0 -1
  52. package/extension-dist/chunks/shared-LK5ScAJA.js +0 -227
  53. package/extension-dist/chunks/shared-_8sSdh22.js +0 -21
  54. package/extension-dist/chunks/shared-sY-POWsC.js +0 -51
@@ -1,54 +1,54 @@
1
1
  #!/usr/bin/env node
2
- var Xo=Object.defineProperty;var i=(t,e)=>Xo(t,"name",{value:e,configurable:!0});import{realpathSync as gd}from"node:fs";import{pathToFileURL as wd}from"node:url";import{z as hn}from"zod";var zo=/^[a-z_]{1,32}@\d{1,3}$/,fn=hn.array(hn.string().regex(zo)).min(1).max(32),gn=["playback@1"],wn="make_auto@2",yn="atlas_crawl@2",_n="atlas_crawl@1",En="swarm@1",Sn="swarm@2",Rn="scenario_launch@1";import{z as h}from"zod";var ie=/^pgat_[0-9A-Za-z]{43}$/;var Ie="agent:command",Fe="agent:command-ack",Ct="agent:active-job";import{z as l}from"zod";import{z as _}from"zod";import{z as u}from"zod";var Zo=["running","pausing","paused","stopping","finalizing","completed","cancelled","failed"],bn=u.enum(Zo),kn=["completed","cancelled","failed"],Pd=u.enum(kn),Qo=["running","pausing","paused","stopping","finalizing"],Cd=u.enum(Qo),ei=["running","pausing","stopping"],Dd=u.enum(ei),ti=["paused",...kn],Ld=u.enum(ti),ni=["user","credits"],Gd=u.enum(ni),ri=["exploring","final_analysis","done"],Ud=u.enum(ri),oi=["queued","running","done","failed","cancelled"],Md=u.enum(oi),ii=["done","failed","cancelled"],$d=u.enum(ii),ai=["lead_finished","user_cancelled","lead_failed"],Fd=u.enum(ai);var si=["none","attached","lost"],jd=u.enum(si),li=["idle","active","awaiting_user"],Wd=u.enum(li),di=["atlas","make_auto","preset"],Bd=u.enum(di),ci=["extension_atlas_card","extension_make_auto_modal","web_atlas_dialog","web_make_auto_dialog","web_job_repeat","chat","web_workflow_repeat","web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog"],Kd=u.enum(ci),ui=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog"],mi=u.enum(ui),qd=u.union([mi,u.literal("chat")]),pi=["extension_atlas_card","extension_make_auto_modal","web_make_auto_dialog","web_job_repeat","web_workflow_repeat"],Vd=u.enum(pi),hi=["browser","agent","none"],fi=u.enum(hi),gi=["browser","agent"],Hd=u.enum(gi),wi=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],Jd=u.enum(wi),yi=["file_bugs","write_tests","edit_project"],Yd=u.enum(yi),_i=["text","auto"],Xd=u.enum(_i),Ei=["project","scenarios","test_run","test_plan"],zd=u.enum(Ei),Si=["server","chat"],Zd=u.enum(Si),Ri=["host_lost","awaiting_browser","awaiting_user","paused"],Qd=u.enum(Ri),bi=["window","mcp_agent"],ec=u.enum(bi),ki=["opening","idle","busy","closing","closed"],tc=u.enum(ki),Ti=["lead","user","window_closed","workflow_ended","workflow_paused"],nc=u.enum(Ti),vi=["lead","user","workflow_ended","no_connection","left"],rc=u.enum(vi),Ai=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left"],oc=u.enum(Ai),xi=["make_auto","atlas","run"],ic=u.enum(xi),Ii=["starting","running","ended"],ac=u.enum(Ii),Oi=["completed","cancelled","failed","start_failed"],sc=u.enum(Oi),Ni=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],lc=u.enum(Ni),Pi=["lead_choice","role_default"],dc=u.enum(Pi),Ci=["observe","main","dangerous"],cc=u.enum(Ci),Di=["main","dangerous"],Tn=u.enum(Di);var Li=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion"],uc=u.enum(Li),Gi=["workflows.not_found","workflows.not_initiator","workflows.not_initiator_or_admin","workflows.worker_not_found","workflows.not_running","workflows.host_held","workflows.host_mismatch","workflows.host_lost","workflows.host_attached","workflows.host_pending","workflows.executor_kind_mismatch","workflows.executor_mismatch","workflows.agent_mismatch","workflows.request_mismatch","workflows.agents_over_max","workflows.scope_not_found","workflows.scope_forbidden","workflows.conversation_busy","workflows.max_requires_browser","workflows.not_preset","workflows.not_pausable","workflows.not_continuable","workflows.not_amendable","workflows.place_mismatch","workflows.auto_requires_browser","workflows.segment_changed","workflows.mcp_join_unavailable","workflows.mcp_code_invalid","workflows.mcp_code_used","workflows.mcp_agent_not_found","workflows.mcp_agent_disconnected","workflows.mcp_inbox_invalid_cursor","workflows.question_not_to_lead","workflows.device_handoff_not_found","workflows.device_step_already_reported","workflows.device_run_ended"],mc=u.enum(Gi),pc=u.object({status:bn}),Ui=u.object({status:bn}),Mi=["conversation_deleted"],$i=u.enum(Mi),hc=Ui.extend({reason:$i.optional()}),fc=u.object({segment:u.number().int().min(1)}),gc=u.object({executorKind:fi}),wc=u.object({reason:u.enum(["ended","no_browser"])}),yc=u.object({reason:u.literal("task_paused")}),_c=u.object({stepNumber:u.number().int().min(1),currentStepNumber:u.number().int().min(1).nullable()}),Ec=u.object({leaseExpiresAt:u.iso.datetime()}),Sc=u.object({workflowId:u.uuid()}),Rc=u.object({agentId:u.uuid()});var vn=_.object({queueId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),applicationId:_.uuid().nullable(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),An=_.object({launchId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),je=_.object({projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),standMode:Tn,accountLabel:_.string().min(1),role:_.string().min(1),locale:_.string().min(1),viewportWidth:_.number().int().min(1),viewportHeight:_.number().int().min(1)}).strict(),Dt=_.object({...je.shape,environmentId:_.uuid().nullable()}).strict(),vc=_.union([je,Dt]),Ac=_.object({workflowId:_.uuid(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict();import{z as se}from"zod";import{z as ae}from"zod";var xn=["passed","failed","infra","cancelled","abandoned"];var Fi=["queued","launching","in_progress"];var In=["passed","failed"],ji=["before_hook_failed","no_start_page","no_path_for_page"],Wi=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Lt=[...ji,...Wi],Cc=ae.enum(Lt).exclude(["before_hook_failed"]);var Dc=[...xn,...Fi];var Lc=ae.object({by:ae.literal("human"),outcome:ae.enum(In)}).strict(),Gc=ae.object({outcome:ae.enum(In)}).strict();var Bi=["queued","launching","in_progress","completed","failed","cancelled"],jc=se.enum(Bi);var Ki=["queued","launching","in_progress"],On=se.enum(Ki);var qi=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Lt,"result_not_saved","mcp_agent_disconnected"],Wc=se.enum(qi),Vi=["launch_error","browser_gone","max_duration"],Gt=se.enum(Vi),Hi=["name_not_resolved","unreachable","certificate","timeout","other"],Nn=se.enum(Hi);var Ji=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","stalled","capability_mismatch","subject_rejected","model_timeout","runs_not_started","credits_exhausted","tab_closed","slot_taken","ai_disabled","workflow_host_lost"],Yi=se.enum(Ji),Xi=["workflow_host_lost"],Bc=Yi.exclude(Xi);var zi=l.enum(["darwin","linux","win32"]),Zi=l.enum(["x64","arm64"]),Cn=l.enum(["official","debug"]),Xc=l.object({enrollmentCode:l.string().min(32),hostname:l.string().min(1).max(255),platform:zi,arch:Zi,agentVersion:l.string().min(1).max(30),protocolVersion:l.number().int().min(1)}).strict(),We=l.object({agentId:l.uuid(),agentToken:l.string().regex(ie),pollWaitSec:l.number().int().min(1).max(25),protocolVersion:l.literal(1)}).strict(),zc=l.object({waitSec:l.coerce.number().int().min(0).max(25).optional()}).strict(),Dn=l.object({agent:l.object({revoked:l.boolean()}).strict(),run:l.union([l.null(),l.object({runId:l.uuid(),phase:On}).strict()])}).strict(),Ut=l.object({v:l.literal(1),kind:l.literal("playback"),runId:l.uuid(),scenarioId:l.uuid(),projectId:l.uuid(),projectDomain:l.string().min(1),applicationId:l.uuid().nullable(),environmentId:l.uuid().nullable(),executionMode:l.literal("auto"),issuedAt:l.iso.datetime()}).strict(),Mt=l.object({v:l.literal(1),kind:l.literal("make_auto"),runId:l.uuid(),issuedAt:l.iso.datetime(),...vn.shape}).strict(),Qi=l.object({v:l.literal(1),kind:l.literal("atlas_crawl"),runId:l.uuid(),issuedAt:l.iso.datetime(),...je.shape}).strict(),ea=l.object({v:l.literal(1),kind:l.literal("atlas_crawl"),runId:l.uuid(),issuedAt:l.iso.datetime(),...Dt.shape}).strict(),$t=l.union([ea,Qi]),Ft=l.object({v:l.literal(1),kind:l.literal("scenario_launch"),runId:l.uuid(),issuedAt:l.iso.datetime(),...An.shape}).strict(),jt=l.object({v:l.literal(1),kind:l.literal("swarm"),runId:l.uuid(),issuedAt:l.iso.datetime(),workflowId:l.uuid()}).strict(),Zc=l.union([Ut,Mt,$t,jt,Ft]),ta={playback:!0,make_auto:!0,atlas_crawl:!0,swarm:!0,scenario_launch:!0},Qc=Object.keys(ta),eu=l.object({agentJobId:l.uuid(),updatedAt:l.iso.datetime()}).strict(),na=l.enum(["invalid_envelope","dispatch_failed"]),Ln=l.discriminatedUnion("outcome",[l.object({runId:l.uuid(),outcome:l.literal("dispatched")}).strict(),l.object({runId:l.uuid(),outcome:l.literal("rejected"),reason:na}).strict()]),Gn=l.object({cancelRequested:l.boolean(),killRequested:l.boolean()}).strict(),ra=2147483646,oa=l.object({stepId:l.uuid(),stepIndex:l.number().int().min(0).max(ra),status:l.enum(["passed","failed","skipped"]),failureCode:l.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:l.string().max(4e3).nullable(),startedAt:l.iso.datetime().nullable(),completedAt:l.iso.datetime().nullable()}).strict(),tu=l.object({events:l.array(oa).min(1).max(50)}).strict(),nu=l.object({updated:l.number().int().min(0),control:Gn}).strict(),ru=l.object({phase:l.enum(["running","paused"])}).strict(),ou=l.object({control:Gn}).strict(),Pn=l.string().max(500).optional(),iu=l.discriminatedUnion("reason",[l.object({reason:l.literal(Gt.enum.launch_error),message:Pn,entryFailure:Nn.optional()}).strict(),l.object({reason:Gt.exclude(["launch_error"]),message:Pn}).strict()]),Un=l.object({status:l.enum(["failed","already_terminal"])}).strict();var uu=h.union([h.object({}).strict(),h.object({capabilities:fn}).strict()]);function Oe(t){let{value:e}=t;e.command.runId!==e.runId&&t.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}i(Oe,"checkClaimRunIdAgreement");function ia(t){let{value:e}=t;e.command.projectId!==e.projectId&&t.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}i(ia,"checkPlaybackClaimProjectAgreement");var aa=h.object({runId:h.uuid(),scenarioId:h.uuid(),projectId:h.uuid(),applicationId:h.uuid().nullable(),projectDomain:h.string().min(1),entryUrl:h.url({protocol:/^https?$/}),environmentId:h.uuid().nullable(),runPurpose:Cn,headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(3600),extensionSession:h.object({accessToken:h.string().min(1),refreshToken:h.string().min(1)}).strict(),command:Ut}).strict().check(Oe).check(ia),Ke=h.object({accessToken:h.string().min(1),refreshToken:h.string().min(1)}).strict(),sa=h.object({kind:h.literal("make_auto"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ke,command:Mt}).strict().check(Oe),la=h.object({kind:h.literal("atlas_crawl"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ke,command:$t}).strict().check(Oe),da=h.object({kind:h.literal("swarm"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ke,command:jt}).strict().check(Oe),ca=h.object({kind:h.literal("scenario_launch"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ke,command:Ft}).strict().check(Oe),Mn=h.union([aa,sa,la,da,ca]);import{z as $n}from"zod";var ua=["finished","cancelled","ai_disabled"],ma=$n.enum(ua),fu=$n.object({outcome:ma}).strict();import{spawn as Sa}from"node:child_process";import{existsSync as Ra}from"node:fs";import{createRequire as ba}from"node:module";import{dirname as Wn,join as ka}from"node:path";import ya from"pino";var pa=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),ha=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,fa=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,ga=["token","secret","password","authorization","api_key","api-key","apikey"],wa=new RegExp(`([?&](?:${ga.join("|")})=)([^&\\s]+)`,"gi"),qe="[REDACTED]";function Fn(t){let e=t.replace(fa,qe);return e=e.replace(ha,qe),e=e.replace(wa,`$1${qe}`),e}i(Fn,"redactValueString");function z(t){if(Array.isArray(t))return t.map(z);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))pa.has(r.toLowerCase())?n[r]=qe:n[r]=z(e[r]);return n}return typeof t=="string"?Fn(t):t}i(z,"redactSecrets");function M(t){return Fn(t)}i(M,"redactSensitiveText");function _a(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&new Set(["trace","debug","info","warn","error","fatal","silent"]).has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}i(_a,"resolveLogLevel");function Ea(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(Ea,"buildTransport");var jn=ya({name:"qa-runner",level:_a(),transport:Ea(),base:{pid:process.pid},redact:{paths:["token","agentToken","accessToken","refreshToken","pgrtToken","jobToken","authorization","secret","password","resolvedVariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key","*.token","*.agentToken","*.accessToken","*.refreshToken","*.secret","*.password","*.authorization","*.cookie","*.set-cookie","*.x-api-key","*.proxy-authorization","*.api-key"],censor:"[REDACTED]"}});function Wt(t){return{debug(e,n){n!==void 0?t.debug(z(n),e):t.debug(e)},info(e,n){n!==void 0?t.info(z(n),e):t.info(e)},warn(e,n){n!==void 0?t.warn(z(n),e):t.warn(e)},error(e,n){n!==void 0?t.error(z(n),e):t.error(e)},child(e){return Wt(t.child(e))}}}i(Wt,"adaptPino");function m(t){return Wt(jn.child({module:t}))}i(m,"createLogger");var Iu=Wt(jn);var Bt=m("browser-provision"),Ta=60*6e4,K=class extends Error{static{i(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,n={}){super(e,{cause:n.cause}),this.name="BrowserProvisionError",this.exitCode=n.exitCode===void 0?null:n.exitCode,this.timedOut=n.timedOut===void 0?!1:n.timedOut}},Bn=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
3
- `);function va(){let t=ba(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new K(`[browser-provision] Cannot locate the 'playwright-core' package from ${import.meta.url}. It is a declared dependency of this agent \u2014 reinstall the package ('npm ci') rather than installing a browser by hand: the agent launches the revision THIS copy of playwright-core expects.`,{cause:r})}let n=ka(Wn(e),"cli.js");if(!Ra(n))throw new K(`[browser-provision] 'playwright-core' resolved to ${Wn(e)} but its CLI is not at ${n}. That installation is incomplete or has been altered \u2014 reinstall it ('npm ci'). This agent installs Chromium through that CLI and through no other path (CONTRACT-la \xA715 A31.1).`);return{execPath:process.execPath,cliPath:n,args:["install","chromium","--no-shell"]}}i(va,"resolveInstallCommand");async function Ve(t){let e=t.commandOverride===void 0?va():t.commandOverride,n=t.deadlineMs===void 0?Ta:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],o=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,a=Date.now();Bt.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let s=Sa(e.execPath,[e.cliPath,...r],{env:process.env,stdio:t.stdio==="inherit"?"inherit":["ignore","pipe","pipe"]});if(t.stdio==="pipe"){let{stdout:w,stderr:f}=s;if(w===null||f===null)throw new K(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${o}).`);Kn(w,"stdout"),Kn(f,"stderr")}let d=!1,c=setTimeout(()=>{d=!0,s.kill("SIGKILL")},n),g=new Map,y=i(()=>{for(let[w,f]of g)process.off(w,f);g.clear()},"removeSignalHandlers");for(let w of["SIGTERM","SIGINT"]){let f=i(()=>{s.kill("SIGKILL"),y(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:w,installerPid:s.pid})+`
4
- `),process.kill(process.pid,w)},"handler");g.set(w,f),process.on(w,f)}try{await new Promise((w,f)=>{s.once("error",R=>{f(new K(`[browser-provision] Could not start the Playwright installer (${o}): ${R.message}`,{cause:R}))}),s.once("close",(R,v)=>{if(d){f(new K(`[browser-provision] Chromium installation did not finish within ${n}ms and was killed (${o}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
5
- ${Bn}`,{exitCode:R,timedOut:!0}));return}if(R===0){w();return}let $e=R===null?`was terminated by signal ${String(v)}`:`exited with code ${R}`;f(new K(`[browser-provision] Chromium could not be installed: the Playwright installer ${$e} (${o}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
6
- ${Bn}`,{exitCode:R}))})})}finally{clearTimeout(c),y()}Bt.info("Chromium is provisioned",{durationMs:Date.now()-a})}i(Ve,"provisionBrowser");function Kn(t,e){let n="";t.setEncoding("utf8"),t.on("data",r=>{n+=r;let o=n.lastIndexOf(`
7
- `);if(o===-1)return;let a=n.slice(0,o);n=n.slice(o+1);for(let s of a.split(`
8
- `))qn(s,e)}),t.on("end",()=>{let r=n;n="",qn(r,e)})}i(Kn,"forwardLinesToLogger");function qn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Bt.info("Chromium provisioning output",{stream:e,line:n})}i(qn,"logLine");import{homedir as ps}from"node:os";import{isAbsolute as fr,join as Qe}from"node:path";var p=class extends Error{static{i(this,"OperatorRefusalError")}};var Aa=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Z(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Aa.has(e.hostname)))throw new p(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new p("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");if(e.search!==""||e.hash!=="")throw new p(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix). See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(Z,"validateServerUrl");function Ne(t){if(!ie.test(t))throw new p("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}i(Ne,"validateRunnerToken");function Kt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new p(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}i(Kt,"validateRunnerMachineId");function qt(t){if(t!==1)throw new p(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}i(qt,"validateProtocolVersion");import{Agent as xa,EnvHttpProxyAgent as Ia}from"undici";var Vn=m("gateway-proxy"),Oa=["http_proxy","HTTP_PROXY"],Na=["https_proxy","HTTPS_PROXY"],Pa=["no_proxy","NO_PROXY"];function Ca(t){return t.http!==void 0||t.https!==void 0}i(Ca,"gatewayIsProxied");var Da=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,La=/:\d+$/,Ga=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function Ua(t){let e=Ga.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}i(Ua,"withoutProxyCredentials");function de(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(Ua(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${t} to connect to the server directly. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(de,"refuseProxyValue");function Hn(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}i(Hn,"readProxyVariable");function Ma(t){for(let e of Pa){let n=t[e];if(n!==void 0)return n}}i(Ma,"readNoProxy");function Jn(t,e){if(Da.test(e)){let s;try{s=new URL(e)}catch{throw de(t,e,"it carries a scheme but is not a URL that parses")}if(s.protocol!=="http:"&&s.protocol!=="https:")throw de(t,e,`its scheme is ${JSON.stringify(s.protocol)}, not http: or https:`);if(s.hostname==="")throw de(t,e,"it names no host");return{variable:t,url:e,schemeCompleted:!1}}let n=e.search(/[/?#]/),r=n===-1?e:e.slice(0,n);if(!La.test(r))throw de(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let o=`http://${e}`,a;try{a=new URL(o)}catch{throw de(t,e,'it is neither a URL nor a "host:port" pair')}if(a.hostname==="")throw de(t,e,"it names no host");return{variable:t,url:o,schemeCompleted:!0}}i(Jn,"parseProxyValue");function Vt(t){let e=Hn(t,Oa),n=Hn(t,Na);return{http:e===void 0?void 0:Jn(e.variable,e.raw),https:n===void 0?void 0:Jn(n.variable,n.raw),noProxy:Ma(t)}}i(Vt,"resolveGatewayProxyConfig");function Yn(t,e,n){if(!Ca(t))return new xa(e);Vn.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let a of[t.http,t.https])a!==void 0&&a.schemeCompleted&&r.push(a.variable);r.length>0&&Vn.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let o={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new Ia(o)}i(Yn,"createProxyAwareDispatcher");function Xn(t){Vt(t)}i(Xn,"validateGatewayProxyEnv");import{readFileSync as $a,statSync as Fa}from"node:fs";import{isAbsolute as ja}from"node:path";import{rootCertificates as zn}from"node:tls";var Wa=m("gateway-tls-trust"),Je="PROGON_AGENT_EXTRA_CA_CERTS";function He(t,e,n){let r=`[config] ${Je} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(t)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Je} to trust only the public roots.`;return n===void 0?new Error(r):new Error(r,{cause:n})}i(He,"refuseExtraCaValue");function Zn(t){let e=t[Je];if(e===void 0||e==="")return;if(!ja(e))throw He(e,"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in");let n;try{n=Fa(e)}catch(o){throw He(e,"it cannot be read",o)}if(!n.isFile())throw He(e,"it is not a file");let r;try{r=$a(e,"utf8")}catch(o){throw He(e,"its contents could not be read",o)}return{variable:Je,path:e,pem:r}}i(Zn,"resolveExtraCaTrust");function Qn(t){let e=Zn(t);if(e!==void 0)return Wa.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:zn.length}),[...zn,e.pem]}i(Qn,"readTrustedCaBundle");function er(t){Zn(t)}i(er,"validateExtraCaTrustEnv");import{readFileSync as Ha}from"node:fs";import{dirname as Ja,join as Ya}from"node:path";import{fileURLToPath as Xa}from"node:url";function Q(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}i(Q,"isAbsentPathError");import{statSync as Ba}from"node:fs";import{dirname as Ka,join as qa}from"node:path";var tr="package.json";function Ye(t){let e=t;for(;;){if(Va(e))return e;let n=Ka(e);if(n===e)throw new Error(`[package-root] No ${tr} was found in ${t} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=n}}i(Ye,"findPackageRoot");function Va(t){try{return Ba(qa(t,tr)),!0}catch(e){if(Q(e))return!1;throw e}}i(Va,"holdsPackageManifest");var za="extension-bundle.json";function Ht(){return Za(Ya(Ye(Ja(Xa(import.meta.url))),za))}i(Ht,"readBundledAppUrl");function Za(t){let e;try{e=Ha(t,"utf-8")}catch(o){if(Q(o))return null;throw new p(`[extension-bundle] ${t} exists but could not be read: ${String(o)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:o})}let n;try{n=JSON.parse(e)}catch(o){throw new p(`[extension-bundle] ${t} contains invalid JSON: ${String(o)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:o})}if(typeof n!="object"||n===null||Array.isArray(n)){let o=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[extension-bundle] ${t} must contain a JSON object, got: ${o}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=n.appUrl;if(typeof r!="string"||r==="")throw new p(`[extension-bundle] ${t} has no usable 'appUrl' (expected a non-empty string). That field is the deployment this package was built for; without it the agent cannot tell which Progon it belongs to. Reinstall the package (npm i -g progon-agent@latest), or name the deployment explicitly with --server / PROGON_SERVER_URL.`);try{Z(r)}catch(o){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(o)}`,{cause:o})}return r}i(Za,"readBundledAppUrlFrom");import{unlinkSync as us}from"node:fs";import{readFileSync as Qa,writeFileSync as es,renameSync as ts,mkdirSync as ns,existsSync as rs,chmodSync as os,fchmodSync as is,openSync as nr,fsyncSync as rr,closeSync as or,unlinkSync as as}from"node:fs";import{join as ir}from"node:path";var Xe=m("state-file");function ze(t){return ir(t,"runner-state.json")}i(ze,"stateFilePath");function Jt(t){return ir(t,"runner-state.json.tmp")}i(Jt,"stateTmpPath");function ar(t){let e=ze(t);if(!rs(e))return Xe.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=Qa(e,"utf-8")}catch(a){throw new p(`[state-file] Failed to read state file at ${e}: ${String(a)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let r;try{r=JSON.parse(n)}catch(a){throw new p(`[state-file] State file at ${e} contains invalid JSON: ${String(a)}. Remove the file and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let o=ds(r,e);return Xe.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(ar,"readState");function sr(t,e){ns(t,{recursive:!0,mode:448}),os(t,448);let n=ze(t),r=Jt(t),o=JSON.stringify(e,null,2);try{let a=nr(r,"w",384);try{is(a,384),es(a,o,{encoding:"utf-8"}),rr(a)}finally{or(a)}ts(r,n),ls(t)}catch(a){throw ss(r),new p(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}Xe.info("State file written",{agentId:e.agentId,filePath:n})}i(sr,"writeState");function ss(t){try{as(t)}catch(e){if(e.code==="ENOENT")return;Xe.error("Failed to remove the temporary state file \u2014 it may still hold the agent credential",{tmpPath:t,err:e instanceof Error?e.message:String(e)})}}i(ss,"removeStateTmp");function ls(t){let e=nr(t,"r");try{rr(e)}finally{or(e)}}i(ls,"fsyncDirectory");function ds(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let d=t===null?"null":Array.isArray(t)?"array":typeof t;throw new p(`[state-file] State file ${e} must contain a JSON object, got: ${d}`)}let n=t,r=n.agentId;if(typeof r!="string"||r==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);Kt(r);let o=n.agentToken;if(typeof o!="string"||o==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Ne(o);let a=n.protocolVersion;if(typeof a!="number"||!Number.isInteger(a))throw new p(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);qt(a);let s=n.serverUrl;if(typeof s!="string"||s==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{Z(s)}catch(d){throw new p(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(d)}`)}return{agentId:r,agentToken:o,protocolVersion:a,serverUrl:s,tokenRotatedAt:cs(n,e)}}i(ds,"validateState");function cs(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new p(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return n}i(cs,"readTokenRotatedAt");var lr=m("token-store");function $(t){return ar(t)}i($,"loadAgentIdentity");function ce(t,e){sr(t,e)}i(ce,"saveAgentIdentity");function cr(t){let e=ze(t),n=Jt(t),r=dr(n,"temporary state file"),o=dr(e,"identity");if(!o&&!r){lr.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}lr.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:o,removedTmp:r})}i(cr,"wipeAgentIdentity");function dr(t,e){try{return us(t),!0}catch(n){if(ms(n))return!1;throw new Error(`[token-store] Failed to wipe the agent ${e} at ${t}: ${String(n)}. The agent has been revoked (CONTRACT-la \xA715 A15.1) and its credential must not remain on disk \u2014 remove the file manually.`)}}i(dr,"removeCredentialFile");function ms(t){return t.code==="ENOENT"}i(ms,"isFileNotFound");var ur="extension-bundle.json";function Ze(t,e){return mr(t)===mr(e)}i(Ze,"isSameDeployment");function mr(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}i(mr,"normalizeDeployment");function pr(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return Z(e),{url:e,source:"env"};if(n){let s=Ht();if(s!==null)return{url:s,source:"bundle"};throw new p(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
9
- This build carries no ${ur} either, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
2
+ var ui=Object.defineProperty;var i=(n,e)=>ui(n,"name",{value:e,configurable:!0});import{realpathSync as Ld}from"node:fs";import{pathToFileURL as Gd}from"node:url";import{z as Tn}from"zod";var pi=/^[a-z_]{1,32}@\d{1,3}$/,In=Tn.array(Tn.string().regex(pi)).min(1).max(32),xn=["playback@1"],An="swarm@1",On="swarm@2",Nn="scenario_launch@1",Pn="browser_channel@1",Cn="task_launch@1";import{z as y}from"zod";var de=/^pgat_[0-9A-Za-z]{43}$/;var Ue="agent:command",He="agent:command-ack",Kt="agent:active-job";import{z as d}from"zod";import{z as _}from"zod";import{z as u}from"zod";var hi=["running","pausing","paused","stopping","finalizing","completed","cancelled","failed"],Dn=u.enum(hi),Ln=["completed","cancelled","failed"],zd=u.enum(Ln),mi=["running","pausing","paused","stopping","finalizing"],Zd=u.enum(mi),fi=["running","pausing","stopping"],Qd=u.enum(fi),gi=["paused",...Ln],ec=u.enum(gi),wi=["user","credits","user_credit_limit","provider_unavailable"],tc=u.enum(wi),yi=["exploring","final_analysis","done"],nc=u.enum(yi),_i=["queued","running","done","failed","cancelled"],rc=u.enum(_i),Ei=["done","failed","cancelled"],oc=u.enum(Ei),Si=["lead_finished","user_cancelled","lead_failed"],ic=u.enum(Si);var Ri=["none","attached","lost"],sc=u.enum(Ri),ki=["idle","active","awaiting_user"],ac=u.enum(ki),bi=["atlas","make_auto","preset"],lc=u.enum(bi),vi=["extension_atlas_card","extension_make_auto_modal","web_atlas_dialog","web_make_auto_dialog","web_job_repeat","chat","web_workflow_repeat","web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","web_launch_request"],dc=u.enum(vi),Ti=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat","web_launch_request"],Ii=u.enum(Ti),xi=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],cc=u.enum(xi),uc=u.union([Ii,u.literal("chat")]),Ai=["browser","agent","none"],Oi=u.enum(Ai),Ni=["browser","agent"],pc=u.enum(Ni),Pi=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],hc=u.enum(Pi),Ci=["file_bugs","write_tests","edit_project"],mc=u.enum(Ci),Di=["text","auto"],fc=u.enum(Di),Li=["project","scenarios","test_run","test_plan"],gc=u.enum(Li),Gi=["host_lost","awaiting_browser","awaiting_user","paused"],wc=u.enum(Gi),Ui=["window","mcp_agent","agent"],yc=u.enum(Ui),Mi=["opening","idle","busy","closing","closed"],_c=u.enum(Mi),$i=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],Ec=u.enum($i),Fi=["lead","user","workflow_ended","no_connection","left"],Sc=u.enum(Fi),ji=["lead","user","workflow_ended","workflow_paused","unit_ended"],Rc=u.enum(ji),Bi=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],kc=u.enum(Bi),Wi=["make_auto","atlas","run","agent","mcp_task","check_launch"],bc=u.enum(Wi);var Ki=["starting","running","ended"],vc=u.enum(Ki),Ji=["completed","cancelled","failed","start_failed","lost"],Tc=u.enum(Ji),qi=["user","lead","left","no_connection","workflow_ended","not_taken"],Vi=u.enum(qi);var Hi=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],Ic=u.enum(Hi),Yi=["lead_choice","role_default"],xc=u.enum(Yi),Xi=["observe","main","dangerous"],Ac=u.enum(Xi),zi=["main","dangerous"],Gn=u.enum(zi);var Zi=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],Oc=u.enum(Zi),Qi=["workflows.not_found","workflows.not_initiator","workflows.not_initiator_or_admin","workflows.worker_not_found","workflows.not_running","workflows.host_held","workflows.host_mismatch","workflows.host_lost","workflows.host_attached","workflows.host_pending","workflows.executor_kind_mismatch","workflows.executor_mismatch","workflows.agent_mismatch","workflows.request_mismatch","workflows.scope_not_found","workflows.scope_forbidden","workflows.conversation_busy","workflows.not_preset","workflows.not_pausable","workflows.not_continuable","workflows.text_not_stored","workflows.last_stage_not_retryable","workflows.not_amendable","workflows.place_mismatch","workflows.auto_requires_browser","workflows.segment_changed","workflows.mcp_join_unavailable","workflows.mcp_code_invalid","workflows.mcp_code_used","workflows.mcp_agent_not_found","workflows.mcp_agent_disconnected","workflows.mcp_inbox_invalid_cursor","workflows.question_not_to_lead","workflows.device_handoff_not_found","workflows.device_step_already_reported","workflows.device_run_ended","workflows.mcp_task_not_found","workflows.mcp_task_ended","workflows.mcp_task_address_required"],Nc=u.enum(Qi),Pc=u.object({status:Dn}),es=u.object({status:Dn}),ts=["conversation_deleted","text_not_stored"],ns=u.enum(ts),Cc=es.extend({reason:ns.extract(["conversation_deleted"]).optional()}),Dc=u.object({segment:u.number().int().min(1)}),Lc=u.object({executorKind:Oi}),Gc=u.object({reason:u.enum(["ended","no_browser"])}),Uc=u.object({reason:u.literal("task_paused")}),Mc=u.discriminatedUnion("outcome",[u.object({outcome:u.enum(["finished","stopped"]),lostReason:u.null()}),u.object({outcome:u.literal("lost"),lostReason:Vi})]),$c=u.object({taskIds:u.array(u.uuid()).min(2)}),Fc=u.object({stepNumber:u.number().int().min(1),currentStepNumber:u.number().int().min(1).nullable()}),jc=u.object({leaseExpiresAt:u.iso.datetime()}),Bc=u.object({workflowId:u.uuid()}),Wc=u.object({agentId:u.uuid()});var Vc=_.object({queueId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),applicationId:_.uuid().nullable(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),Un=_.object({launchId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),Mn=_.object({projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),standMode:Gn,accountLabel:_.string().min(1),role:_.string().min(1),locale:_.string().min(1),viewportWidth:_.number().int().min(1),viewportHeight:_.number().int().min(1)}).strict(),rs=_.object({...Mn.shape,environmentId:_.uuid().nullable()}).strict(),Hc=_.union([Mn,rs]),Yc=_.object({workflowId:_.uuid(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict();import{z as ue}from"zod";import{z as ce}from"zod";var $n=["passed","failed","infra","cancelled","abandoned"];var os=["queued","launching","in_progress"];var Fn=["passed","failed"],is=["before_hook_failed","no_start_page","no_path_for_page"],ss=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Jt=[...is,...ss],tu=ce.enum(Jt).exclude(["before_hook_failed"]);var nu=[...$n,...os];var ru=ce.object({by:ce.literal("human"),outcome:ce.enum(Fn)}).strict(),ou=ce.object({outcome:ce.enum(Fn)}).strict();var as=["queued","launching","in_progress","completed","failed","cancelled"],du=ue.enum(as);var ls=["queued","launching","in_progress"],jn=ue.enum(ls);var ds=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Jt,"result_not_saved","mcp_agent_disconnected"],cu=ue.enum(ds),cs=["launch_error","browser_gone","max_duration"],qt=ue.enum(cs),us=["name_not_resolved","unreachable","certificate","timeout","other"],Bn=ue.enum(us);var ps=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","stalled","capability_mismatch","subject_rejected","model_timeout","runs_not_started","credits_exhausted","tab_closed","slot_taken","ai_disabled","workflow_host_lost"],hs=ue.enum(ps),ms=["workflow_host_lost"],uu=hs.exclude(ms);var fs=d.enum(["darwin","linux","win32"]),gs=d.enum(["x64","arm64"]),Kn=d.enum(["official","debug"]),yu=d.object({enrollmentCode:d.string().min(32),hostname:d.string().min(1).max(255),platform:fs,arch:gs,agentVersion:d.string().min(1).max(30),protocolVersion:d.number().int().min(1)}).strict(),Ye=d.object({agentId:d.uuid(),agentToken:d.string().regex(de),pollWaitSec:d.number().int().min(1).max(25),protocolVersion:d.literal(1)}).strict(),_u=d.object({waitSec:d.coerce.number().int().min(0).max(25).optional()}).strict(),Jn=d.object({agent:d.object({revoked:d.boolean()}).strict(),run:d.union([d.null(),d.object({runId:d.uuid(),phase:jn,identities:d.array(d.object({identityId:d.uuid()}).strict()).optional(),launches:d.array(d.object({launchId:d.uuid()}).strict()).optional()}).strict()])}).strict(),Vt=d.object({v:d.literal(1),kind:d.literal("playback"),runId:d.uuid(),scenarioId:d.uuid(),projectId:d.uuid(),projectDomain:d.string().min(1),applicationId:d.uuid().nullable(),environmentId:d.uuid().nullable(),executionMode:d.literal("auto"),issuedAt:d.iso.datetime()}).strict(),Ht=d.object({v:d.literal(1),kind:d.literal("scenario_launch"),runId:d.uuid(),issuedAt:d.iso.datetime(),...Un.shape}).strict(),Yt=d.object({v:d.literal(1),kind:d.literal("swarm"),runId:d.uuid(),issuedAt:d.iso.datetime(),workflowId:d.uuid()}).strict(),ws=d.object({v:d.literal(1),kind:d.literal("task_identity"),runId:d.uuid(),issuedAt:d.iso.datetime(),workflowId:d.uuid(),identityId:d.uuid()}).strict(),ys=d.object({v:d.literal(1),kind:d.literal("task_launch"),runId:d.uuid(),issuedAt:d.iso.datetime(),workflowId:d.uuid(),launchId:d.uuid()}).strict(),Eu=d.union([Vt,Yt,Ht,ws,ys]),_s={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0,task_launch:!0},Su=Object.keys(_s),Ru=d.object({agentJobId:d.uuid(),updatedAt:d.iso.datetime()}).strict(),Es=d.enum(["invalid_envelope","dispatch_failed"]),qn=d.discriminatedUnion("outcome",[d.object({runId:d.uuid(),outcome:d.literal("dispatched")}).strict(),d.object({runId:d.uuid(),outcome:d.literal("rejected"),reason:Es}).strict()]),Vn=d.object({cancelRequested:d.boolean(),killRequested:d.boolean()}).strict(),Ss=2147483646,Rs=d.object({stepId:d.uuid(),stepIndex:d.number().int().min(0).max(Ss),status:d.enum(["passed","failed","skipped"]),failureCode:d.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:d.string().max(4e3).nullable(),startedAt:d.iso.datetime().nullable(),completedAt:d.iso.datetime().nullable()}).strict(),ku=d.object({events:d.array(Rs).min(1).max(50)}).strict(),bu=d.object({updated:d.number().int().min(0),control:Vn}).strict(),vu=d.object({phase:d.enum(["running","paused"])}).strict(),Tu=d.object({control:Vn}).strict(),Wn=d.string().max(500).optional(),Iu=d.discriminatedUnion("reason",[d.object({reason:d.literal(qt.enum.launch_error),message:Wn,entryFailure:Bn.optional()}).strict(),d.object({reason:qt.exclude(["launch_error"]),message:Wn}).strict()]),Hn=d.object({status:d.enum(["failed","already_terminal"])}).strict();var Cu=y.union([y.object({}).strict(),y.object({capabilities:In}).strict()]);function Xt(n){let{value:e}=n;e.command.runId!==e.runId&&n.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}i(Xt,"checkClaimRunIdAgreement");function ks(n){let{value:e}=n;e.command.projectId!==e.projectId&&n.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}i(ks,"checkPlaybackClaimProjectAgreement");var bs=y.object({runId:y.uuid(),scenarioId:y.uuid(),projectId:y.uuid(),applicationId:y.uuid().nullable(),projectDomain:y.string().min(1),entryUrl:y.url({protocol:/^https?$/}),environmentId:y.uuid().nullable(),runPurpose:Kn,headful:y.boolean(),maxRunDurationSec:y.number().int().min(60).max(3600),extensionSession:y.object({accessToken:y.string().min(1),refreshToken:y.string().min(1)}).strict(),command:Vt}).strict().check(Xt).check(ks),zt=y.object({accessToken:y.string().min(1),refreshToken:y.string().min(1)}).strict(),Zt=y.object({extensionSession:zt}).strict(),vs=y.object({kind:y.literal("swarm"),runId:y.uuid(),entryUrl:y.url({protocol:/^https?$/}),headful:y.boolean(),maxRunDurationSec:y.number().int().min(60).max(604800),extensionSession:zt,command:Yt}).strict().check(Xt),Ts=y.object({kind:y.literal("scenario_launch"),runId:y.uuid(),entryUrl:y.url({protocol:/^https?$/}),headful:y.boolean(),maxRunDurationSec:y.number().int().min(60).max(604800),extensionSession:zt,command:Ht}).strict().check(Xt),Xn=y.union([bs,vs,Ts]);import{z as zn}from"zod";var Is=["finished","cancelled","ai_disabled"],xs=zn.enum(Is),Uu=zn.object({outcome:xs}).strict();import{spawn as Us}from"node:child_process";import{existsSync as Ms}from"node:fs";import{createRequire as $s}from"node:module";import{dirname as er,join as Fs}from"node:path";import Ds from"pino";var As=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Os=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,Ns=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ps=["token","secret","password","authorization","api_key","api-key","apikey"],Cs=new RegExp(`([?&](?:${Ps.join("|")})=)([^&\\s]+)`,"gi"),Xe="[REDACTED]";function Zn(n){let e=n.replace(Ns,Xe);return e=e.replace(Os,Xe),e=e.replace(Cs,`$1${Xe}`),e}i(Zn,"redactValueString");function te(n){if(Array.isArray(n))return n.map(te);if(n!==null&&typeof n=="object"){let e=n,t={};for(let r of Object.keys(e))As.has(r.toLowerCase())?t[r]=Xe:t[r]=te(e[r]);return t}return typeof n=="string"?Zn(n):n}i(te,"redactSecrets");function $(n){return Zn(n)}i($,"redactSensitiveText");function Ls(){let n=process.env.PROGON_LOG_LEVEL;return n!==void 0&&new Set(["trace","debug","info","warn","error","fatal","silent"]).has(n)?n:process.env.NODE_ENV==="production"?"info":"debug"}i(Ls,"resolveLogLevel");function Gs(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(Gs,"buildTransport");var Qn=Ds({name:"qa-runner",level:Ls(),transport:Gs(),base:{pid:process.pid},redact:{paths:["token","agentToken","accessToken","refreshToken","pgrtToken","jobToken","authorization","secret","password","resolvedVariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key","*.token","*.agentToken","*.accessToken","*.refreshToken","*.secret","*.password","*.authorization","*.cookie","*.set-cookie","*.x-api-key","*.proxy-authorization","*.api-key"],censor:"[REDACTED]"}});function Qt(n){return{debug(e,t){t!==void 0?n.debug(te(t),e):n.debug(e)},info(e,t){t!==void 0?n.info(te(t),e):n.info(e)},warn(e,t){t!==void 0?n.warn(te(t),e):n.warn(e)},error(e,t){t!==void 0?n.error(te(t),e):n.error(e)},child(e){return Qt(n.child(e))}}}i(Qt,"adaptPino");function p(n){return Qt(Qn.child({module:n}))}i(p,"createLogger");var zu=Qt(Qn);var en=p("browser-provision"),js=60*6e4,V=class extends Error{static{i(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,t={}){super(e,{cause:t.cause}),this.name="BrowserProvisionError",this.exitCode=t.exitCode===void 0?null:t.exitCode,this.timedOut=t.timedOut===void 0?!1:t.timedOut}},tr=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
3
+ `);function Bs(){let n=$s(import.meta.url),e;try{e=n.resolve("playwright-core/package.json")}catch(r){throw new V(`[browser-provision] Cannot locate the 'playwright-core' package from ${import.meta.url}. It is a declared dependency of this agent \u2014 reinstall the package ('npm ci') rather than installing a browser by hand: the agent launches the revision THIS copy of playwright-core expects.`,{cause:r})}let t=Fs(er(e),"cli.js");if(!Ms(t))throw new V(`[browser-provision] 'playwright-core' resolved to ${er(e)} but its CLI is not at ${t}. That installation is incomplete or has been altered \u2014 reinstall it ('npm ci'). This agent installs Chromium through that CLI and through no other path (CONTRACT-la \xA715 A31.1).`);return{execPath:process.execPath,cliPath:t,args:["install","chromium","--no-shell"]}}i(Bs,"resolveInstallCommand");async function ze(n){let e=n.commandOverride===void 0?Bs():n.commandOverride,t=n.deadlineMs===void 0?js:n.deadlineMs,r=n.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],o=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,s=Date.now();en.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:t});let a=Us(e.execPath,[e.cliPath,...r],{env:process.env,stdio:n.stdio==="inherit"?"inherit":["ignore","pipe","pipe"]});if(n.stdio==="pipe"){let{stdout:g,stderr:m}=a;if(g===null||m===null)throw new V(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${o}).`);nr(g,"stdout"),nr(m,"stderr")}let l=!1,c=setTimeout(()=>{l=!0,a.kill("SIGKILL")},t),w=new Map,f=i(()=>{for(let[g,m]of w)process.off(g,m);w.clear()},"removeSignalHandlers");for(let g of["SIGTERM","SIGINT"]){let m=i(()=>{a.kill("SIGKILL"),f(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:g,installerPid:a.pid})+`
4
+ `),process.kill(process.pid,g)},"handler");w.set(g,m),process.on(g,m)}try{await new Promise((g,m)=>{a.once("error",v=>{m(new V(`[browser-provision] Could not start the Playwright installer (${o}): ${v.message}`,{cause:v}))}),a.once("close",(v,b)=>{if(l){m(new V(`[browser-provision] Chromium installation did not finish within ${t}ms and was killed (${o}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
5
+ ${tr}`,{exitCode:v,timedOut:!0}));return}if(v===0){g();return}let Ve=v===null?`was terminated by signal ${String(b)}`:`exited with code ${v}`;m(new V(`[browser-provision] Chromium could not be installed: the Playwright installer ${Ve} (${o}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
6
+ ${tr}`,{exitCode:v}))})})}finally{clearTimeout(c),f()}en.info("Chromium is provisioned",{durationMs:Date.now()-s})}i(ze,"provisionBrowser");function nr(n,e){let t="";n.setEncoding("utf8"),n.on("data",r=>{t+=r;let o=t.lastIndexOf(`
7
+ `);if(o===-1)return;let s=t.slice(0,o);t=t.slice(o+1);for(let a of s.split(`
8
+ `))rr(a,e)}),n.on("end",()=>{let r=t;t="",rr(r,e)})}i(nr,"forwardLinesToLogger");function rr(n,e){let t=n.replace(/\r/g,"").trim();t!==""&&en.info("Chromium provisioning output",{stream:e,line:t})}i(rr,"logLine");import{homedir as Aa}from"node:os";import{isAbsolute as Ir,join as ot}from"node:path";var h=class extends Error{static{i(this,"OperatorRefusalError")}};var Ws=new Set(["localhost","127.0.0.1","::1","[::1]"]);function ne(n){let e;try{e=new URL(n)}catch{throw new h("[config] PROGON_SERVER_URL is not a valid https:// URL. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Ws.has(e.hostname)))throw new h(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.host==="")throw new h(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(n)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new h("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");if(e.search!==""||e.hash!=="")throw new h(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix). See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(ne,"validateServerUrl");function Me(n){if(!de.test(n))throw new h("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}i(Me,"validateRunnerToken");function tn(n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n))throw new h(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(n)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}i(tn,"validateRunnerMachineId");function nn(n){if(n!==1)throw new h(`[config] Protocol version mismatch: state file records version ${n} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}i(nn,"validateProtocolVersion");import{Agent as Ks,EnvHttpProxyAgent as Js}from"undici";var or=p("gateway-proxy"),qs=["http_proxy","HTTP_PROXY"],Vs=["https_proxy","HTTPS_PROXY"],Hs=["no_proxy","NO_PROXY"];function Ys(n){return n.http!==void 0||n.https!==void 0}i(Ys,"gatewayIsProxied");var Xs=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,zs=/:\d+$/,Zs=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function Qs(n){let e=Zs.exec(n);if(e===null)return n;let t=e[1];return`${t===void 0?"":t}***@${n.slice(e[0].length)}`}i(Qs,"withoutProxyCredentials");function he(n,e,t){return new Error(`[config] ${n} does not name a proxy this agent can use: ${t}. Got: ${JSON.stringify(Qs(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${n} to connect to the server directly. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(he,"refuseProxyValue");function ir(n,e){for(let t of e){let r=n[t];if(r!==void 0)return r===""?void 0:{variable:t,raw:r}}}i(ir,"readProxyVariable");function ea(n){for(let e of Hs){let t=n[e];if(t!==void 0)return t}}i(ea,"readNoProxy");function sr(n,e){if(Xs.test(e)){let a;try{a=new URL(e)}catch{throw he(n,e,"it carries a scheme but is not a URL that parses")}if(a.protocol!=="http:"&&a.protocol!=="https:")throw he(n,e,`its scheme is ${JSON.stringify(a.protocol)}, not http: or https:`);if(a.hostname==="")throw he(n,e,"it names no host");return{variable:n,url:e,schemeCompleted:!1}}let t=e.search(/[/?#]/),r=t===-1?e:e.slice(0,t);if(!zs.test(r))throw he(n,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let o=`http://${e}`,s;try{s=new URL(o)}catch{throw he(n,e,'it is neither a URL nor a "host:port" pair')}if(s.hostname==="")throw he(n,e,"it names no host");return{variable:n,url:o,schemeCompleted:!0}}i(sr,"parseProxyValue");function rn(n){let e=ir(n,qs),t=ir(n,Vs);return{http:e===void 0?void 0:sr(e.variable,e.raw),https:t===void 0?void 0:sr(t.variable,t.raw),noProxy:ea(n)}}i(rn,"resolveGatewayProxyConfig");function ar(n,e,t){if(!Ys(n))return new Ks(e);or.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:n.http!==void 0,httpsProxy:n.https!==void 0,noProxy:n.noProxy!==void 0});let r=[];for(let s of[n.http,n.https])s!==void 0&&s.schemeCompleted&&r.push(s.variable);r.length>0&&or.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let o={...e,...t===void 0?{}:{requestTls:{ca:t},proxyTls:{ca:t}},httpProxy:n.http?.url,httpsProxy:n.https?.url,noProxy:n.noProxy};return new Js(o)}i(ar,"createProxyAwareDispatcher");function lr(n){rn(n)}i(lr,"validateGatewayProxyEnv");import{readFileSync as ta,statSync as na}from"node:fs";import{isAbsolute as ra}from"node:path";import{rootCertificates as dr}from"node:tls";var oa=p("gateway-tls-trust"),Qe="PROGON_AGENT_EXTRA_CA_CERTS";function Ze(n,e,t){let r=`[config] ${Qe} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(n)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Qe} to trust only the public roots.`;return t===void 0?new Error(r):new Error(r,{cause:t})}i(Ze,"refuseExtraCaValue");function cr(n){let e=n[Qe];if(e===void 0||e==="")return;if(!ra(e))throw Ze(e,"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in");let t;try{t=na(e)}catch(o){throw Ze(e,"it cannot be read",o)}if(!t.isFile())throw Ze(e,"it is not a file");let r;try{r=ta(e,"utf8")}catch(o){throw Ze(e,"its contents could not be read",o)}return{variable:Qe,path:e,pem:r}}i(cr,"resolveExtraCaTrust");function ur(n){let e=cr(n);if(e!==void 0)return oa.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:dr.length}),[...dr,e.pem]}i(ur,"readTrustedCaBundle");function pr(n){cr(n)}i(pr,"validateExtraCaTrustEnv");import{readFileSync as da}from"node:fs";import{dirname as ca,join as ua}from"node:path";import{fileURLToPath as pa}from"node:url";function re(n){if(typeof n!="object"||n===null)return!1;let e=n.code;return e==="ENOENT"||e==="ENOTDIR"}i(re,"isAbsentPathError");import{statSync as ia}from"node:fs";import{dirname as sa,join as aa}from"node:path";var hr="package.json";function et(n){let e=n;for(;;){if(la(e))return e;let t=sa(e);if(t===e)throw new Error(`[package-root] No ${hr} was found in ${n} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=t}}i(et,"findPackageRoot");function la(n){try{return ia(aa(n,hr)),!0}catch(e){if(re(e))return!1;throw e}}i(la,"holdsPackageManifest");var ha="extension-bundle.json";function on(){return ma(ua(et(ca(pa(import.meta.url))),ha))}i(on,"readBundledAppUrl");function ma(n){let e;try{e=da(n,"utf-8")}catch(o){if(re(o))return null;throw new h(`[extension-bundle] ${n} exists but could not be read: ${String(o)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:o})}let t;try{t=JSON.parse(e)}catch(o){throw new h(`[extension-bundle] ${n} contains invalid JSON: ${String(o)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:o})}if(typeof t!="object"||t===null||Array.isArray(t)){let o=t===null?"null":Array.isArray(t)?"array":typeof t;throw new h(`[extension-bundle] ${n} must contain a JSON object, got: ${o}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=t.appUrl;if(typeof r!="string"||r==="")throw new h(`[extension-bundle] ${n} has no usable 'appUrl' (expected a non-empty string). That field is the deployment this package was built for; without it the agent cannot tell which Progon it belongs to. Reinstall the package (npm i -g progon-agent@latest), or name the deployment explicitly with --server / PROGON_SERVER_URL.`);try{ne(r)}catch(o){throw new h(`[extension-bundle] ${n} has an invalid 'appUrl': ${String(o)}`,{cause:o})}return r}i(ma,"readBundledAppUrlFrom");import{unlinkSync as Ia}from"node:fs";import{readFileSync as fa,writeFileSync as ga,renameSync as wa,mkdirSync as ya,existsSync as _a,chmodSync as Ea,fchmodSync as Sa,openSync as mr,fsyncSync as fr,closeSync as gr,unlinkSync as Ra}from"node:fs";import{join as wr}from"node:path";var tt=p("state-file");function nt(n){return wr(n,"runner-state.json")}i(nt,"stateFilePath");function sn(n){return wr(n,"runner-state.json.tmp")}i(sn,"stateTmpPath");function yr(n){let e=nt(n);if(!_a(e))return tt.debug("No state file found \u2014 first start",{filePath:e}),null;let t;try{t=fa(e,"utf-8")}catch(s){throw new h(`[state-file] Failed to read state file at ${e}: ${String(s)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let r;try{r=JSON.parse(t)}catch(s){throw new h(`[state-file] State file at ${e} contains invalid JSON: ${String(s)}. Remove the file and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let o=va(r,e);return tt.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(yr,"readState");function _r(n,e){ya(n,{recursive:!0,mode:448}),Ea(n,448);let t=nt(n),r=sn(n),o=JSON.stringify(e,null,2);try{let s=mr(r,"w",384);try{Sa(s,384),ga(s,o,{encoding:"utf-8"}),fr(s)}finally{gr(s)}wa(r,t),ba(n)}catch(s){throw ka(r),new h(`[state-file] Failed to write state file at ${t}: ${String(s)}. Check permissions on stateDir ${n}.`)}tt.info("State file written",{agentId:e.agentId,filePath:t})}i(_r,"writeState");function ka(n){try{Ra(n)}catch(e){if(e.code==="ENOENT")return;tt.error("Failed to remove the temporary state file \u2014 it may still hold the agent credential",{tmpPath:n,err:e instanceof Error?e.message:String(e)})}}i(ka,"removeStateTmp");function ba(n){let e=mr(n,"r");try{fr(e)}finally{gr(e)}}i(ba,"fsyncDirectory");function va(n,e){if(typeof n!="object"||n===null||Array.isArray(n)){let l=n===null?"null":Array.isArray(n)?"array":typeof n;throw new h(`[state-file] State file ${e} must contain a JSON object, got: ${l}`)}let t=n,r=t.agentId;if(typeof r!="string"||r==="")throw new h(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);tn(r);let o=t.agentToken;if(typeof o!="string"||o==="")throw new h(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Me(o);let s=t.protocolVersion;if(typeof s!="number"||!Number.isInteger(s))throw new h(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);nn(s);let a=t.serverUrl;if(typeof a!="string"||a==="")throw new h(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{ne(a)}catch(l){throw new h(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:o,protocolVersion:s,serverUrl:a,tokenRotatedAt:Ta(t,e)}}i(va,"validateState");function Ta(n,e){let t=n.tokenRotatedAt;if(t==null)return null;if(typeof t!="string"||t==="")throw new h(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return t}i(Ta,"readTokenRotatedAt");var Er=p("token-store");function F(n){return yr(n)}i(F,"loadAgentIdentity");function me(n,e){_r(n,e)}i(me,"saveAgentIdentity");function Rr(n){let e=nt(n),t=sn(n),r=Sr(t,"temporary state file"),o=Sr(e,"identity");if(!o&&!r){Er.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:t});return}Er.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:t,removedState:o,removedTmp:r})}i(Rr,"wipeAgentIdentity");function Sr(n,e){try{return Ia(n),!0}catch(t){if(xa(t))return!1;throw new Error(`[token-store] Failed to wipe the agent ${e} at ${n}: ${String(t)}. The agent has been revoked (CONTRACT-la \xA715 A15.1) and its credential must not remain on disk \u2014 remove the file manually.`)}}i(Sr,"removeCredentialFile");function xa(n){return n.code==="ENOENT"}i(xa,"isFileNotFound");var kr="extension-bundle.json";function rt(n,e){return br(n)===br(e)}i(rt,"isSameDeployment");function br(n){let e=new URL(n);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}i(br,"normalizeDeployment");function vr(n){let{envUrl:e,envTokenPresent:t,stateDir:r}=n;if(e!==void 0)return ne(e),{url:e,source:"env"};if(t){let a=on();if(a!==null)return{url:a,source:"bundle"};throw new h(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
9
+ This build carries no ${kr} either, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
10
10
  The state file in ${r} is deliberately NOT consulted on this path: PROGON_AGENT_TOKEN is the rotation and recovery mechanism, and it must not start depending on the very file an operator sets it to recover from.
11
11
  Set PROGON_SERVER_URL to the deployment this token belongs to; or unset PROGON_AGENT_TOKEN, after which an enrolled machine takes both its credential and its server from that state file.
12
- See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let o=$(r);if(o!==null)return{url:o.serverUrl,source:"state_file"};let a=Ht();if(a!==null)return{url:a,source:"bundle"};throw new p(`[config] This machine is not enrolled and no deployment is configured, so the agent does not know which Progon to talk to \u2014 none of the three places it looks names one.
13
- PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${ur}, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
12
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let o=F(r);if(o!==null)return{url:o.serverUrl,source:"state_file"};let s=on();if(s!==null)return{url:s,source:"bundle"};throw new h(`[config] This machine is not enrolled and no deployment is configured, so the agent does not know which Progon to talk to \u2014 none of the three places it looks names one.
13
+ PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${kr}, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
14
14
  Enroll this machine \u2014 'progon-agent enroll --server <url>' (approved in a browser), or 'progon-agent enroll <code> --server <url>' with a code from Progon (Settings \u2192 Agents). Enrollment persists the server together with the credential, so every later command finds it with no environment at all.
15
15
  If this machine WAS enrolled with PROGON_RUNNER_STATE_DIR set, set the same variable again \u2014 that directory is where its credential and its server are.
16
16
  Setting PROGON_SERVER_URL on its own names a server but no agent: it is what an 'enroll' needs, and it is enough for 'start' only alongside PROGON_AGENT_TOKEN.
17
- See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(pr,"resolveServerUrl");function Pe(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}i(Pe,"getOptional");function hr(t,e){let n=process.env[t];if(n===void 0||n==="")return e;let r=n.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new p(`[config] Environment variable ${t} must be one of true/false/1/0, got: ${JSON.stringify(n)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(hr,"getOptionalBool");var et="progon-agent";function hs(t,e,n){if(n==="")throw new p("[config] Cannot resolve the default state directory: the current user has no home directory (os.homedir() returned an empty string \u2014 happens in service/container contexts without HOME). Set PROGON_RUNNER_STATE_DIR explicitly.");switch(t){case"darwin":return Qe(n,"Library","Application Support",et);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return Qe(n,".local","state",et);if(!fr(r))throw new p(`[config] XDG_STATE_HOME must be an absolute path (XDG Base Directory specification), got: ${JSON.stringify(r)}. Fix the variable or set PROGON_RUNNER_STATE_DIR explicitly.`);return Qe(r,et)}case"win32":{let r=e.APPDATA;if(r===void 0||r==="")throw new p("[config] %APPDATA% is not set, so the default Windows state directory cannot be resolved. Set PROGON_RUNNER_STATE_DIR explicitly.");return Qe(r,et)}default:throw new p(`[config] No default state directory is defined for platform ${JSON.stringify(t)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}i(hs,"resolveDefaultStateDir");function ue(){Xn(process.env),er(process.env);let t=process.env.PROGON_AGENT_TOKEN;if(t==="")throw new p("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let e=t;e!==void 0&&Ne(e);let n=Pe("PROGON_RUNNER_STATE_DIR")??hs(process.platform,process.env,ps()),r=pr({envUrl:Pe("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),o=Pe("PROGON_AGENT_EXTENSION_DIST");if(o!==void 0&&!fr(o))throw new p(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(o)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let a=Pe("PROGON_AGENT_ENROLL_CODE");if(a!==void 0&&a.length<32)throw new p(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${a.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:n,extensionDistOverride:o,headfulOverride:hr("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:hr("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:a,nodeEnv:Pe("NODE_ENV")??"production"}}i(ue,"loadConfig");function Ce(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
18
- `)}i(Ce,"writeLine");function wr(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:M(e),stack:n!==void 0?M(n):void 0}}i(wr,"describeError");function gr(t,e,n){Ce("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...wr(e),...n})}i(gr,"writeFatalLine");function yr(){process.on("uncaughtException",(t,e)=>{gr("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{gr("unhandledRejection",t,{}),process.exit(1)})}i(yr,"installProcessGuards");function _r(t){let e=!1,n=i(r=>{if(e){Ce("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,Ce("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(o){Ce("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...wr(o)}),process.exit(1)}Ce("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",n),process.on("SIGINT",n)}i(_r,"installShutdownHandlers");import{chmodSync as fs,cpSync as gs,mkdirSync as ws,readdirSync as ys,renameSync as _s,rmSync as Xt,statSync as Er,writeFileSync as Es}from"node:fs";import{dirname as Ss,join as me}from"node:path";import{fileURLToPath as Rs}from"node:url";var tt=m("extension-dist"),bs="extension-dist",Rr="extension-dist",br=`${Rr}.tmp-`,zt="agent-manifest.json",Sr="manifest.json";function ks(){return Ye(Ss(Rs(import.meta.url)))}i(ks,"packageRoot");function Ts(){return vs(me(ks(),bs))}i(Ts,"resolveBundledExtensionSource");function vs(t){let e;try{e=Er(t)}catch(r){throw Q(r)?new Error(Yt(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(Yt(t,"that path is not a directory"));let n=me(t,Sr);try{Er(n)}catch(r){throw Q(r)?new Error(Yt(t,`it holds no ${Sr}`),{cause:r}):r}return t}i(vs,"assertBundledExtensionSource");function Yt(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
17
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(vr,"resolveServerUrl");function $e(n){let e=process.env[n];return e!==void 0&&e!==""?e:void 0}i($e,"getOptional");function Tr(n,e){let t=process.env[n];if(t===void 0||t==="")return e;let r=t.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new h(`[config] Environment variable ${n} must be one of true/false/1/0, got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(Tr,"getOptionalBool");var it="progon-agent";function Oa(n,e,t){if(t==="")throw new h("[config] Cannot resolve the default state directory: the current user has no home directory (os.homedir() returned an empty string \u2014 happens in service/container contexts without HOME). Set PROGON_RUNNER_STATE_DIR explicitly.");switch(n){case"darwin":return ot(t,"Library","Application Support",it);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return ot(t,".local","state",it);if(!Ir(r))throw new h(`[config] XDG_STATE_HOME must be an absolute path (XDG Base Directory specification), got: ${JSON.stringify(r)}. Fix the variable or set PROGON_RUNNER_STATE_DIR explicitly.`);return ot(r,it)}case"win32":{let r=e.APPDATA;if(r===void 0||r==="")throw new h("[config] %APPDATA% is not set, so the default Windows state directory cannot be resolved. Set PROGON_RUNNER_STATE_DIR explicitly.");return ot(r,it)}default:throw new h(`[config] No default state directory is defined for platform ${JSON.stringify(n)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}i(Oa,"resolveDefaultStateDir");function fe(){lr(process.env),pr(process.env);let n=process.env.PROGON_AGENT_TOKEN;if(n==="")throw new h("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let e=n;e!==void 0&&Me(e);let t=$e("PROGON_RUNNER_STATE_DIR")??Oa(process.platform,process.env,Aa()),r=vr({envUrl:$e("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:t}),o=$e("PROGON_AGENT_EXTENSION_DIST");if(o!==void 0&&!Ir(o))throw new h(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(o)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let s=$e("PROGON_AGENT_ENROLL_CODE");if(s!==void 0&&s.length<32)throw new h(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${s.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:t,extensionDistOverride:o,headfulOverride:Tr("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Tr("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:s,nodeEnv:$e("NODE_ENV")??"production"}}i(fe,"loadConfig");function Fe(n,e,t){process.stderr.write(JSON.stringify({level:n,module:"process-guards",msg:e,...t})+`
18
+ `)}i(Fe,"writeLine");function Ar(n){let e=n instanceof Error?n.message:String(n),t=n instanceof Error?n.stack:void 0;return{err:$(e),stack:t!==void 0?$(t):void 0}}i(Ar,"describeError");function xr(n,e,t){Fe("fatal",`Unhandled ${n} \u2014 terminating the daemon`,{event:n,...Ar(e),...t})}i(xr,"writeFatalLine");function Or(){process.on("uncaughtException",(n,e)=>{xr("uncaughtException",n,{origin:e}),process.exit(1)}),process.on("unhandledRejection",n=>{xr("unhandledRejection",n,{}),process.exit(1)})}i(Or,"installProcessGuards");function Nr(n){let e=!1,t=i(r=>{if(e){Fe("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,Fe("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await n(r)}catch(o){Fe("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...Ar(o)}),process.exit(1)}Fe("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",t),process.on("SIGINT",t)}i(Nr,"installShutdownHandlers");import{chmodSync as Na,cpSync as Pa,mkdirSync as Ca,readdirSync as Da,renameSync as La,rmSync as ln,statSync as Pr,writeFileSync as Ga}from"node:fs";import{dirname as Ua,join as ge}from"node:path";import{fileURLToPath as Ma}from"node:url";var st=p("extension-dist"),$a="extension-dist",Dr="extension-dist",Lr=`${Dr}.tmp-`,dn="agent-manifest.json",Cr="manifest.json";function Fa(){return et(Ua(Ma(import.meta.url)))}i(Fa,"packageRoot");function ja(){return Ba(ge(Fa(),$a))}i(ja,"resolveBundledExtensionSource");function Ba(n){let e;try{e=Pr(n)}catch(r){throw re(r)?new Error(an(n,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(an(n,"that path is not a directory"));let t=ge(n,Cr);try{Pr(t)}catch(r){throw re(r)?new Error(an(n,`it holds no ${Cr}`),{cause:r}):r}return n}i(Ba,"assertBundledExtensionSource");function an(n,e){return`[extension-dist] No extension dist is bundled in this package (${n}): ${e}.
19
19
  This package was built WITHOUT the bundling step. Run 'npm run bundle:extension' in the agent package (it copies a built qa-extension dist in; set PROGON_EXTENSION_DIST_SRC to point at that dist if it is not the sibling checkout), then reinstall or restart the daemon.
20
- For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}i(Yt,"bundledMissingMessage");function As(t){let{stateDir:e,agentId:n}=t;if(n==="")throw new Error(`[extension-dist] agentId is required: ${zt} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=t.sourceDir??Ts(),o=me(e,Rr),a=me(e,`${br}${process.pid}`);return ws(e,{recursive:!0,mode:448}),Is(e),Xt(a,{recursive:!0,force:!0}),gs(r,a,{recursive:!0}),fs(a,448),xs(a,n),Xt(o,{recursive:!0,force:!0}),_s(a,o),tt.info("Agent-mode extension dist prepared",{extensionDist:o,sourceDir:r,agentId:n,protocolVersion:1}),o}i(As,"prepareAgentExtensionDist");function xs(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};Es(me(t,zt),JSON.stringify(n,null,2)+`
21
- `,"utf8")}i(xs,"writeAgentManifest");function Is(t){let e;try{e=ys(t,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return;throw n}for(let n of e){if(!n.name.startsWith(br))continue;let r=me(t,n.name);try{Xt(r,{recursive:!0,force:!0}),tt.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(o){tt.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:o instanceof Error?o.message:String(o)})}}}i(Is,"removeLeftoverStagingDirs");function kr(t){if(t.overridePath!==void 0)return tt.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:t.overridePath}),t.overridePath;if(t.agentId===null)throw new Error(`[extension-dist] Cannot prepare the agent-mode extension dist: this daemon authenticated with PROGON_AGENT_TOKEN, which carries no agentId, and ${zt} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
22
- Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return As({stateDir:t.stateDir,agentId:t.agentId})}i(kr,"resolveExtensionDist");import{fetch as Ps}from"undici";var k=class extends Error{static{i(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},F=class extends k{static{i(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},b=class extends k{static{i(this,"GatewayHttpError")}status;errorCode;params;constructor(e,n,r,o,a){super(e,`[gateway] ${e} refused with HTTP ${n}: ${a}`),this.status=n,this.errorCode=r,this.params=o}},pe=class extends b{static{i(this,"GatewayUnauthorizedError")}},T=class extends b{static{i(this,"TokenSupersededError")}},E=class extends k{static{i(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},nt=class extends b{static{i(this,"EnrollmentCodeRejectedError")}},De=class extends b{static{i(this,"ProtocolVersionMismatchError")}},he=class extends b{static{i(this,"RunNotClaimableError")}},ee=class extends b{static{i(this,"RunNotFoundError")}},j=class extends k{static{i(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};var Tr=m("gateway-http");async function te(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),Tr.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(o){throw new F(t.operation,vr(o),o)}let r;try{r=await n.text()}catch(o){throw new F(t.operation,vr(o),o)}if(!n.ok){let o=Os(n.status,r);throw Tr.debug("Gateway request refused",{operation:t.operation,status:o.status,errorCode:o.errorCode}),t.mapHttpError(o)}try{return JSON.parse(r)}catch(o){throw new j(t.operation,`the ${n.status} response body is not valid JSON`,o)}}i(te,"executeGatewayRequest");function C(t,e){if(e.success)return e.data;throw new j(t,Ns(e.error),e.error)}i(C,"parseGatewayBody");function Os(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:Zt}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:Zt};let r=n,o=r.error_code,a=r.params,s=r.message;return{status:t,errorCode:typeof o=="string"?o:null,params:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,message:typeof s=="string"?M(s):Zt}}i(Os,"readErrorEnvelope");var Zt="the response body carried no Progon error envelope";function vr(t){return M(t instanceof Error?t.message:String(t))}i(vr,"describeCause");function Ns(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let o=r.path;return!Array.isArray(o)||o.length===0?"<root>":o.map(a=>String(a)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}i(Ns,"summarizeSchemaViolation");var fe=class extends b{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,o,a,s){super(e,n,r,o,a),this.retryAfterSec=s}},ge=class extends b{static{i(this,"EnrollmentAccessDeniedError")}},we=class extends b{static{i(this,"EnrollmentRequestExpiredError")}},ye=class extends b{static{i(this,"EnrollmentAlreadyCompletedError")}},_e=class extends b{static{i(this,"EnrollmentRequestInvalidError")}};function Ar(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?N(nt,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?N(De,"enroll",t):L("enroll",t)}i(Ar,"mapEnrollError");function xr(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?N(De,"enrollment_request_create",t):L("enrollment_request_create",t)}i(xr,"mapEnrollmentRequestCreateError");function Ir(t){if(t.status===429&&t.errorCode==="agent_enroll.slow_down"){let e=t.params===null?void 0:t.params.retryAfterSeconds,n=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new fe("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?N(ge,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?N(we,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?N(ye,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?N(_e,"enrollment_request_poll",t):L("enrollment_request_poll",t)}i(Ir,"mapEnrollmentRequestPollError");function Or(t){return L("enrollment_request_cancel",t)}i(Or,"mapEnrollmentRequestCancelError");function Nr(t){return Ee("poll_desired_state",t,()=>L("poll_desired_state",t))}i(Nr,"mapPollDesiredStateError");function Pr(t){return Ee("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?N(he,"claim",t):t.status===404?N(ee,"claim",t):L("claim",t))}i(Pr,"mapClaimError");function Cr(t){return Ee("fail",t,()=>t.status===404?N(ee,"fail",t):L("fail",t))}i(Cr,"mapFailError");function Dr(t){return Ee("token_status",t,()=>L("token_status",t))}i(Dr,"mapTokenStatusError");function Lr(t){return Ee("token_rotate",t,()=>L("token_rotate",t))}i(Lr,"mapTokenRotateError");function Gr(t){return Ee("declare_capabilities",t,()=>L("declare_capabilities",t))}i(Gr,"mapDeclareCapabilitiesError");function Ee(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new E(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?N(T,t,e):e.status===401?N(pe,t,e):n()}i(Ee,"bearerRoute");function N(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}i(N,"named");function L(t,e){return N(b,t,e)}i(L,"generic");var rt=[...gn,wn,_n,yn,En,Sn,Rn];import{z as ne}from"zod";var Ur=ne.object({rotationDue:ne.boolean(),tokenRotatedAt:ne.string().nullable(),anchorAt:ne.string(),intervalDays:ne.number().int()}),Mr=ne.object({agentToken:ne.string().regex(ie)});var ot=m("gateway-client"),Cs="/api/agent-gateway";function D(t,e){return new URL(`${t.replace(/\/+$/,"")}${Cs}${e}`)}i(D,"buildGatewayUrl");var $r=3e5,jr=1e4,Fr={headersTimeout:$r,bodyTimeout:$r,connect:{timeout:jr}};function Ds(){let t=Qn(process.env);return Yn(Vt(process.env),t===void 0?Fr:{...Fr,connect:{timeout:jr,ca:t}},t)}i(Ds,"buildGatewayDispatcher");var Qt,st=i((t,e)=>{if(Qt===void 0){let n=Ds();Qt=i((r,o)=>Ps(r,{...o,dispatcher:n}),"defaultGatewayFetch")}return Qt(t,e)},"pinnedGatewayFetch"),it=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??st}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await te({operation:"enroll",method:"POST",url:D(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ar}),o=C("enroll",We.safeParse(r));return ot.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},at=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??st}async authenticatedRequest(e){return te({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=D(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:Nr}),o=C("poll_desired_state",Dn.safeParse(r));if(o.agent.revoked)throw new E("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return o}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:D(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:rt},signal:void 0,mapHttpError:Pr});return C("claim",Mn.safeParse(n))}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:D(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Cr}),o=C("fail",Un.safeParse(r));return ot.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:o.status}),o}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:D(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Dr});return C("token_status",Ur.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:D(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Lr});return C("token_rotate",Mr.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:D(this.serverUrl,"/capabilities"),body:{capabilities:rt},signal:e?.signal,mapHttpError:Gr}),ot.info("Capabilities declared",{capabilities:rt})}useAgentToken(e){this.agentToken=e,ot.info("Adopted a rotated agent token for all subsequent gateway requests")}};var Ls=m("debug-env-guard"),Gs=["pw:protocol","pw:api"];function Us(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(Us,"escapeRegExp");function Wr(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Us).join(".*?")}$`,n=new RegExp(e);return Gs.some(r=>n.test(r))}i(Wr,"enablesPlaywright");function Ms(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(o=>o.trim()).filter(o=>o!==""),n=e.filter(o=>Wr(o));if(n.length===0)return[];let r=e.filter(o=>!Wr(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),Ls.warn("Playwright debug namespaces removed from DEBUG before playwright-core loaded",{removed:n,kept:r,debugFile:process.env.DEBUG_FILE??null,reason:"pw: namespaces write raw CDP messages \u2014 including the per-run session tokens sent to chrome.storage.local \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),n}i(Ms,"sanitizePlaywrightDebugEnv");Ms();import{statSync as qr}from"node:fs";import{isAbsolute as Fs,join as js}from"node:path";import{createRequire as $s}from"node:module";var W=$s(import.meta.url)("playwright-core"),lt=W.chromium,$p=W.firefox,Fp=W.webkit,jp=W.selectors,Wp=W.devices,Br=W.errors,Bp=W.request,Kp=W._electron,qp=W._android;var dt="chromium";var Kr="instances",ct="instance.json";var Ws=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"];async function Vr(t){return lt.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:dt,ignoreHTTPSErrors:t.allowInsecureHttps,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check",...t.keepBackgroundWindowsRendering?Ws:[]]})}i(Vr,"launchExtensionContext");function Bs(t){let e=t.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}i(Bs,"requireBrowser");function Hr(t){return Bs(t).version()}i(Hr,"readChromeVersion");async function Jr(t,e){let n,r=new Promise(o=>{n=setTimeout(()=>o({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),o=>({settled:"rejected",error:o})),r])}finally{n!==void 0&&clearTimeout(n)}}i(Jr,"raceClose");function Yr(t){if(!Fs(t))throw new Error(`[runtime] The extension dist path must be absolute, got ${JSON.stringify(t)}. A relative path would be resolved against the daemon's working directory.`);let e;try{e=qr(t)}catch(r){throw new Error(`[runtime] The extension dist directory ${t} cannot be read. Chromium does NOT fail on a bad --load-extension: it would start without the extension and every run would time out in the readiness probe. Check PROGON_AGENT_EXTENSION_DIST (CONTRACT-la \xA78).`,{cause:r})}if(!e.isDirectory())throw new Error(`[runtime] The extension dist path ${t} is not a directory.`);let n=js(t,"manifest.json");try{qr(n)}catch(r){throw new Error(`[runtime] ${n} is missing, so ${t} is not a built extension. Build qa-extension, or point PROGON_AGENT_EXTENSION_DIST at a real dist.`,{cause:r})}}i(Yr,"assertUsableExtensionDist");var Ks=m("worker-evaluate"),en=class extends Error{static{i(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,n){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${n}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=n}};async function q(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&Ks.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:a instanceof Error?a.message:String(a)})});let r,o=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new en(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(q,"evaluateWithDeadline");var Xr="accessToken",zr="refreshToken";async function Qr(t,e){await q({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o,a,s])=>new Promise(d=>chrome.storage.local.set({[r]:a,[o]:s},()=>d())),[Xr,zr,e.accessToken,e.refreshToken]),"evaluate")});let n=await q({operation:"read the run session back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o])=>new Promise(a=>chrome.storage.local.get([r,o],s=>{let d=s[r],c=s[o];a({accessTokenLength:typeof d=="string"?d.length:null,refreshTokenLength:typeof c=="string"?c.length:null})})),[Xr,zr]),"evaluate")});if(n.accessTokenLength!==e.accessToken.length||n.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: chrome.storage.local holds accessToken(len=${String(n.accessTokenLength)}), refreshToken(len=${String(n.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return n}i(Qr,"seedRunSession");function Zr(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}i(Zr,"canonicalise");async function eo(t,e){await q({operation:`write the command envelope to chrome.storage.local['${Ie}']`,timeoutMs:1e4,evaluate:i(()=>t.evaluate(([a,s])=>new Promise(d=>chrome.storage.local.set({[a]:s},()=>d())),[Ie,e]),"evaluate")});let n=await q({operation:"read the command envelope back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],d=>{let c=d[a];s(c===void 0?null:c)})),Ie),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${Ie}'] does not hold the envelope`);let r=Zr({...e}),o=Zr(n);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(eo,"seedCommandEnvelope");async function Vs(t,e,n){let r=await q({operation:`read chrome.storage.local['${Fe}']`,timeoutMs:n,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],d=>{let c=d[a];s(c===void 0?null:c)})),Fe),"evaluate")});if(r===null)return{kind:"absent"};let o=Ln.safeParse(r);return o.success?o.data.runId!==e?{kind:"other_run",detail:`the ack under that key belongs to run ${o.data.runId}`}:{kind:"ack",ack:o.data}:{kind:"invalid",detail:`the value under that key failed agentCommandAckSchema: ${String(o.error)}`}}i(Vs,"pollCommandAck");async function to(t,e,n){let r=Date.now()+n,o="no ack was written";for(;;){let a=r-Date.now();if(a<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${o}. chrome.storage.local['${Fe}'] is the only success signal (CONTRACT-la \xA75.4).`);let s=t.serviceWorkers()[0];if(s===void 0)o="the context exposed no service worker while polling (evicted, restarting)";else{let d;try{d=await Vs(s,e,a)}catch(c){o=`the last poll failed: ${c instanceof Error?c.message:String(c)}`,d={kind:"invalid",detail:o}}if(d.kind==="ack")return d.ack;d.kind!=="absent"&&(o=d.detail)}await new Promise(d=>setTimeout(d,250))}}i(to,"waitForCommandAck");import mt from"node:os";import{createRequire as Hs}from"node:module";var no=Hs(import.meta.url);function Js(){let t=no.resolve("playwright-core/package.json"),e=no(t);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${t} did not parse into an object.`);let n=e.version;if(typeof n!="string"||n==="")throw new Error(`[runtime] ${t} declares no version string.`);return n}i(Js,"readPlaywrightCoreVersion");function ro(t){return{node:process.version,platform:`${mt.platform()} ${mt.release()} ${mt.arch()}`,cpus:mt.cpus().length,playwrightCore:Js(),chromiumExecutable:lt.executablePath(),channel:dt,extensionDist:t}}i(ro,"buildEnvFingerprint");import{mkdirSync as uo,readdirSync as ml,readFileSync as pl,renameSync as hl,rmSync as rn,writeFileSync as fl}from"node:fs";import{join as Le}from"node:path";var V=class extends Error{static{i(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,o){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:o}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function tn(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n)&&(e.add(n),n.cause!==void 0);)n=n.cause;return n instanceof Error?n.message:String(n)}i(tn,"deepestCauseMessage");var Ys=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),Xs=/\bnet::(ERR_[A-Z0-9_]+)\b/;function oo(t){if(zs(t))return"timeout";let e=Xs.exec(tn(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":Ys.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}i(oo,"entryFailureOf");function zs(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof Br.TimeoutError)return!0;e.add(n),n=n.cause}return!1}i(zs,"causeChainHasTimeout");var H=class extends Error{static{i(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},pt=class extends Error{static{i(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,n){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${n}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=n}};import{execFile as Qs}from"node:child_process";import{promisify as el}from"node:util";import{setTimeout as lo}from"node:timers/promises";var ht=el(Qs),ft={timeout:5e3};function co(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.code!="number"?null:{code:e.code,stdout:typeof e.stdout=="string"?e.stdout:"",stderr:typeof e.stderr=="string"?e.stderr:""}}i(co,"asExecFailure");function tl(t){let e=[];for(let n of t.split(`
23
- `)){let r=n.trim();if(r==="")continue;let o=Number(r);!Number.isInteger(o)||o===process.pid||e.push(o)}return e}i(tl,"parsePidLines");var nn="--user-data-dir=",nl=new Set([" "," ",'"',"'"]),rl=new Set([" "," ",'"',"'"]);function ol(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}i(ol,"escapeEre");function il(t){return`(^|[[:space:]'"])${ol(`${nn}${t}`)}([[:space:]'"]|$)`}i(il,"buildAnchorPattern");function al(t,e){let n=t.toLowerCase(),r=`${nn}${e}`.toLowerCase();for(let o=n.indexOf(r);o!==-1;o=n.indexOf(r,o+1)){let a=o===0?void 0:n[o-1],s=n[o+r.length],d=a===void 0||nl.has(a),c=s===void 0||rl.has(s);if(d&&c)return!0}return!1}i(al,"matchesAnchor");async function sl(t){try{let{stdout:e}=await ht("pgrep",["-f",il(t)],ft);return tl(e)}catch(e){let n=co(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}i(sl,"discoverPosix");async function io(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${nn}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await ht("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],ft),o=[];for(let a of r.split(`
24
- `)){let s=a.indexOf(" ");if(s===-1)continue;let d=Number(a.slice(0,s).trim()),c=a.slice(s+1);!Number.isInteger(d)||d===process.pid||al(c,t)&&o.push(d)}return o}i(io,"discoverWin32");async function ao(){let{stdout:t}=await ht("ps",["-A","-o","pid=,ppid=,pgid="],ft),e=[];for(let n of t.split(`
25
- `)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[o,a,s]=r,d=Number(o),c=Number(a),g=Number(s);!Number.isInteger(d)||!Number.isInteger(c)||!Number.isInteger(g)||e.push({pid:d,ppid:c,pgid:g})}return e}i(ao,"readProcessTable");function ll(t,e){let n=new Map;for(let c of t){let g=n.get(c.ppid);g===void 0?n.set(c.ppid,[c.pid]):g.push(c.pid)}let r=new Set(e),o=[...e];for(let c=o.pop();c!==void 0;c=o.pop()){let g=n.get(c);if(g!==void 0)for(let y of g)r.has(y)||(r.add(y),o.push(y))}let a=t.find(c=>c.pid===process.pid),s=a===void 0?null:a.pgid,d=new Set;for(let c of t)r.has(c.pid)&&(c.pgid<=0||s!==null&&c.pgid===s||d.add(c.pgid));return r.delete(process.pid),{members:[...r],groups:[...d]}}i(ll,"expandTree");function dl(t){try{return process.kill(t,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}i(dl,"sigkill");async function gt(t){return process.platform==="win32"?ul(t):cl(t)}i(gt,"killProcessTree");async function cl(t){let e=await sl(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await ao(),{members:r,groups:o}=ll(n,e),a=[];for(let c of r)dl(c)==="signalled"&&a.push(c);for(let c of o)try{process.kill(-c,"SIGKILL")}catch(g){if(typeof g!="object"||g===null||g.code!=="ESRCH")throw g}await lo(500);let s=await ao(),d=new Set(s.map(c=>c.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:a,survivorPids:r.filter(c=>d.has(c))}}i(cl,"killProcessTreePosix");async function ul(t){let e=await io(t),n=[];for(let o of e)try{await ht("taskkill.exe",["/T","/F","/PID",String(o)],ft),n.push(o)}catch(a){let s=co(a);if(s===null||s.code!==128)throw a}await lo(500);let r=await io(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}i(ul,"killProcessTreeWin32");var re=m("instance-registry");function wt(t){return typeof t=="string"&&t!==""}i(wt,"isNonEmptyString");function gl(t,e){if(typeof t!="object"||t===null)throw new Error(`[instance-registry] ${e} does not contain a JSON object.`);let n=t;if(n.v!==1)throw new Error(`[instance-registry] ${e} has version ${JSON.stringify(n.v)}, expected 1.`);if(!wt(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!wt(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!wt(n.startedAt)||!wt(n.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof n.agentPid!="number"||!Number.isInteger(n.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:n.runId,agentPid:n.agentPid,userDataDir:n.userDataDir,startedAt:n.startedAt,deadlineAt:n.deadlineAt}}i(gl,"parseInstanceRecord");function wl(t,e){let n=`${t}.tmp`;fl(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),hl(n,t)}i(wl,"writeMarkerAtomically");var yt=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=Le(e,Kr)}get instancesRoot(){return this.#e}userDataDirFor(e){return Le(this.#e,e)}reserve(e,n){uo(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{uo(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new H(e,r,a):a}let o=new Date().toISOString();try{wl(Le(r,ct),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:n})}catch(a){try{rn(r,{recursive:!0,force:!0})}catch(s){re.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:s instanceof Error?s.message:String(s)})}throw a}return re.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:n}}read(e){return this.#n(Le(this.userDataDirFor(e),ct))}release(e){let n=this.userDataDirFor(e);rn(n,{recursive:!0,force:!0}),re.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=ml(this.#e,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return[];throw n}return e.filter(n=>n.isDirectory()).map(n=>n.name)}async sweepOrphans(){let e=new Date().toISOString(),n=[];for(let r of this.listRunIds())n.push(await this.#t(r));return n.length>0?re.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):re.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#t(e){let n=this.userDataDirFor(e),r=Le(n,ct),o=null,a;try{o=this.#n(r),a="valid"}catch(d){a=(typeof d=="object"&&d!==null?d.code:null)==="ENOENT"?"missing":"unreadable",re.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:a,err:d instanceof Error?d.message:String(d)})}let s=await gt(n);return re.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),rn(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:o,kill:s,removed:!0}}#n(e){let n=pl(e,"utf8");return gl(JSON.parse(n),e)}};async function mo(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let o=await q({operation:`read chrome.storage.session['tabStates'] and ['${Ct}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async a=>{let s=await new Promise(w=>chrome.storage.session.get(["tabStates",a],w)),d=s.tabStates,c=typeof d!="object"||d===null?[]:Object.entries(d).map(([w,f])=>{let R=typeof f=="object"&&f!==null?f.playback:null;if(typeof R!="object"||R===null)return{tabId:w,playback:null};let v=R;return{tabId:w,playback:{runId:typeof v.runId=="string"?v.runId:null,status:typeof v.status=="string"?v.status:null,currentStepIndex:typeof v.currentStepIndex=="number"?v.currentStepIndex:null}}}),g=s[a],y=typeof g!="object"||g===null?null:(()=>{let w=g;return{agentJobId:typeof w.agentJobId=="string"?w.agentJobId:null,updatedAt:typeof w.updatedAt=="string"?w.updatedAt:null}})();return{tabs:c,agentJob:y}},Ct),"evaluate")});return{ok:!0,observedAt:e,tabs:o.tabs,agentJob:o.agentJob}}catch(o){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:o instanceof Error?o.message:String(o)}}}i(mo,"probePlaybackSession");async function po(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}i(po,"waitForServiceWorker");async function ho(t,e){let n,r=new Promise((o,a)=>{n=setTimeout(()=>a(new Error(`chrome.runtime.id did not resolve within ${e}ms \u2014 the extension's service worker is not executing`)),e)});try{let o=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof o!="string"||o==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(o)} \u2014 expected a non-empty extension id`);return o}finally{n!==void 0&&clearTimeout(n)}}i(ho,"readRuntimeId");function _t(t,e){let n=t-Date.now();if(n<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return n}i(_t,"remainingBudgetMs");async function go(t){let e=Date.now(),n=e+45e3,r=n-5e3,o=await po(t,Math.min(5e3,_t(r,"the service-worker target wait")));try{let a=await ho(o,_t(r,"the first readiness evaluate"));return{worker:o,extensionId:a,serviceWorkerUrl:o.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(a){let s=await t.newPage();try{let d=await po(t,Math.min(5e3,_t(n,"the retry service-worker target wait"))),c=await ho(d,_t(n,"the retry readiness evaluate"));return{worker:d,extensionId:c,serviceWorkerUrl:d.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(d){let c=a instanceof Error?a.message:String(a),g=d instanceof Error?d.message:String(d);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${c}. Page-open retry: ${g}.`,{cause:d})}finally{await s.close()}}}i(go,"probeExtensionReadiness");var S=m("playwright-execution-runtime"),sn=class extends Error{static{i(this,"LaunchAbortedError")}runId;constructor(e){super(`[runtime] launch of run ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being published (CONTRACT-la \xA715 A3, A19.1).`),this.name="LaunchAbortedError",this.runId=e}},Et=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#o;#a;#s;#r=null;#i=null;#m=!1;#c=null;#l=null;constructor(e){Yr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#o=e.onInstanceLost,this.#a=new yt(e.stateDir),this.#s=ro(e.extensionDist),S.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#r;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#r;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:mo(e.context)}async startRun(e){let n=this.#r;if(n!==null)throw new pt(e.runId,n.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await J(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,o));this.#l?.runId===e.runId&&(this.#l=null);let s={runId:e.runId,userDataDir:a.userDataDir,context:null,disposeRequested:!1};this.#i=s;let d=this.#h(e),c=e.command.kind==="swarm";S.info("Launching browser for run",{runId:e.runId,headful:d,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:c,userDataDir:a.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:o,envFingerprint:this.#s});let g=null;try{let y=await J(e.runId,"browser_launch",()=>Vr({userDataDir:a.userDataDir,extensionDist:this.#e,headful:d,allowInsecureHttps:this.#n,keepBackgroundWindowsRendering:c}));g=y,s.context=y,this.#d(s);let w=await J(e.runId,"browser_version",()=>Hr(y)),f=await J(e.runId,"readiness_probe",()=>go(y));await this.#f(e,f.worker),await J(e.runId,"entry_navigation",()=>El(y,e)),await this.#p(e,y);let R={runId:e.runId,context:g,userDataDir:a.userDataDir,headful:d,extensionId:f.extensionId,chromeVersion:w,startedAt:a.startedAt,deadlineAt:o};this.#d(s),this.#u(R),this.#r=R,this.#i===s&&(this.#i=null),S.info("Run launched",{runId:e.runId,chromeVersion:w,extensionId:f.extensionId,readinessAttempts:f.attempts,readyAfterMs:f.readyAfterMs,launchDurationMs:Date.now()-r})}catch(y){throw this.#i===s&&(this.#i=null),await this.#g({runId:e.runId,context:g,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:s.disposeRequested?"dispose_during_launch":"launch_failure"}),y}finally{this.#i===s&&(this.#i=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let r=this.#c;if(r!==null&&r.runId===e)return S.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let o=this.#i;if(o!==null&&o.runId===e)return o.disposeRequested=!0,S.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:o.userDataDir,contextPresent:o.context!==null}),this.#g({runId:e,context:o.context,userDataDir:o.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let a=this.#r;return a===null||a.runId!==e?this.#w(e):(this.#r=null,this.#g({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#h(e){return e.headful||this.#t}async#f(e,n){let r=await J(e.runId,"token_seed",()=>Qr(n,e.extensionSession));S.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await J(e.runId,"command_seed",()=>eo(n,e.command)),S.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#p(e,n){let r=await J(e.runId,"command_ack",()=>to(n,e.runId,15e3));if(r.outcome==="rejected")throw new V(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);S.info("Command envelope dispatched by the extension",{runId:e.runId})}#d(e){if(e.disposeRequested)throw new sn(e.runId)}#u(e){let n=i(o=>{if(this.#m||this.#r?.runId!==e.runId)return;this.#r=null;let a=this.#g({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#c={runId:e.runId,promise:a},a.catch(d=>{S.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:d instanceof Error?d.message:String(d)})}).finally(()=>{this.#c?.promise===a&&(this.#c=null)});let s={runId:e.runId,at:new Date().toISOString(),source:o};S.error("Browser instance disappeared without a dispose",{...s}),this.#o(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#l;if(n===null||n.runId!==e)return S.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#r===null?null:this.#r.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return S.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;if(!n.killConfirmed)throw S.error("Dispose repeated for a run whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:e,disposeOutcome:n.result.outcome,kill:n.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for run ${e} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();S.warn("Dispose repeated for a run whose instance directory survived \u2014 retrying",{runId:e,disposeOutcome:n.result.outcome}),this.#a.release(e);let o={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#l={runId:e,result:o,killConfirmed:!0},S.info("Instance released on a repeated dispose",{runId:e,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}async#g(e){let n=Date.now();this.#m=!0;let r="closed",o=null,a=null;try{if(e.context!==null){let f=await Jr(e.context,e.timeoutMs);f.settled==="closed"?r="closed":f.settled==="timeout"?(r="timeout-force-killed",S.error("context.close() did not settle before the deadline \u2014 force-killing",{runId:e.runId,timeoutMs:e.timeoutMs,userDataDir:e.userDataDir})):(r="close-failed-force-killed",S.error("context.close() rejected \u2014 force-killing",{runId:e.runId,userDataDir:e.userDataDir,err:f.error instanceof Error?f.error.message:String(f.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await gt(e.userDataDir)}catch(f){a=f,S.error("Force-kill of the run process tree failed",{runId:e.runId,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:f instanceof Error?f.message:String(f)})}let d=a===null&&(o===null||o.survivorPids.length===0),c=null,g=!1;if(d)try{this.#a.release(e.runId),g=!0}catch(f){c=f,S.error("Failed to remove the instance directory after teardown",{runId:e.runId,userDataDir:e.userDataDir,err:f instanceof Error?f.message:String(f)})}else S.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.runId,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:a!==null,survivorPids:o===null?null:o.survivorPids});let y={runId:e.runId,outcome:r,kill:o,instanceReleased:g,durationMs:Date.now()-n};this.#l={runId:e.runId,result:y,killConfirmed:d};let w={runId:y.runId,disposeOutcome:y.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:y.kill,killFailed:a!==null,instanceReleased:y.instanceReleased,durationMs:y.durationMs};if(a!==null||c!==null?S.error("Instance disposed with a failed cleanup step",w):S.info("Instance disposed",w),c!==null)throw c;if(a!==null)throw a;if(o!==null&&o.survivorPids.length>0)throw new Error(`[runtime] force-kill for run ${e.runId} left ${o.survivorPids.length} process(es) alive after the settle delay (${o.survivorPids.join(", ")}). The instance directory ${e.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`);return y}finally{this.#m=!1}}};async function J(t,e,n){try{return await n()}catch(r){throw r instanceof V||r instanceof H?r:new V(t,e,r instanceof Error?r.message:String(r),r)}}i(J,"stage");async function El(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"domcontentloaded"})}i(El,"navigateToEntry");import{setTimeout as Rl}from"node:timers/promises";function oe(t,e=Math.random){if(t<0)throw new Error(`[backoff] attempt must be >= 0, got ${t}. Pass 0 for the first reconnect after a disconnect.`);let n=Math.min(6e4,1e3*Math.pow(2,Math.min(t,26)));return Math.floor(e()*n)}i(oe,"computeBackoffDelayMs");function Se(t){let e=Sl(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:oe(t.attempt,t.rng)}}i(Se,"decideGatewayRetry");function Sl(t){if(t instanceof E)return"terminal_signal";if(t instanceof j)return"contract_breach";if(t instanceof T)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof F||t instanceof pe)return null;if(t instanceof b)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}i(Sl,"classifyFailure");var Y=m("supervisor-identity");async function Re(t){let{config:e}=t;if(e.initialToken!==void 0)return bl(e,e.initialToken);let n=$(e.stateDir);if(n!==null)return Al(n.serverUrl,e.serverUrl),Y.info("Agent identity loaded from the state file",{agentId:n.agentId}),{agentToken:n.agentToken,agentId:n.agentId,pollWaitSec:void 0,source:"state_file"};if(e.enrollmentCode!==void 0)return Tl(t,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
20
+ For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}i(an,"bundledMissingMessage");function Wa(n){let{stateDir:e,agentId:t}=n;if(t==="")throw new Error(`[extension-dist] agentId is required: ${dn} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=n.sourceDir??ja(),o=ge(e,Dr),s=ge(e,`${Lr}${process.pid}`);return Ca(e,{recursive:!0,mode:448}),Ja(e),ln(s,{recursive:!0,force:!0}),Pa(r,s,{recursive:!0}),Na(s,448),Ka(s,t),ln(o,{recursive:!0,force:!0}),La(s,o),st.info("Agent-mode extension dist prepared",{extensionDist:o,sourceDir:r,agentId:t,protocolVersion:1}),o}i(Wa,"prepareAgentExtensionDist");function Ka(n,e){let t={agentMode:!0,agentId:e,protocolVersion:1};Ga(ge(n,dn),JSON.stringify(t,null,2)+`
21
+ `,"utf8")}i(Ka,"writeAgentManifest");function Ja(n){let e;try{e=Da(n,{withFileTypes:!0})}catch(t){if(typeof t=="object"&&t!==null&&t.code==="ENOENT")return;throw t}for(let t of e){if(!t.name.startsWith(Lr))continue;let r=ge(n,t.name);try{ln(r,{recursive:!0,force:!0}),st.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(o){st.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:o instanceof Error?o.message:String(o)})}}}i(Ja,"removeLeftoverStagingDirs");function Gr(n){if(n.overridePath!==void 0)return st.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:n.overridePath}),n.overridePath;if(n.agentId===null)throw new Error(`[extension-dist] Cannot prepare the agent-mode extension dist: this daemon authenticated with PROGON_AGENT_TOKEN, which carries no agentId, and ${dn} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
22
+ Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return Wa({stateDir:n.stateDir,agentId:n.agentId})}i(Gr,"resolveExtensionDist");import{fetch as Ha}from"undici";var k=class extends Error{static{i(this,"GatewayError")}operation;constructor(e,t,r){super(t,{cause:r}),this.name=new.target.name,this.operation=e}},j=class extends k{static{i(this,"GatewayTransportError")}constructor(e,t,r){super(e,`[gateway] ${e} failed before a response was received: ${t}`,r)}},R=class extends k{static{i(this,"GatewayHttpError")}status;errorCode;params;constructor(e,t,r,o,s){super(e,`[gateway] ${e} refused with HTTP ${t}: ${s}`),this.status=t,this.errorCode=r,this.params=o}},we=class extends R{static{i(this,"GatewayUnauthorizedError")}},S=class extends R{static{i(this,"TokenSupersededError")}},E=class extends k{static{i(this,"TerminalSignalError")}signal;constructor(e,t,r){super(e,`[gateway] agent revoked (${t}) during ${e}: ${r}`),this.signal=t}},at=class extends R{static{i(this,"EnrollmentCodeRejectedError")}},je=class extends R{static{i(this,"ProtocolVersionMismatchError")}},ye=class extends R{static{i(this,"RunNotClaimableError")}},oe=class extends R{static{i(this,"RunNotFoundError")}},B=class extends k{static{i(this,"GatewayResponseSchemaError")}constructor(e,t,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${t}`,r)}};var Ur=p("gateway-http");async function ie(n){let e={accept:"application/json"};n.agentToken!==null&&(e.authorization=`Bearer ${n.agentToken}`),n.body!==null&&(e["content-type"]="application/json"),Ur.debug("Gateway request",{operation:n.operation,method:n.method,url:n.url.toString()});let t;try{t=await n.fetchImpl(n.url,{method:n.method,headers:e,body:n.body===null?void 0:JSON.stringify(n.body),signal:n.signal})}catch(o){throw new j(n.operation,Mr(o),o)}let r;try{r=await t.text()}catch(o){throw new j(n.operation,Mr(o),o)}if(!t.ok){let o=qa(t.status,r);throw Ur.debug("Gateway request refused",{operation:n.operation,status:o.status,errorCode:o.errorCode}),n.mapHttpError(o)}try{return JSON.parse(r)}catch(o){throw new B(n.operation,`the ${t.status} response body is not valid JSON`,o)}}i(ie,"executeGatewayRequest");function O(n,e){if(e.success)return e.data;throw new B(n,Va(e.error),e.error)}i(O,"parseGatewayBody");function qa(n,e){let t;try{t=JSON.parse(e)}catch{return{status:n,errorCode:null,params:null,message:cn}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:n,errorCode:null,params:null,message:cn};let r=t,o=r.error_code,s=r.params,a=r.message;return{status:n,errorCode:typeof o=="string"?o:null,params:typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,message:typeof a=="string"?$(a):cn}}i(qa,"readErrorEnvelope");var cn="the response body carried no Progon error envelope";function Mr(n){return $(n instanceof Error?n.message:String(n))}i(Mr,"describeCause");function Va(n){let e=n.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let t=e.map(r=>{let o=r.path;return!Array.isArray(o)||o.length===0?"<root>":o.map(s=>String(s)).join(".")});return`${e.length} schema violation(s) at: ${t.join(", ")}`}i(Va,"summarizeSchemaViolation");var _e=class extends R{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,t,r,o,s,a){super(e,t,r,o,s),this.retryAfterSec=a}},Ee=class extends R{static{i(this,"EnrollmentAccessDeniedError")}},Se=class extends R{static{i(this,"EnrollmentRequestExpiredError")}},Re=class extends R{static{i(this,"EnrollmentAlreadyCompletedError")}},ke=class extends R{static{i(this,"EnrollmentRequestInvalidError")}};function $r(n){return n.status===401&&n.errorCode==="agent_enroll.invalid_code"?N(at,"enroll",n):n.status===409&&n.errorCode==="agent_enroll.protocol_version"?N(je,"enroll",n):D("enroll",n)}i($r,"mapEnrollError");function Fr(n){return n.status===409&&n.errorCode==="agent_enroll.protocol_version"?N(je,"enrollment_request_create",n):D("enrollment_request_create",n)}i(Fr,"mapEnrollmentRequestCreateError");function jr(n){if(n.status===429&&n.errorCode==="agent_enroll.slow_down"){let e=n.params===null?void 0:n.params.retryAfterSeconds,t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new _e("enrollment_request_poll",n.status,n.errorCode,n.params,n.message,t)}return n.status===403&&n.errorCode==="agent_enroll.access_denied"?N(Ee,"enrollment_request_poll",n):n.status===410&&n.errorCode==="agent_enroll.expired"?N(Se,"enrollment_request_poll",n):n.status===410&&n.errorCode==="agent_enroll.already_completed"?N(Re,"enrollment_request_poll",n):n.status===401&&n.errorCode==="agent_enroll.invalid_request"?N(ke,"enrollment_request_poll",n):D("enrollment_request_poll",n)}i(jr,"mapEnrollmentRequestPollError");function Br(n){return D("enrollment_request_cancel",n)}i(Br,"mapEnrollmentRequestCancelError");function Wr(n){return H("poll_desired_state",n,()=>D("poll_desired_state",n))}i(Wr,"mapPollDesiredStateError");function Kr(n){return H("claim",n,()=>n.status===409&&n.errorCode==="run.not_claimable"?N(ye,"claim",n):n.status===404?N(oe,"claim",n):D("claim",n))}i(Kr,"mapClaimError");function Jr(n){return H("fail",n,()=>n.status===404?N(oe,"fail",n):D("fail",n))}i(Jr,"mapFailError");function qr(n){return H("token_status",n,()=>D("token_status",n))}i(qr,"mapTokenStatusError");function Vr(n){return H("token_rotate",n,()=>D("token_rotate",n))}i(Vr,"mapTokenRotateError");function Hr(n){return H("declare_capabilities",n,()=>D("declare_capabilities",n))}i(Hr,"mapDeclareCapabilitiesError");function Yr(n){return H("identity_session",n,()=>D("identity_session",n))}i(Yr,"mapIdentitySessionError");function Xr(n){return H("launch_session",n,()=>D("launch_session",n))}i(Xr,"mapLaunchSessionError");function H(n,e,t){return e.status===403&&e.errorCode==="agents.revoked"?new E(n,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?N(S,n,e):e.status===401?N(we,n,e):t()}i(H,"bearerRoute");function N(n,e,t){return new n(e,t.status,t.errorCode,t.params,t.message)}i(N,"named");function D(n,e){return N(R,n,e)}i(D,"generic");var lt=[...xn,An,On,Pn,Nn,Cn];import{z as se}from"zod";var zr=se.object({rotationDue:se.boolean(),tokenRotatedAt:se.string().nullable(),anchorAt:se.string(),intervalDays:se.number().int()}),Zr=se.object({agentToken:se.string().regex(de)});var dt=p("gateway-client"),Ya="/api/agent-gateway";function P(n,e){return new URL(`${n.replace(/\/+$/,"")}${Ya}${e}`)}i(P,"buildGatewayUrl");var Qr=3e5,to=1e4,eo={headersTimeout:Qr,bodyTimeout:Qr,connect:{timeout:to}};function Xa(){let n=ur(process.env);return ar(rn(process.env),n===void 0?eo:{...eo,connect:{timeout:to,ca:n}},n)}i(Xa,"buildGatewayDispatcher");var un,pt=i((n,e)=>{if(un===void 0){let t=Xa();un=i((r,o)=>Ha(r,{...o,dispatcher:t}),"defaultGatewayFetch")}return un(n,e)},"pinnedGatewayFetch"),ct=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??pt}async enroll(e){let t={...this.machine,enrollmentCode:e,protocolVersion:1},r=await ie({operation:"enroll",method:"POST",url:P(this.serverUrl,"/enroll"),agentToken:null,body:t,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:$r}),o=O("enroll",Ye.safeParse(r));return dt.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},ut=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??pt}async authenticatedRequest(e){return ie({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let t=P(this.serverUrl,"/state");e?.waitSec!==void 0&&t.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:t,body:null,signal:e?.signal,mapHttpError:Wr}),o=O("poll_desired_state",Jn.safeParse(r));if(o.agent.revoked)throw new E("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return o}async claimRun(e){let t=await this.authenticatedRequest({operation:"claim",method:"POST",url:P(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:lt},signal:void 0,mapHttpError:Kr});return O("claim",Xn.safeParse(t))}async issueIdentitySession(e,t){let r=await this.authenticatedRequest({operation:"identity_session",method:"POST",url:P(this.serverUrl,`/runs/${encodeURIComponent(e)}/identities/${encodeURIComponent(t)}/session`),body:null,signal:void 0,mapHttpError:Yr});return O("identity_session",Zt.safeParse(r)).extensionSession}async issueLaunchSession(e,t){let r=await this.authenticatedRequest({operation:"launch_session",method:"POST",url:P(this.serverUrl,`/runs/${encodeURIComponent(e)}/launches/${encodeURIComponent(t)}/session`),body:null,signal:void 0,mapHttpError:Xr});return O("launch_session",Zt.safeParse(r)).extensionSession}async failRun(e,t){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:P(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:t,signal:void 0,mapHttpError:Jr}),o=O("fail",Hn.safeParse(r));return dt.info("Reported run failure to the gateway",{runId:e,reason:t.reason,status:o.status}),o}async getTokenRotationStatus(e){let t=await this.authenticatedRequest({operation:"token_status",method:"GET",url:P(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:qr});return O("token_status",zr.safeParse(t))}async rotateToken(e){let t=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:P(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Vr});return O("token_rotate",Zr.safeParse(t))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:P(this.serverUrl,"/capabilities"),body:{capabilities:lt},signal:e?.signal,mapHttpError:Hr}),dt.info("Capabilities declared",{capabilities:lt})}useAgentToken(e){this.agentToken=e,dt.info("Adopted a rotated agent token for all subsequent gateway requests")}};var za=p("debug-env-guard"),Za=["pw:protocol","pw:api"];function Qa(n){return n.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(Qa,"escapeRegExp");function no(n){if(n.startsWith("-"))return!1;let e=`^${n.split("*").map(Qa).join(".*?")}$`,t=new RegExp(e);return Za.some(r=>t.test(r))}i(no,"enablesPlaywright");function el(){let n=process.env.DEBUG;if(n===void 0||n==="")return[];let e=n.split(/[\s,]+/).map(o=>o.trim()).filter(o=>o!==""),t=e.filter(o=>no(o));if(t.length===0)return[];let r=e.filter(o=>!no(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),za.warn("Playwright debug namespaces removed from DEBUG before playwright-core loaded",{removed:t,kept:r,debugFile:process.env.DEBUG_FILE??null,reason:"pw: namespaces write raw CDP messages \u2014 including the per-run session tokens sent to chrome.storage.local \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),t}i(el,"sanitizePlaywrightDebugEnv");el();import{statSync as io}from"node:fs";import{isAbsolute as nl,join as rl}from"node:path";import{createRequire as tl}from"node:module";var W=tl(import.meta.url)("playwright-core"),ht=W.chromium,am=W.firefox,lm=W.webkit,dm=W.selectors,cm=W.devices,ro=W.errors,um=W.request,pm=W._electron,hm=W._android;var mt="chromium";var oo="instances",ft="instance.json";var ol=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"];async function so(n){return ht.launchPersistentContext(n.userDataDir,{headless:!n.headful,channel:mt,ignoreHTTPSErrors:n.allowInsecureHttps,args:[`--disable-extensions-except=${n.extensionDist}`,`--load-extension=${n.extensionDist}`,"--no-first-run","--no-default-browser-check",...n.keepBackgroundWindowsRendering?ol:[]]})}i(so,"launchExtensionContext");function il(n){let e=n.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}i(il,"requireBrowser");function ao(n){return il(n).version()}i(ao,"readChromeVersion");async function lo(n,e){let t,r=new Promise(o=>{t=setTimeout(()=>o({settled:"timeout"}),e)});try{return await Promise.race([n.close().then(()=>({settled:"closed"}),o=>({settled:"rejected",error:o})),r])}finally{t!==void 0&&clearTimeout(t)}}i(lo,"raceClose");function co(n){if(!nl(n))throw new Error(`[runtime] The extension dist path must be absolute, got ${JSON.stringify(n)}. A relative path would be resolved against the daemon's working directory.`);let e;try{e=io(n)}catch(r){throw new Error(`[runtime] The extension dist directory ${n} cannot be read. Chromium does NOT fail on a bad --load-extension: it would start without the extension and every run would time out in the readiness probe. Check PROGON_AGENT_EXTENSION_DIST (CONTRACT-la \xA78).`,{cause:r})}if(!e.isDirectory())throw new Error(`[runtime] The extension dist path ${n} is not a directory.`);let t=rl(n,"manifest.json");try{io(t)}catch(r){throw new Error(`[runtime] ${t} is missing, so ${n} is not a built extension. Build qa-extension, or point PROGON_AGENT_EXTENSION_DIST at a real dist.`,{cause:r})}}i(co,"assertUsableExtensionDist");var sl=p("worker-evaluate"),pn=class extends Error{static{i(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,t){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${t}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=t}};async function Y(n){let e=n.evaluate(),t=!1;e.catch(s=>{t&&sl.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:n.operation,timeoutMs:n.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,o=new Promise((s,a)=>{r=setTimeout(()=>{t=!0,a(new pn(n.operation,n.timeoutMs))},n.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(Y,"evaluateWithDeadline");var uo="accessToken",po="refreshToken";async function mo(n,e){await Y({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>n.evaluate(([r,o,s,a])=>new Promise(l=>chrome.storage.local.set({[r]:s,[o]:a},()=>l())),[uo,po,e.accessToken,e.refreshToken]),"evaluate")});let t=await Y({operation:"read the run session back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>n.evaluate(([r,o])=>new Promise(s=>chrome.storage.local.get([r,o],a=>{let l=a[r],c=a[o];s({accessTokenLength:typeof l=="string"?l.length:null,refreshTokenLength:typeof c=="string"?c.length:null})})),[uo,po]),"evaluate")});if(t.accessTokenLength!==e.accessToken.length||t.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: chrome.storage.local holds accessToken(len=${String(t.accessTokenLength)}), refreshToken(len=${String(t.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return t}i(mo,"seedRunSession");function ho(n){return JSON.stringify(Object.keys(n).sort().map(e=>[e,n[e]]))}i(ho,"canonicalise");async function fo(n,e){await Y({operation:`write the command envelope to chrome.storage.local['${Ue}']`,timeoutMs:1e4,evaluate:i(()=>n.evaluate(([s,a])=>new Promise(l=>chrome.storage.local.set({[s]:a},()=>l())),[Ue,e]),"evaluate")});let t=await Y({operation:"read the command envelope back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>n.evaluate(s=>new Promise(a=>chrome.storage.local.get([s],l=>{let c=l[s];a(c===void 0?null:c)})),Ue),"evaluate")});if(typeof t!="object"||t===null)throw new Error(`command envelope read-back returned ${JSON.stringify(t)} \u2014 chrome.storage.local['${Ue}'] does not hold the envelope`);let r=ho({...e}),o=ho(t);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(fo,"seedCommandEnvelope");async function ll(n,e,t){let r=await Y({operation:`read chrome.storage.local['${He}']`,timeoutMs:t,evaluate:i(()=>n.evaluate(s=>new Promise(a=>chrome.storage.local.get([s],l=>{let c=l[s];a(c===void 0?null:c)})),He),"evaluate")});if(r===null)return{kind:"absent"};let o=qn.safeParse(r);return o.success?o.data.runId!==e?{kind:"other_run",detail:`the ack under that key belongs to run ${o.data.runId}`}:{kind:"ack",ack:o.data}:{kind:"invalid",detail:`the value under that key failed agentCommandAckSchema: ${String(o.error)}`}}i(ll,"pollCommandAck");async function go(n,e,t){let r=Date.now()+t,o="no ack was written";for(;;){let s=r-Date.now();if(s<=0)throw new Error(`no command ack for run ${e} within ${t}ms \u2014 ${o}. chrome.storage.local['${He}'] is the only success signal (CONTRACT-la \xA75.4).`);let a=n.serviceWorkers()[0];if(a===void 0)o="the context exposed no service worker while polling (evicted, restarting)";else{let l;try{l=await ll(a,e,s)}catch(c){o=`the last poll failed: ${c instanceof Error?c.message:String(c)}`,l={kind:"invalid",detail:o}}if(l.kind==="ack")return l.ack;l.kind!=="absent"&&(o=l.detail)}await new Promise(l=>setTimeout(l,250))}}i(go,"waitForCommandAck");import{execFile as cl}from"node:child_process";import{promisify as ul}from"node:util";import{setTimeout as Eo}from"node:timers/promises";var wt=ul(cl),yt={timeout:5e3};function So(n){if(typeof n!="object"||n===null)return null;let e=n;return typeof e.code!="number"?null:{code:e.code,stdout:typeof e.stdout=="string"?e.stdout:"",stderr:typeof e.stderr=="string"?e.stderr:""}}i(So,"asExecFailure");function pl(n){let e=[];for(let t of n.split(`
23
+ `)){let r=t.trim();if(r==="")continue;let o=Number(r);!Number.isInteger(o)||o===process.pid||e.push(o)}return e}i(pl,"parsePidLines");var hn="--user-data-dir=",hl=new Set([" "," ",'"',"'"]),ml=new Set([" "," ",'"',"'"]);function fl(n){return n.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}i(fl,"escapeEre");function gl(n){return`(^|[[:space:]'"])${fl(`${hn}${n}`)}([[:space:]'"]|$)`}i(gl,"buildAnchorPattern");function wl(n,e){let t=n.toLowerCase(),r=`${hn}${e}`.toLowerCase();for(let o=t.indexOf(r);o!==-1;o=t.indexOf(r,o+1)){let s=o===0?void 0:t[o-1],a=t[o+r.length],l=s===void 0||hl.has(s),c=a===void 0||ml.has(a);if(l&&c)return!0}return!1}i(wl,"matchesAnchor");async function yl(n){try{let{stdout:e}=await wt("pgrep",["-f",gl(n)],yt);return pl(e)}catch(e){let t=So(e);if(t!==null&&t.code===1&&t.stdout.trim()==="")return[];throw e}}i(yl,"discoverPosix");async function wo(n){let t=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${hn}${n}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await wt("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],yt),o=[];for(let s of r.split(`
24
+ `)){let a=s.indexOf(" ");if(a===-1)continue;let l=Number(s.slice(0,a).trim()),c=s.slice(a+1);!Number.isInteger(l)||l===process.pid||wl(c,n)&&o.push(l)}return o}i(wo,"discoverWin32");async function yo(){let{stdout:n}=await wt("ps",["-A","-o","pid=,ppid=,pgid="],yt),e=[];for(let t of n.split(`
25
+ `)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let[o,s,a]=r,l=Number(o),c=Number(s),w=Number(a);!Number.isInteger(l)||!Number.isInteger(c)||!Number.isInteger(w)||e.push({pid:l,ppid:c,pgid:w})}return e}i(yo,"readProcessTable");function _l(n,e){let t=new Map;for(let c of n){let w=t.get(c.ppid);w===void 0?t.set(c.ppid,[c.pid]):w.push(c.pid)}let r=new Set(e),o=[...e];for(let c=o.pop();c!==void 0;c=o.pop()){let w=t.get(c);if(w!==void 0)for(let f of w)r.has(f)||(r.add(f),o.push(f))}let s=n.find(c=>c.pid===process.pid),a=s===void 0?null:s.pgid,l=new Set;for(let c of n)r.has(c.pid)&&(c.pgid<=0||a!==null&&c.pgid===a||l.add(c.pgid));return r.delete(process.pid),{members:[...r],groups:[...l]}}i(_l,"expandTree");function El(n){try{return process.kill(n,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}i(El,"sigkill");async function _t(n){return process.platform==="win32"?Rl(n):Sl(n)}i(_t,"killProcessTree");async function Sl(n){let e=await yl(n);if(e.length===0)return{platform:process.platform,userDataDir:n,discoveredPids:[],signalledPids:[],survivorPids:[]};let t=await yo(),{members:r,groups:o}=_l(t,e),s=[];for(let c of r)El(c)==="signalled"&&s.push(c);for(let c of o)try{process.kill(-c,"SIGKILL")}catch(w){if(typeof w!="object"||w===null||w.code!=="ESRCH")throw w}await Eo(500);let a=await yo(),l=new Set(a.map(c=>c.pid));return{platform:process.platform,userDataDir:n,discoveredPids:e,signalledPids:s,survivorPids:r.filter(c=>l.has(c))}}i(Sl,"killProcessTreePosix");async function Rl(n){let e=await wo(n),t=[];for(let o of e)try{await wt("taskkill.exe",["/T","/F","/PID",String(o)],yt),t.push(o)}catch(s){let a=So(s);if(a===null||a.code!==128)throw s}await Eo(500);let r=await wo(n);return{platform:"win32",userDataDir:n,discoveredPids:e,signalledPids:t,survivorPids:r}}i(Rl,"killProcessTreeWin32");async function Ro(n,e){let r=n.serviceWorkers()[0];return r!==void 0?r:n.waitForEvent("serviceworker",{timeout:e})}i(Ro,"waitForServiceWorker");async function ko(n,e){let t,r=new Promise((o,s)=>{t=setTimeout(()=>s(new Error(`chrome.runtime.id did not resolve within ${e}ms \u2014 the extension's service worker is not executing`)),e)});try{let o=await Promise.race([n.evaluate(()=>chrome.runtime.id),r]);if(typeof o!="string"||o==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(o)} \u2014 expected a non-empty extension id`);return o}finally{t!==void 0&&clearTimeout(t)}}i(ko,"readRuntimeId");function Et(n,e){let t=n-Date.now();if(t<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return t}i(Et,"remainingBudgetMs");async function vo(n){let e=Date.now(),t=e+45e3,r=t-5e3,o=await Ro(n,Math.min(5e3,Et(r,"the service-worker target wait")));try{let s=await ko(o,Et(r,"the first readiness evaluate"));return{worker:o,extensionId:s,serviceWorkerUrl:o.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(s){let a=await n.newPage();try{let l=await Ro(n,Math.min(5e3,Et(t,"the retry service-worker target wait"))),c=await ko(l,Et(t,"the retry readiness evaluate"));return{worker:l,extensionId:c,serviceWorkerUrl:l.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(l){let c=s instanceof Error?s.message:String(s),w=l instanceof Error?l.message:String(l);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${c}. Page-open retry: ${w}.`,{cause:l})}finally{await a.close()}}}i(vo,"probeExtensionReadiness");var X=class extends Error{static{i(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,t,r,o){super(`[runtime] launch failed at stage ${t} for run ${e}: ${r}`,{cause:o}),this.name="RuntimeLaunchError",this.runId=e,this.stage=t}};function fn(n){let e=new Set,t=n;for(;t instanceof Error&&!e.has(t)&&(e.add(t),t.cause!==void 0);)t=t.cause;return t instanceof Error?t.message:String(t)}i(fn,"deepestCauseMessage");var kl=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),bl=/\bnet::(ERR_[A-Z0-9_]+)\b/;function To(n){if(vl(n))return"timeout";let e=bl.exec(fn(n))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":kl.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}i(To,"entryFailureOf");function vl(n){let e=new Set,t=n;for(;t instanceof Error&&!e.has(t);){if(t instanceof ro.TimeoutError)return!0;e.add(t),t=t.cause}return!1}i(vl,"causeChainHasTimeout");var z=class extends Error{static{i(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,t,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${t}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=t}},St=class extends Error{static{i(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,t){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${t}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=t}};var C=p("browser-instance");async function Rt(n){let e=await G(n.runId,"browser_launch",()=>so({userDataDir:n.userDataDir,extensionDist:n.extensionDist,headful:n.headful,allowInsecureHttps:n.allowInsecureHttps,keepBackgroundWindowsRendering:n.keepBackgroundWindowsRendering}));n.onContext(e),n.assertNotAborted();let t=await G(n.runId,"browser_version",()=>ao(e)),r=await G(n.runId,"readiness_probe",()=>vo(e));return await Il(n,r.worker),await G(n.runId,"entry_navigation",()=>Ol(e,n.entryUrl)),await xl(n,e),{context:e,chromeVersion:t,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}i(Rt,"bringUpBrowser");async function Il(n,e){let t=await G(n.runId,"token_seed",()=>mo(e,n.extensionSession));C.info("Run session seeded into the browser profile",{runId:n.runId,userDataDir:n.userDataDir,accessTokenLength:t.accessTokenLength,refreshTokenLength:t.refreshTokenLength}),await G(n.runId,"command_seed",()=>fo(e,n.command)),C.info("Command envelope seeded",{runId:n.runId,userDataDir:n.userDataDir,command:n.command})}i(Il,"seed");async function xl(n,e){let t=await G(n.runId,"command_ack",()=>go(e,n.runId,15e3));if(t.outcome==="rejected")throw new X(n.runId,"command_ack",`the extension refused the command envelope: ${t.reason}`);C.info("Command envelope dispatched by the extension",{runId:n.runId,userDataDir:n.userDataDir,kind:n.command.kind})}i(xl,"awaitDispatchAck");async function Be(n,e){let t=Date.now(),r="closed",o=null,s=null;if(e.context!==null){let m=await lo(e.context,e.timeoutMs);m.settled==="closed"?r="closed":m.settled==="timeout"?(r="timeout-force-killed",C.error("context.close() did not settle before the deadline \u2014 force-killing",{runId:e.instanceKey,timeoutMs:e.timeoutMs,userDataDir:e.userDataDir})):(r="close-failed-force-killed",C.error("context.close() rejected \u2014 force-killing",{runId:e.instanceKey,userDataDir:e.userDataDir,err:m.error instanceof Error?m.error.message:String(m.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await _t(e.userDataDir)}catch(m){s=m,C.error("Force-kill of the run process tree failed",{runId:e.instanceKey,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:m instanceof Error?m.message:String(m)})}let l=s===null&&(o===null||o.survivorPids.length===0),c=null,w=!1;if(l)try{n.release(e.instanceKey),w=!0}catch(m){c=m,C.error("Failed to remove the instance directory after teardown",{runId:e.instanceKey,userDataDir:e.userDataDir,err:m instanceof Error?m.message:String(m)})}else C.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.instanceKey,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:s!==null,survivorPids:o===null?null:o.survivorPids});let f={runId:e.instanceKey,outcome:r,kill:o,instanceReleased:w,durationMs:Date.now()-t},g={runId:f.runId,disposeOutcome:f.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:f.kill,killFailed:s!==null,instanceReleased:f.instanceReleased,durationMs:f.durationMs};return s!==null||c!==null?C.error("Instance disposed with a failed cleanup step",g):C.info("Instance disposed",g),{result:f,killConfirmed:l,failure:Al(e,o,s,c)}}i(Be,"tearDownBrowser");function kt(n,e){let{instanceKey:t}=e;if(!e.killConfirmed)throw C.error("Dispose repeated for an instance whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:t,disposeOutcome:e.result.outcome,kill:e.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for ${t} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();C.warn("Dispose repeated for an instance whose directory survived \u2014 retrying",{runId:t,disposeOutcome:e.result.outcome}),n.release(t);let o={...e.result,instanceReleased:!0,durationMs:Date.now()-r};return C.info("Instance released on a repeated dispose",{runId:t,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}i(kt,"retryRetainedRelease");function Al(n,e,t,r){return r!==null?Io(r):t!==null?Io(t):e!==null&&e.survivorPids.length>0?new Error(`[runtime] force-kill for run ${n.instanceKey} left ${e.survivorPids.length} process(es) alive after the settle delay (${e.survivorPids.join(", ")}). The instance directory ${n.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`):null}i(Al,"teardownFailure");function Io(n){return n instanceof Error?n:new Error(String(n))}i(Io,"asError");async function G(n,e,t){try{return await t()}catch(r){throw r instanceof X||r instanceof z?r:new X(n,e,r instanceof Error?r.message:String(r),r)}}i(G,"stage");async function Ol(n,e){let t=n.pages()[0];await(t===void 0?await n.newPage():t).goto(e,{waitUntil:"domcontentloaded"})}i(Ol,"navigateToEntry");import bt from"node:os";import{createRequire as Nl}from"node:module";var xo=Nl(import.meta.url);function Pl(){let n=xo.resolve("playwright-core/package.json"),e=xo(n);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${n} did not parse into an object.`);let t=e.version;if(typeof t!="string"||t==="")throw new Error(`[runtime] ${n} declares no version string.`);return t}i(Pl,"readPlaywrightCoreVersion");function Ao(n){return{node:process.version,platform:`${bt.platform()} ${bt.release()} ${bt.arch()}`,cpus:bt.cpus().length,playwrightCore:Pl(),chromiumExecutable:ht.executablePath(),channel:mt,extensionDist:n}}i(Ao,"buildEnvFingerprint");async function vt(n){let e=new Date().toISOString(),r=n.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let o=await Y({operation:`read chrome.storage.session['tabStates'] and ['${Kt}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async s=>{let a=await new Promise(g=>chrome.storage.session.get(["tabStates",s],g)),l=a.tabStates,c=typeof l!="object"||l===null?[]:Object.entries(l).map(([g,m])=>{let v=typeof m=="object"&&m!==null?m.playback:null;if(typeof v!="object"||v===null)return{tabId:g,playback:null};let b=v;return{tabId:g,playback:{runId:typeof b.runId=="string"?b.runId:null,status:typeof b.status=="string"?b.status:null,currentStepIndex:typeof b.currentStepIndex=="number"?b.currentStepIndex:null}}}),w=a[s],f=typeof w!="object"||w===null?null:(()=>{let g=w;return{agentJobId:typeof g.agentJobId=="string"?g.agentJobId:null,updatedAt:typeof g.updatedAt=="string"?g.updatedAt:null}})();return{tabs:c,agentJob:f}},Kt),"evaluate")});return{ok:!0,observedAt:e,tabs:o.tabs,agentJob:o.agentJob}}catch(o){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:o instanceof Error?o.message:String(o)}}}i(vt,"probePlaybackSession");var be=p("task-browser-instances"),gn=class extends Error{static{i(this,"TaskBrowserLaunchAbortedError")}subjectId;constructor(e){super(`[runtime] launch of the instance of task browser subject ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being kept.`),this.name="TaskBrowserLaunchAbortedError",this.subjectId=e}},Te=class{static{i(this,"TaskBrowserInstances")}#e;#t;#n;#r;#i;#a=new Map;#o=new Map;constructor(e){this.#e=e.registry,this.#t=e.extensionDist,this.#n=e.allowInsecureHttps,this.#r=e.onLost,this.#i=e.kind}subjectIdsWithInstance(){return[...this.#a.keys()]}async start(e,t,r,o){let s=this.#a.get(t);if(s!==void 0)throw new Error(`[runtime] task browser subject ${t} already has an instance in state ${s.state}`);let a=this.#p(e.jobId,t),l=await G(e.jobId,"instance_reserve",()=>{let f=this.#o.get(a);return f!==void 0&&this.#h(f),this.#e.reserve(a,e.deadlineAt)}),c={subjectId:t,jobId:e.jobId,instanceKey:a,userDataDir:l.userDataDir,state:"launching",context:null,contextAtTeardown:null,teardown:null};this.#a.set(t,c),be.info("Launching the browser task browser instance",{runId:e.jobId,workflowId:e.workflowId,subjectId:t,headful:e.headful,userDataDir:l.userDataDir,deadlineAt:e.deadlineAt});let w=Date.now();try{let f=await Rt({runId:e.jobId,userDataDir:l.userDataDir,extensionDist:this.#t,headful:e.headful,allowInsecureHttps:this.#n,keepBackgroundWindowsRendering:!0,extensionSession:r,command:o,entryUrl:e.entryUrl,onContext:i(g=>{c.context=g},"onContext"),assertNotAborted:i(()=>this.#s(c),"assertNotAborted")});this.#s(c),c.state="active",this.#d(c,f.context),be.info("Task browser instance launched",{runId:e.jobId,subjectId:t,chromeVersion:f.chromeVersion,extensionId:f.extensionId,readinessAttempts:f.readinessAttempts,readyAfterMs:f.readyAfterMs,launchDurationMs:Date.now()-w})}catch(f){let g=i(m=>{be.error("Teardown after a failed task browser launch did not finish",{runId:e.jobId,subjectId:t,err:m instanceof Error?m.message:String(m)})},"logTeardownFailure");if(c.teardown===null)await this.#c(c,"launch_failure").catch(g);else if(await c.teardown.catch(g),c.context!==null&&c.context!==c.contextAtTeardown){let m=await Be(this.#e,{instanceKey:c.instanceKey,context:c.context,userDataDir:c.userDataDir,timeoutMs:2e4,trigger:"dispose_during_launch"});this.#l(c,m),m.failure!==null&&g(m.failure)}throw f}}async dispose(e,t){let r=this.#a.get(t);if(r!==void 0&&r.jobId===e){if(r.teardown!==null)return r.teardown;let s=r.state==="launching"?"dispose_during_launch":"dispose";return this.#c(r,s)}let o=this.#o.get(this.#p(e,t));return o!==void 0?this.#h(o):null}async disposeAll(e){let t=new Set;for(let s of this.#a.values())s.jobId===e&&t.add(s.subjectId);for(let s of this.#o.values())s.jobId===e&&t.add(s.subjectId);if(t.size===0)return;let o=(await Promise.allSettled([...t].map(s=>this.dispose(e,s)))).find(s=>s.status==="rejected");if(o!==void 0)throw o.reason}async probe(e){let t=this.#a.get(e);return t===void 0||t.state!=="active"||t.context===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:`the runtime owns no running instance of task browser subject ${e}`}:vt(t.context)}#s(e){if(e.teardown!==null)throw new gn(e.subjectId)}#d(e,t){let r=i(s=>{if(e.state!=="active"||e.teardown!==null)return;let a=this.#c(e,"instance_lost"),l={jobId:e.jobId,subjectId:e.subjectId,at:new Date().toISOString(),source:s};be.warn("Task browser instance disappeared without a dispose",{...l}),a.catch(c=>{be.error("Teardown after a lost task browser instance failed",{runId:e.jobId,subjectId:e.subjectId,err:c instanceof Error?c.message:String(c)})}).finally(()=>this.#r(l))},"report");t.on("close",()=>r("context_closed"));let o=t.browser();o!==null&&o.on("disconnected",()=>r("browser_disconnected"))}#c(e,t){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let o=await Be(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:t});if(be.info("Task browser instance closed",{runId:e.jobId,subjectId:e.subjectId,trigger:t,disposeOutcome:o.result.outcome,instanceReleased:o.result.instanceReleased}),this.#l(e,o),o.failure!==null)throw o.failure;return o.result}finally{this.#a.get(e.subjectId)===e&&this.#a.delete(e.subjectId)}})();return e.teardown=r,r}#l(e,t){if(t.result.instanceReleased){this.#o.delete(e.instanceKey);return}this.#o.set(e.instanceKey,{instanceKey:e.instanceKey,jobId:e.jobId,subjectId:e.subjectId,result:t.result,killConfirmed:t.killConfirmed})}#p(e,t){return this.#i==="identity"?`${e}~${t}`:`${e}~launch~${t}`}#h(e){let t=kt(this.#e,e);return this.#o.delete(e.instanceKey),t}};var Tt=class{static{i(this,"IdentityInstances")}#e;constructor(e){this.#e=new Te({...e,kind:"identity",onLost:i(({subjectId:t,...r})=>e.onLost({...r,identityId:t}),"onLost")})}identityIdsWithInstance(){return this.#e.subjectIdsWithInstance()}async start(e,t,r){await this.#e.start(e,t,r,{v:1,kind:"task_identity",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,identityId:t})}dispose(e,t){return this.#e.dispose(e,t)}disposeAll(e){return this.#e.disposeAll(e)}probe(e){return this.#e.probe(e)}};var It=class{static{i(this,"TaskJobInstances")}identities;launches;constructor(e){this.identities=new Tt(e),this.launches=new Te({...e,kind:"launch",onLost:i(({subjectId:t,...r})=>e.onLaunchLost({...r,launchId:t}),"onLost")})}async startLaunch(e,t,r,o){let s=wn(e,t);await this.launches.start(s,r,o,{v:1,kind:"task_launch",runId:t,issuedAt:new Date().toISOString(),workflowId:s.workflowId,launchId:r})}async disposeAll(e){let t=await Promise.allSettled([this.identities.disposeAll(e),this.launches.disposeAll(e)]);for(let r of t)if(r.status==="rejected")throw r.reason}};function wn(n,e){if(n===null||n.runId!==e)throw new Error(`[runtime] job ${e} is not the running instance (running: ${n===null?"none":n.runId})`);if(n.identityInputs===null)throw new Error(`[runtime] job ${e} is not a task job; only a swarm job hosts task browser instances`);return n.identityInputs}i(wn,"taskInputs");import{mkdirSync as Oo,readdirSync as Dl,readFileSync as Ll,renameSync as Gl,rmSync as yn,writeFileSync as Ul}from"node:fs";import{join as We}from"node:path";var ae=p("instance-registry");function xt(n){return typeof n=="string"&&n!==""}i(xt,"isNonEmptyString");function Ml(n,e){if(typeof n!="object"||n===null)throw new Error(`[instance-registry] ${e} does not contain a JSON object.`);let t=n;if(t.v!==1)throw new Error(`[instance-registry] ${e} has version ${JSON.stringify(t.v)}, expected 1.`);if(!xt(t.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!xt(t.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!xt(t.startedAt)||!xt(t.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof t.agentPid!="number"||!Number.isInteger(t.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:t.runId,agentPid:t.agentPid,userDataDir:t.userDataDir,startedAt:t.startedAt,deadlineAt:t.deadlineAt}}i(Ml,"parseInstanceRecord");function $l(n,e){let t=`${n}.tmp`;Ul(t,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Gl(t,n)}i($l,"writeMarkerAtomically");var At=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=We(e,oo)}get instancesRoot(){return this.#e}userDataDirFor(e){return We(this.#e,e)}reserve(e,t){Oo(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Oo(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new z(e,r,s):s}let o=new Date().toISOString();try{$l(We(r,ft),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:t})}catch(s){try{yn(r,{recursive:!0,force:!0})}catch(a){ae.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:a instanceof Error?a.message:String(a)})}throw s}return ae.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:t}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:t}}read(e){return this.#n(We(this.userDataDirFor(e),ft))}release(e){let t=this.userDataDirFor(e);yn(t,{recursive:!0,force:!0}),ae.info("Instance released",{runId:e,userDataDir:t})}listRunIds(){let e;try{e=Dl(this.#e,{withFileTypes:!0})}catch(t){if(typeof t=="object"&&t!==null&&t.code==="ENOENT")return[];throw t}return e.filter(t=>t.isDirectory()).map(t=>t.name)}async sweepOrphans(){let e=new Date().toISOString(),t=[];for(let r of this.listRunIds())t.push(await this.#t(r));return t.length>0?ae.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:t.length,outcomes:t}):ae.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:t}}async#t(e){let t=this.userDataDirFor(e),r=We(t,ft),o=null,s;try{o=this.#n(r),s="valid"}catch(l){s=(typeof l=="object"&&l!==null?l.code:null)==="ENOENT"?"missing":"unreadable",ae.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:t,marker:s,err:l instanceof Error?l.message:String(l)})}let a=await _t(t);return ae.warn("Leftover browser instance swept",{runId:e,userDataDir:t,marker:s,kill:a}),yn(t,{recursive:!0,force:!0}),{runId:e,userDataDir:t,marker:s,record:o,kill:a,removed:!0}}#n(e){let t=Ll(e,"utf8");return Ml(JSON.parse(t),e)}};var K=p("playwright-execution-runtime"),_n=class extends Error{static{i(this,"LaunchAbortedError")}runId;constructor(e){super(`[runtime] launch of run ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being published (CONTRACT-la \xA715 A3, A19.1).`),this.name="LaunchAbortedError",this.runId=e}},Ot=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#i;#a;#o;#s=null;#d=null;#c=!1;#l=null;#p=null;constructor(e){co(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#i=new At(e.stateDir),this.#a=Ao(e.extensionDist),this.#o=new It({registry:this.#i,extensionDist:e.extensionDist,allowInsecureHttps:e.allowInsecureHttps,onLost:e.onIdentityInstanceLost,onLaunchLost:e.onLaunchInstanceLost}),K.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#i.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#a})}getActiveInstance(){let e=this.#s;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async startIdentityInstance(e,t,r){await this.#o.identities.start(wn(this.#s,e),t,r)}async startLaunchInstance(e,t,r){await this.#o.startLaunch(this.#s,e,t,r)}disposeLaunchInstance(e,t){return this.#o.launches.dispose(e,t)}launchIdsWithInstance(){return this.#o.launches.subjectIdsWithInstance()}async disposeIdentityInstance(e,t){return this.#o.identities.dispose(e,t)}async probeIdentityInstance(e){return this.#o.identities.probe(e)}identityIdsWithInstance(){return this.#o.identities.identityIdsWithInstance()}async sweepOrphanInstances(){return this.#i.sweepOrphans()}async probePlaybackSession(){let e=this.#s;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:vt(e.context)}async startRun(e){let t=this.#s;if(t!==null)throw new St(e.runId,t.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),s=await G(e.runId,"instance_reserve",()=>this.#i.reserve(e.runId,o));this.#p?.runId===e.runId&&(this.#p=null);let a={runId:e.runId,userDataDir:s.userDataDir,context:null,disposeRequested:!1};this.#d=a;let l=this.#m(e),c=e.command.kind==="swarm";K.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:c,userDataDir:s.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:o,envFingerprint:this.#a});let w=null;try{let f=await Rt({runId:e.runId,userDataDir:s.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n,keepBackgroundWindowsRendering:c,extensionSession:e.extensionSession,command:e.command,entryUrl:e.entryUrl,onContext:i(m=>{w=m,a.context=m},"onContext"),assertNotAborted:i(()=>this.#u(a),"assertNotAborted")}),g={runId:e.runId,context:f.context,userDataDir:s.userDataDir,headful:l,extensionId:f.extensionId,chromeVersion:f.chromeVersion,startedAt:s.startedAt,deadlineAt:o,identityInputs:e.command.kind==="swarm"?{jobId:e.runId,workflowId:e.command.workflowId,entryUrl:e.entryUrl,headful:l,deadlineAt:o}:null};this.#u(a),this.#f(g),this.#s=g,this.#d===a&&(this.#d=null),K.info("Run launched",{runId:e.runId,chromeVersion:f.chromeVersion,extensionId:f.extensionId,readinessAttempts:f.readinessAttempts,readyAfterMs:f.readyAfterMs,launchDurationMs:Date.now()-r})}catch(f){throw this.#d===a&&(this.#d=null),await this.#g({runId:e.runId,context:w,userDataDir:s.userDataDir,timeoutMs:2e4,trigger:a.disposeRequested?"dispose_during_launch":"launch_failure"}),f}finally{this.#d===a&&(this.#d=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,t=2e4){let[r,o]=await Promise.allSettled([this.#o.disposeAll(e),this.#h(e,t)]);if(o.status==="rejected")throw o.reason;if(r.status==="rejected")throw r.reason;return o.value}async#h(e,t){let r=this.#l;if(r!==null&&r.runId===e)return K.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let o=this.#d;if(o!==null&&o.runId===e)return o.disposeRequested=!0,K.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:o.userDataDir,contextPresent:o.context!==null}),this.#g({runId:e,context:o.context,userDataDir:o.userDataDir,timeoutMs:t,trigger:"dispose_during_launch"});let s=this.#s;return s===null||s.runId!==e?this.#w(e):(this.#s=null,this.#g({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:t,trigger:"dispose"}))}#m(e){return e.headful||this.#t}#u(e){if(e.disposeRequested)throw new _n(e.runId)}#f(e){let t=i(o=>{if(this.#c||this.#s?.runId!==e.runId)return;this.#s=null;let s=this.#g({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#l={runId:e.runId,promise:s},s.catch(l=>{K.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:l instanceof Error?l.message:String(l)})}).finally(()=>{this.#l?.promise===s&&(this.#l=null)});let a={runId:e.runId,at:new Date().toISOString(),source:o};K.error("Browser instance disappeared without a dispose",{...a}),this.#r(a)},"report");e.context.on("close",()=>t("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>t("browser_disconnected"))}#w(e){let t=this.#p;if(t===null||t.runId!==e)return K.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#s===null?null:this.#s.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(t.result.instanceReleased)return K.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:t.result.outcome,instanceReleased:!0}),t.result;let r=kt(this.#i,{instanceKey:e,result:t.result,killConfirmed:t.killConfirmed});return this.#p={runId:e,result:r,killConfirmed:!0},r}async#g(e){this.#c=!0;try{let t=await Be(this.#i,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#p={runId:e.runId,result:t.result,killConfirmed:t.killConfirmed},t.failure!==null)throw t.failure;return t.result}finally{this.#c=!1}}};import{setTimeout as jl}from"node:timers/promises";function le(n,e=Math.random){if(n<0)throw new Error(`[backoff] attempt must be >= 0, got ${n}. Pass 0 for the first reconnect after a disconnect.`);let t=Math.min(6e4,1e3*Math.pow(2,Math.min(n,26)));return Math.floor(e()*t)}i(le,"computeBackoffDelayMs");function Ie(n){let e=Fl(n.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:le(n.attempt,n.rng)}}i(Ie,"decideGatewayRetry");function Fl(n){if(n instanceof E)return"terminal_signal";if(n instanceof B)return"contract_breach";if(n instanceof S)return"semantic_refusal";if(n.operation==="claim"||n.operation==="token_rotate")return"one_shot_operation";if(n instanceof j||n instanceof we)return null;if(n instanceof R)return n.status===429?"rate_limited":n.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${n.name} on operation '${n.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}i(Fl,"classifyFailure");var Z=p("supervisor-identity");async function xe(n){let{config:e}=n;if(e.initialToken!==void 0)return Bl(e,e.initialToken);let t=F(e.stateDir);if(t!==null)return ql(t.serverUrl,e.serverUrl),Z.info("Agent identity loaded from the state file",{agentId:t.agentId}),{agentToken:t.agentToken,agentId:t.agentId,pollWaitSec:void 0,source:"state_file"};if(e.enrollmentCode!==void 0)return Kl(n,e.enrollmentCode);throw new h(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
26
26
  There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
27
- To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}i(Re,"resolveAgentIdentity");function bl(t,e){return t.enrollmentCode!==void 0&&Y.warn("Both PROGON_AGENT_TOKEN and PROGON_AGENT_ENROLL_CODE are set \u2014 the token wins and the enrollment code is NOT redeemed (it stays valid until it expires)"),Y.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:kl(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}i(bl,"identityFromEnvToken");function kl(t){try{return $(t)===null?"absent":"present"}catch(e){return Y.warn("The state file could not be read \u2014 continuing on PROGON_AGENT_TOKEN, which does not need it. The persisted credential is NOT usable: once this variable is unset, the daemon will refuse to start until the file is removed and the machine re-enrolled",{stateDir:t,err:e instanceof Error?e.message:String(e)}),"unreadable"}}i(kl,"describeStateFile");async function Tl(t,e){let{config:n,machine:r}=t;Y.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let o=new it(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),a=await vl(o,e,t.rng);return ce(n.stateDir,{agentId:a.agentId,agentToken:a.agentToken,protocolVersion:a.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),Y.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:a.agentId,stateDir:n.stateDir}),{agentToken:a.agentToken,agentId:a.agentId,pollWaitSec:a.pollWaitSec,source:"enrollment"}}i(Tl,"enrollThisMachine");var wo=900*1e3;async function vl(t,e,n){let r=Date.now()+wo;for(let o=0;;o+=1)try{return await t.enroll(e)}catch(a){if(!(a instanceof k))throw a;let s=Se({attempt:o,error:a,rng:n});if(!s.retry)throw Y.warn("Enrollment refused definitively \u2014 not retrying",{attempt:o,reason:s.reason,err:a.message}),a;if(Date.now()+s.delayMs>=r)throw new p(`[progon-agent] Enrollment kept failing for the ${wo/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${a.message}
28
- Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:a});Y.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:o,retryInMs:s.delayMs,err:a.message}),await Rl(s.delayMs)}}i(vl,"enrollWithRetry");function St(t,e){if(t.source==="enrollment")return;let n=" The code itself was not spent and stays valid until it expires.";throw t.source==="env_token"?new p(`[progon-agent] The enrollment code was not redeemed: PROGON_AGENT_TOKEN is set, and a credential supplied that way takes precedence over any code (CONTRACT-la \xA78).
27
+ To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}i(xe,"resolveAgentIdentity");function Bl(n,e){return n.enrollmentCode!==void 0&&Z.warn("Both PROGON_AGENT_TOKEN and PROGON_AGENT_ENROLL_CODE are set \u2014 the token wins and the enrollment code is NOT redeemed (it stays valid until it expires)"),Z.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Wl(n.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}i(Bl,"identityFromEnvToken");function Wl(n){try{return F(n)===null?"absent":"present"}catch(e){return Z.warn("The state file could not be read \u2014 continuing on PROGON_AGENT_TOKEN, which does not need it. The persisted credential is NOT usable: once this variable is unset, the daemon will refuse to start until the file is removed and the machine re-enrolled",{stateDir:n,err:e instanceof Error?e.message:String(e)}),"unreadable"}}i(Wl,"describeStateFile");async function Kl(n,e){let{config:t,machine:r}=n;Z.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let o=new ct(n.fetchImpl===void 0?{serverUrl:t.serverUrl,machine:r}:{serverUrl:t.serverUrl,machine:r,fetchImpl:n.fetchImpl}),s=await Jl(o,e,n.rng);return me(t.stateDir,{agentId:s.agentId,agentToken:s.agentToken,protocolVersion:s.protocolVersion,serverUrl:t.serverUrl,tokenRotatedAt:null}),Z.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:s.agentId,stateDir:t.stateDir}),{agentToken:s.agentToken,agentId:s.agentId,pollWaitSec:s.pollWaitSec,source:"enrollment"}}i(Kl,"enrollThisMachine");var No=900*1e3;async function Jl(n,e,t){let r=Date.now()+No;for(let o=0;;o+=1)try{return await n.enroll(e)}catch(s){if(!(s instanceof k))throw s;let a=Ie({attempt:o,error:s,rng:t});if(!a.retry)throw Z.warn("Enrollment refused definitively \u2014 not retrying",{attempt:o,reason:a.reason,err:s.message}),s;if(Date.now()+a.delayMs>=r)throw new h(`[progon-agent] Enrollment kept failing for the ${No/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${s.message}
28
+ Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:s});Z.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:o,retryInMs:a.delayMs,err:s.message}),await jl(a.delayMs)}}i(Jl,"enrollWithRetry");function Nt(n,e){if(n.source==="enrollment")return;let t=" The code itself was not spent and stays valid until it expires.";throw n.source==="env_token"?new h(`[progon-agent] The enrollment code was not redeemed: PROGON_AGENT_TOKEN is set, and a credential supplied that way takes precedence over any code (CONTRACT-la \xA78).
29
29
  Unset PROGON_AGENT_TOKEN, then run the same command again. A separate state directory does NOT help here: the variable is read before any state file and wins wherever that file lives.
30
- `+n):new p(`[progon-agent] The enrollment code was not redeemed: this machine already holds a credential enrolled against ${e.serverUrl}, and a persisted credential takes precedence over a code (CONTRACT-la \xA78).
30
+ `+t):new h(`[progon-agent] The enrollment code was not redeemed: this machine already holds a credential enrolled against ${e.serverUrl}, and a persisted credential takes precedence over a code (CONTRACT-la \xA78).
31
31
  To enroll this machine as a SECOND agent \u2014 for another deployment, or as another agent record \u2014 give it its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll <code> --server <url> (and give 'progon-agent start' the same variable).
32
32
  To REPLACE the credential it already holds, remove the state file in ${e.stateDir}, then run: progon-agent enroll <code> --server ${e.serverUrl} \u2014 with that file gone this machine no longer names that deployment itself, and --server is what keeps the new enrollment pointed at it.
33
- `+n)}i(St,"assertEnrollmentCodeWasRedeemed");function Al(t,e){if(!Ze(t,e))throw new p(`[progon-agent] The persisted agent credential was enrolled against ${t}, but PROGON_SERVER_URL is ${e}. A pgat_ token is meaningless at a different deployment (CONTRACT-la \xA78), so the daemon refuses to authenticate blind.
34
- Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}i(Al,"assertServerMatchesEnrollment");import{createRequire as xl}from"node:module";import{hostname as Il}from"node:os";var yo=["darwin","linux","win32"],_o=["x64","arm64"];function Ol(t){return yo.includes(t)}i(Ol,"isSupportedPlatform");function Nl(t){return _o.includes(t)}i(Nl,"isSupportedArch");function Pl(){let e=xl(import.meta.url)("../../package.json"),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||n==="")throw new Error('[supervisor] The agent package.json has no usable "version" field, so the agent cannot state its version on the enroll wire (CONTRACT-la \xA75.1). This is a packaging defect \u2014 the daemon must not enroll under an invented version.');if(n.length>30)throw new Error(`[supervisor] The agent package version ${JSON.stringify(n)} is longer than the 30 characters CONTRACT-la \xA75.1 allows for agentVersion.`);return n}i(Pl,"readAgentVersion");function be(){let t=process.platform;if(!Ol(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${yo.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Nl(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${_o.join(", ")} (CONTRACT-la \xA75.1).`);let n=Il();if(n==="")throw new Error("[supervisor] os.hostname() returned an empty string, so this machine cannot be named on the enroll wire (CONTRACT-la \xA75.1 requires a non-empty hostname). Fix the host's network configuration.");return{hostname:n,platform:t,arch:e,agentVersion:Pl()}}i(be,"describeAgentMachine");var Eo=i(()=>{},"noop"),Rt=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Eo,Eo),n}};var So=m("supervisor-deadline"),Ge=class extends Error{static{i(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function bt(t){let e=t.work(),n=!1;e.then(()=>{n&&So.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&So.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:a instanceof Error?a.message:String(a)})});let r,o=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Ge(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(bt,"withDeadline");function Ue(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);function o(){clearTimeout(r),n()}i(o,"onAbort"),e.addEventListener("abort",o,{once:!0})})}i(Ue,"sleep");var X=m("fail-reporter"),kt=class{static{i(this,"RunFailureReporter")}#e;#t=null;#n=null;constructor(e){this.#e=e}hasVerdictFor(e){return this.#n===e}async report(e){if(this.#n===e.runId){X.warn("Ignoring a second terminal verdict for a run this agent already reported",{runId:e.runId,ignoredReason:e.body.reason,stillUndelivered:this.#t!==null});return}let n=this.#t;n!==null&&n.runId!==e.runId&&X.warn("Dropping an undelivered fail verdict \u2014 a different run needs one now",{droppedRunId:n.runId,droppedReason:n.body.reason,runId:e.runId}),this.#t={...e,attempt:0,nextAttemptAtMs:0},this.#n=e.runId,X.error("Reporting run failure to the gateway",{runId:e.runId,...e.body}),await this.#o()}async retryPending(){let e=this.#t;e!==null&&(Date.now()<e.nextAttemptAtMs||await this.#o())}discardIfNotPublished(e){let n=this.#t;n!==null&&n.runId!==e&&(X.info("Undelivered fail verdict discarded \u2014 its run is already terminal server-side",{runId:n.runId,reason:n.body.reason,publishedRunId:e}),this.#t=null)}async#o(){let e=this.#t;if(e!==null)try{let n=await this.#e.failRun(e.runId,e.body);X.info("Fail verdict delivered",{runId:e.runId,reason:e.body.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof E)throw n;if(n instanceof T)throw X.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.body.reason,err:n.message}),this.#t=null,n;if(!(n instanceof k))throw n;let r=Se({attempt:e.attempt,error:n});if(!r.retry){X.error("Fail verdict abandoned \u2014 the gateway refused it definitively",{runId:e.runId,reason:e.body.reason,noRetryReason:r.reason,err:n.message}),this.#t=null;return}this.#t={runId:e.runId,body:e.body,attempt:e.attempt+1,nextAttemptAtMs:Date.now()+r.delayMs},X.warn("Fail verdict not delivered \u2014 held for retry",{runId:e.runId,reason:e.body.reason,attempt:e.attempt+1,retryInMs:r.delayMs,err:n.message})}}};var Tt=120,Ro=Tt*1e3,ln=3e4,ke=3,dn=45*1e3,cn="agent shutdown";var G=m("launch-run");async function To(t){let e;try{e=await Dl(t)}finally{t.onClaimAnswered()}return e.kind!=="claimed"?e:Gl(t,e.payload)}i(To,"claimAndLaunch");async function Dl(t){try{let e=await t.client.claimRun(t.runId);return G.info("Run claimed",Ll(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof E)throw e;if(e instanceof T)throw G.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof he||e instanceof ee)return G.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof k))throw e;return G.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}i(Dl,"claimRun");function Ll(t){return"kind"in t?t.kind==="make_auto"?{kind:t.kind,runId:t.runId,projectId:t.command.projectId,queueId:t.command.queueId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}:t.kind==="swarm"?{kind:t.kind,runId:t.runId,workflowId:t.command.workflowId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}:t.kind==="scenario_launch"?{kind:t.kind,runId:t.runId,projectId:t.command.projectId,launchId:t.command.launchId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}:{kind:t.kind,runId:t.runId,projectId:t.command.projectId,maxRunDurationSec:t.maxRunDurationSec}:{kind:"playback",runId:t.runId,scenarioId:t.scenarioId,projectId:t.projectId,runPurpose:t.runPurpose,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}}i(Ll,"describeClaim");async function Gl(t,e){try{await bt({operation:`startRun(${e.runId})`,timeoutMs:Ro,work:i(()=>t.runtime.startRun({runId:e.runId,entryUrl:e.entryUrl,headful:e.headful,maxRunDurationSec:e.maxRunDurationSec,extensionSession:e.extensionSession,command:e.command}),"work")})}catch(r){return{kind:"failed",body:Ml(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(G.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}i(Gl,"launchClaimedRun");var bo=500,ko="\u2026";function Ul(t){return t.length<=bo?t:t.slice(0,bo-ko.length)+ko}i(Ul,"fitFailMessageToWire");function Ml(t,e){if(e instanceof V){let n=Ul(`stage ${e.stage}: ${tn(e)}`);if(e.stage==="entry_navigation"){let r=oo(e);return G.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:r,err:e.message}),{reason:e.failReason,message:n,entryFailure:r}}return G.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:n}}return e instanceof Ge?(G.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:Tt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Tt}s`}):e instanceof H?(G.error("Launch refused by the instance fence \u2014 the run cannot be started here",{runId:t,userDataDir:e.userDataDir,err:e.message}),{reason:"launch_error",message:"a leftover instance directory blocks this run"}):(G.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}i(Ml,"describeLaunchFailure");var Te=m("run-monitor");function $l(t,e){let n=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===t)?{healthy:!0}:Fl(t,e.agentJob,n)?{healthy:!0}:{healthy:!1,reason:"playback_absent",detail:`the extension answered but nothing it holds describes a live run of ours (${jl(e.tabs)}; ${Wl(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i($l,"judgeProbe");function Fl(t,e,n){if(e===null||e.agentJobId!==t||e.updatedAt===null)return!1;let r=Date.parse(e.updatedAt);return Number.isNaN(r)?!1:n-r<=dn}i(Fl,"isJobPulseStanding");function jl(t){if(t.length===0)return"tabStates is empty";let e=t.map(n=>n.playback===null?"none":n.playback.runId);return`${t.length} tab(s), playback run ids: ${e.join(", ")}`}i(jl,"describeTabs");function Wl(t,e){if(t===null)return"no job pulse is standing";if(t.updatedAt===null)return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, updatedAt=unreadable`;let n=Date.parse(t.updatedAt),r=Number.isNaN(n)?"unparsable":`${String(e-n)}ms old`;return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, ${r} (stale past ${String(dn)}ms)`}i(Wl,"describeJobMarker");var vt=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#o=null;#a=0;#s=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());Te.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:ln,probeStrikeLimit:ke}),this.#n=setInterval(()=>{this.#r()},ln),this.#n.unref(),this.#o=setTimeout(()=>{this.#s||(this.stop(),Te.error("Run reached its server-authored deadline",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt}),this.#e.onDeadline())},e),this.#o.unref()}stop(){this.#s=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#o!==null&&(clearTimeout(this.#o),this.#o=null)}async#r(){if(this.#s)return;let e=$l(this.#e.runId,await this.#i());if(this.#s)return;if(e.healthy){this.#a>0&&Te.info("Liveness probe recovered",{runId:this.#e.runId,clearedStrikes:this.#a}),this.#a=0;return}this.#a+=1;let n=`${e.reason}: ${e.detail}`;Te.warn("Liveness probe failed",{runId:this.#e.runId,strike:this.#a,strikeLimit:ke,reason:e.reason,detail:e.detail}),!(this.#a<ke)&&(this.stop(),Te.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,strikes:ke,detail:n}),this.#e.onBrowserGone(`${ke} consecutive liveness probes failed (${n})`))}async#i(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return Te.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,err:n}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:n}}}};var U=m("instance-reconciler");function Bl(t){let e=i(()=>{},"markSettled"),n=new Promise(s=>{e=s}),r=i(()=>{},"resolveClaimAnswer"),o=new Promise(s=>{r=s}),a={runId:t,cancelledBy:null,claimAnswered:!1,claimAnswer:o,markClaimAnswered:i(()=>{a.claimAnswered=!0,r()},"markClaimAnswered"),settled:n,markSettled:e};return a}i(Bl,"createPendingLaunch");var B={kind:"reconciled"},At=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#o;#a=new Set;#s=null;#r=null;#i=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#o=e.detach}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#a=new Set(e.outcomes.map(n=>n.runId)),U.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#a]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId);let r=this.#r;if(r!==null)return n!==null&&n.runId===r.runId?n.phase!=="queued"?B:{kind:"claim_issued",runId:n.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}:(r.cancelledBy!==null||await this.#f(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),B);let o=this.#t.getActiveInstance();return n===null?(o!==null&&await this.dispose(o.runId,"desired_state_run_absent"),B):o!==null?(o.runId===n.runId||await this.dispose(o.runId,"desired_state_runid_mismatch"),B):this.#n.hasVerdictFor(n.runId)?B:n.phase==="queued"?this.#i===n.runId?(U.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId}),{kind:"claim_issued",runId:n.runId,claimAnswer:null}):(this.#i=n.runId,this.#m(n.runId),B):(await this.#d(n.runId,n.phase),B)}async cancelLaunchAndSettle(e){let n=this.#r;return n===null?null:(U.warn("Stopping a launch that is still in flight",{runId:n.runId,trigger:e}),n.cancelledBy=e,this.#o(()=>this.dispose(n.runId,e)),await n.settled,n.runId)}async handleInstanceLost(e){U.error("The runtime reported a lost browser instance",{...e}),await this.#u(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,n){this.stopMonitor();try{let r=await this.#t.disposeRun(e);U.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){U.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#s?.stop(),this.#s=null}#m(e){let n=Bl(e);this.#r=n,this.#c(n)}async#c(e){try{let n=await this.#l(e);await this.#o(()=>this.#h(e,n))}finally{e.markSettled()}}async#l(e){try{return{kind:"outcome",outcome:await To({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(n){return{kind:"thrown",error:n}}}async#h(e,n){if(this.#r===e&&(this.#r=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){U.warn("A cancelled launch completed anyway \u2014 disposing what it brought up",{runId:e.runId,trigger:e.cancelledBy}),await this.dispose(e.runId,e.cancelledBy);return}this.#p(r.instance.runId,r.instance.deadlineAt);return;case"claim_refused":case"claim_unavailable":case"instance_lost_immediately":return;case"failed":if(await this.dispose(e.runId,"launch_failure"),e.cancelledBy!==null){U.info("A cancelled launch failed on the way down \u2014 no verdict is sent",{runId:e.runId,trigger:e.cancelledBy,suppressedReason:r.body.reason});return}await this.#n.report({runId:e.runId,body:r.body});return}}async#f(e,n){U.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:n}),e.cancelledBy=n,await this.dispose(e.runId,n)}#p(e,n){this.#s=new vt({runId:e,deadlineAt:n,probe:i(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:i(r=>{this.#o(()=>this.#u(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:i(()=>{this.#o(()=>this.#u(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#s.start()}async#d(e,n){let r=this.#a.has(e),o=r?"browser_gone":"launch_error";U.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:o}),await this.#n.report({runId:e,body:{reason:o,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"}})}async#u(e,n,r,o){await this.dispose(e,o),await this.#n.report({runId:e,body:{reason:n,message:r}})}};var vo="Create a new enrollment code in Progon (Settings \u2192 Agents) and run 'progon-agent enroll <code>' to enroll this machine again. The wipe removed the state file, so an installed package now takes the deployment it was built for; on a source checkout add --server <url>.",Ao={revoked:{exitCode:1,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+vo},reenroll_required:{exitCode:1,level:"error",message:"progon-agent stopped: this machine's agent token was superseded and the server no longer accepts it, so the credential has been wiped. This is not a revocation \u2014 the token was replaced and the replacement could not be kept. "+vo},credential_unusable:{exitCode:1,level:"error",message:"progon-agent stopped: the server no longer accepts the agent token this daemon was given in PROGON_AGENT_TOKEN, and a credential the operator owns is not one this daemon can replace. NOTHING WAS WIPED \u2014 the state directory belongs to an enrollment this mode never reads and may still be perfectly valid. Set PROGON_AGENT_TOKEN to a current token and start the daemon again, or unset it and enroll this machine so the daemon can rotate on its own."},fatal:{exitCode:1,level:"error",message:"progon-agent stopped: the desired-state poll was refused definitively and no repetition can change that answer, so the daemon has disposed its browser and stopped instead of live-locking. The preceding error line names the reason and the server's own message. Restarting is the process supervisor's call once that condition has been fixed."},stopped:{exitCode:null,level:"info",message:"progon-agent stopped"}},xo={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var I=m("token-rotation"),Io=1440*60*1e3,xt=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#o=null;#a=!1;#s=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#o;if(n!==null)return n;let r=this.#r(e);this.#o=r;try{return await r}finally{this.#o=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return I.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof T)return"reenroll_required";if(n instanceof E)throw n;if(n instanceof k)return I.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:n.operation,err:n.message}),"alive";throw n}}async settle(){let e=this.#o;e!==null&&await e.then(()=>{},()=>{})}async#r(e){if(this.#n==="env_token")return this.#a||(this.#a=!0,I.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#s)return{kind:"superseded_in_grace"};let n=this.#d();if(n.kind!=="identity")return this.#u(n);let r=n.identity,o=await this.#i(e);return o.kind!=="status"?o.outcome:o.value.rotationDue?await this.#c(r,o.value.tokenRotatedAt,e):this.#m(r,o.value.tokenRotatedAt)}async#i(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof T)return I.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof E)throw n;if(n instanceof k)return I.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:n.operation,err:n.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw n}}#m(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#p({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#s=!0,I.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:n}),{kind:"superseded_in_grace"})}async#c(e,n,r){let o;try{o=(await this.#e.rotateToken()).agentToken}catch(s){if(s instanceof E)throw s;if(s instanceof T)return await this.#l(r);if(s instanceof k)return I.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:s.operation,err:s.message}),await this.#h(n);throw s}this.#p({...e,agentToken:o,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(o);let a=await this.#f();return a.kind==="reenroll_required"?a:(a.kind==="observed"&&this.#p({...e,agentToken:o,tokenRotatedAt:a.tokenRotatedAt},"rotation marker of the new agent token"),I.info("Agent token rotated"),{kind:"rotated"})}async#l(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#s=!0,I.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#h(e){let n=await this.#i(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(I.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#s=!0,I.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:n.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#f(){let e=await this.#i(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(I.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#p(e,n){try{return ce(this.#t,e),!0}catch(r){return I.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#d(){let e;try{e=$(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#u(e){return e.kind==="unreadable"?(I.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(I.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var O=m("run-supervisor"),un=i(()=>Promise.resolve(),"noVerdictOwed"),It=class{static{i(this,"RunSupervisor")}#e;#t;#n;#o=new Rt;#a;#s;#r=null;#i=0;#m=0;#c=!1;#l=new AbortController;#h=null;#f=!1;#p=!1;#d;#u=null;#w=null;constructor(e){this.#e=e.client,this.#a=e.stateDir,this.#s=e.pollWaitSec,this.#d=e.tokenRotation,this.#t=new kt(e.client),this.#l.signal.addEventListener("abort",()=>this.#L(),{once:!0});let n=e.createRuntime(r=>{this.#x(()=>this.#n.handleInstanceLost(r))});this.#n=new At({client:e.client,runtime:n,reporter:this.#t,detach:i(r=>this.#x(r),"detach")})}async run(){await this.#o.run(()=>this.#n.sweepAtStartup());let e=await this.#C();if(e!==null)return e;for(this.#T(),await this.#N();!this.#c;){let n=this.#h;if(n!==null)return await this.#S(n),"revoked";if(this.#f)return await this.#R(),"reenroll_required";if(this.#p)return await this.#A(),"credential_unusable";try{await this.#o.run(()=>this.#t.retryPending());let r=await this.#G();this.#i=0;let o=await this.#o.run(()=>this.#n.reconcile(r));await this.#U(o)}catch(r){if(r instanceof E)return await this.#S(r),"revoked";if(r instanceof T&&await this.#v(r))return await this.#R(),"reenroll_required";if(this.#c)break;if(this.#_())continue;let o=await this.#F(r);if(o!==null)return o==="credential_unusable"?await this.#A():await this.#$(),o}}return this.#g()}async#g(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#N(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(await this.#O(e),this.#_())return;if(!(e instanceof k))throw e;O.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#w;if(n!==null)return O.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#P(e);return this.#w=r,r}async#P(e){O.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#k(n))}async#y(e,n){this.#c=!0,this.#r?.abort(),this.#l.abort();let r=xo[e],o=await this.#n.cancelLaunchAndSettle(r);await this.#o.run(async()=>{this.#n.stopMonitor();let a=this.#n.activeRunId;a!==null&&await this.#n.dispose(a,r),await n({activeRunId:a,launchingRunId:o})}),await this.#d.settle()}async#k(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#b(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:cn}}));return}if(r!==null){await this.#b(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:cn}}));return}await this.#b(()=>this.#t.retryPending())}async#C(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof E)return await this.#S(e),"revoked";throw e}return await this.#R(),"reenroll_required"}#T(){if(this.#c||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#u=null,this.#D().finally(()=>{this.#T()})},Io);e.unref(),this.#u=e}async#D(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#f=!0,this.#r?.abort()}catch(e){await this.#I(e)}}#L(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}async#v(e){O.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#d.diagnoseSuperseded(this.#l.signal)==="reenroll_required"}catch(n){if(n instanceof E)return this.#h=n,!1;throw n}}async#G(){let e=new AbortController;this.#r=e;try{return await this.#e.pollDesiredState({waitSec:this.#s,signal:e.signal})}finally{this.#r=null}}async#U(e){if(e.kind==="reconciled"){this.#m=0;return}await this.#M(e.runId,e.claimAnswer)}async#M(e,n){let r=oe(this.#m);O.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#m,waitMs:r,claimOnTheWire:n!==null}),this.#m+=1;let o=new AbortController;if(this.#r=o,this.#l.signal.aborted||this.#_()){this.#r=null;return}n?.then(()=>o.abort());try{await Ue(r,o.signal)}finally{this.#r=null}}async#E(){await this.#d.settle(),cr(this.#a)}async#S(e){O.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",un),await this.#E()}async#A(){O.error("The server refuses the credential this daemon runs on as superseded, and this daemon has no way to replace it \u2014 disposing the browser and stopping so the operator, and the process supervisor, both learn it now. The state directory is left untouched: this credential did not come from there."),await this.#y("credential_unusable",un)}async#$(){await this.#y("fatal",e=>this.#k(e))}async#R(){O.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#y("reenroll_required",un),await this.#E()}async#F(e){if(!(e instanceof k))throw e;let n=this.#j(e);return n.kind==="exit"?n.exit:(this.#i+=1,await Ue(n.delayMs,this.#l.signal),null)}#j(e){if(e instanceof T){if(!this.#d.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=oe(this.#i);return O.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#i,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Se({attempt:this.#i,error:e});return n.retry?(O.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#i,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(O.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#x(e){return this.#o.run(e).catch(n=>this.#I(n))}async#I(e){await this.#O(e)||O.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#O(e){if(e instanceof E)return this.#h=e,this.#r?.abort(),!0;if(!(e instanceof T))return!1;try{await this.#v(e)?this.#f=!0:this.#d.canDiagnoseFromTheWire||(this.#p=!0)}catch(n){return O.error("The superseded diagnosis failed after a gateway refusal off the poll",{operation:e.operation,err:n instanceof Error?n.message:String(n)}),!0}return this.#_()&&this.#r?.abort(),!0}#_(){return this.#h!==null||this.#f||this.#p}async#b(e){try{await e()}catch(n){if(n instanceof T){O.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof E){await this.#E(),O.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var Oo=m("supervisor-boot");async function No(){let t=ue();Oo.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,serverUrlSource:t.serverUrlSource,stateDir:t.stateDir,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps});let e=be(),n=await Re({config:t,machine:e});Oo.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=kr({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ve({stdio:"pipe"});let o=new at({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new xt({client:o,stateDir:t.stateDir,identitySource:n.source});return new It({client:o,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:i(s=>new Et({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:s}),"createRuntime")})}i(No,"bootRunSupervisor");var mn=m("daemon");async function Co(){yr(),mn.info("progon-agent starting");let t=await No();_r(async r=>{await t.shutdown(r)});let e;try{e=await t.run()}catch(r){throw await t.shutdown("fatal").catch(o=>{throw new AggregateError([r,o],`${Po(r)} \u2014 and the teardown after it failed too, so the browser may still be running: ${Po(o)}`)}),r}let n=Ao[e];return n.level==="error"?mn.error(n.message):mn.info(n.message),n.exitCode}i(Co,"runDaemon");function Po(t){return t instanceof Error?t.message:String(t)}i(Po,"describe");import{createHash as Zl,randomBytes as Ql}from"node:crypto";import{z as x}from"zod";var Do=x.object({requestId:x.uuid(),mode:x.literal("device"),userCode:x.string().min(1),verificationUrl:x.url(),expiresAt:x.iso.datetime({offset:!0}),pollIntervalSec:x.number().int().positive()}),Lo=x.object({status:x.literal("authorization_pending"),expiresAt:x.iso.datetime({offset:!0}),pollIntervalSec:x.number().int().positive()}),Kl=x.object({companyName:x.string(),approvedByEmail:x.string(),approvedAt:x.string()}),Go=x.object({credential:We,approval:Kl});var Uo=m("gateway-enrollment-request"),Ot=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??st}async create(e){let n=await te({operation:"enrollment_request_create",method:"POST",url:D(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:xr}),r=C("enrollment_request_create",Do.safeParse(n));return Uo.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await te({operation:"enrollment_request_poll",method:"POST",url:D(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ir}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let o=C("enrollment_request_poll",Go.safeParse(n));return Uo.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=C("enrollment_request_poll",Lo.safeParse(n));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new j("enrollment_request_poll","the 2xx body is neither the authorization_pending answer nor the success envelope CONTRACT-phase-c \xA74.1 M2 defines")}async cancel(e){await te({operation:"enrollment_request_cancel",method:"POST",url:D(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Or})}};import{spawn as ql}from"node:child_process";var Me=m("browser-open");function Nt(t){return t!==void 0&&t!==""}i(Nt,"isSet");function Vl(t,e){return!(Nt(t.SSH_CONNECTION)||Nt(t.SSH_TTY)||e==="linux"&&!Nt(t.DISPLAY)&&!Nt(t.WAYLAND_DISPLAY))}i(Vl,"shouldAttemptBrowserOpen");var Hl=/[&|^<>"'` ]/;function Jl(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!Hl.test(t)}i(Jl,"isSpawnSafeUrl");function Yl(t,e){switch(e){case"darwin":return{command:"open",args:[t]};case"linux":return{command:"xdg-open",args:[t]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",t]};default:return null}}i(Yl,"browserOpenCommand");function Mo(t,e,n){if(!Vl(e,n)){Me.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!Jl(t)){Me.warn('Not opening a browser: the verification URL the server returned is not safe to hand to a spawned process. Follow the "Approve at:" link printed above instead',{platform:n});return}let r=Yl(t,n);if(r===null){Me.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let o=ql(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",a=>{Me.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),o.unref()}catch(o){Me.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:o instanceof Error?o.message:String(o)})}}i(Mo,"openVerificationUrl");var Xl=30,zl=5;function $o(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}i($o,"initialPollSchedule");function Pt(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+zl,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(o,Xl);return{state:{intervalSec:a,deadlineMs:t.deadlineMs},delayMs:a*1e3}}let n=oe(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}i(Pt,"nextPollDelayMs");function Fo(t,e){return e>=t.deadlineMs}i(Fo,"isDeadlinePassed");function jo(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}i(jo,"clampDelayToDeadline");var Ae=m("device-enrollment"),ed=24,td=2e3,pn=0,ve=1,Bo=130,nd="This machine is already enrolled. Start the daemon with: progon-agent start",rd="Enrollment was denied in the browser. Nothing was created on this machine.",od="Cancelled. Nothing was saved on this machine.",id="progon-agent: interrupted again \u2014 exiting immediately. The enrollment request was not withdrawn; it expires on its own. Nothing was saved on this machine.";function Wo(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}i(Wo,"expiredLine");function ad(t,e,n){return`This machine is already enrolled against ${t}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
33
+ `+t)}i(Nt,"assertEnrollmentCodeWasRedeemed");function ql(n,e){if(!rt(n,e))throw new h(`[progon-agent] The persisted agent credential was enrolled against ${n}, but PROGON_SERVER_URL is ${e}. A pgat_ token is meaningless at a different deployment (CONTRACT-la \xA78), so the daemon refuses to authenticate blind.
34
+ Either point PROGON_SERVER_URL back at ${n} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}i(ql,"assertServerMatchesEnrollment");import{createRequire as Vl}from"node:module";import{hostname as Hl}from"node:os";var Po=["darwin","linux","win32"],Co=["x64","arm64"];function Yl(n){return Po.includes(n)}i(Yl,"isSupportedPlatform");function Xl(n){return Co.includes(n)}i(Xl,"isSupportedArch");function zl(){let e=Vl(import.meta.url)("../../package.json"),t=typeof e=="object"&&e!==null?e.version:void 0;if(typeof t!="string"||t==="")throw new Error('[supervisor] The agent package.json has no usable "version" field, so the agent cannot state its version on the enroll wire (CONTRACT-la \xA75.1). This is a packaging defect \u2014 the daemon must not enroll under an invented version.');if(t.length>30)throw new Error(`[supervisor] The agent package version ${JSON.stringify(t)} is longer than the 30 characters CONTRACT-la \xA75.1 allows for agentVersion.`);return t}i(zl,"readAgentVersion");function Ae(){let n=process.platform;if(!Yl(n))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(n)}. The local agent runs on ${Po.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Xl(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Co.join(", ")} (CONTRACT-la \xA75.1).`);let t=Hl();if(t==="")throw new Error("[supervisor] os.hostname() returned an empty string, so this machine cannot be named on the enroll wire (CONTRACT-la \xA75.1 requires a non-empty hostname). Fix the host's network configuration.");return{hostname:t,platform:n,arch:e,agentVersion:zl()}}i(Ae,"describeAgentMachine");var Do=i(()=>{},"noop"),Pt=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let t=this.#e.then(e,e);return this.#e=t.then(Do,Do),t}};var Lo=p("supervisor-deadline"),Ke=class extends Error{static{i(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,t){super(`[supervisor] ${e} did not settle within ${t}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=t}};async function Q(n){let e=n.work(),t=!1;e.then(()=>{t&&Lo.warn("Abandoned work settled successfully after its deadline had passed",{operation:n.operation,timeoutMs:n.timeoutMs})},s=>{t&&Lo.warn("Abandoned work rejected after its deadline had passed",{operation:n.operation,timeoutMs:n.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,o=new Promise((s,a)=>{r=setTimeout(()=>{t=!0,a(new Ke(n.operation,n.timeoutMs))},n.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(Q,"withDeadline");function Je(n,e){return new Promise(t=>{if(e.aborted){t();return}let r=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);function o(){clearTimeout(r),t()}i(o,"onAbort"),e.addEventListener("abort",o,{once:!0})})}i(Je,"sleep");var ee=p("fail-reporter"),Ct=class{static{i(this,"RunFailureReporter")}#e;#t=null;#n=null;constructor(e){this.#e=e}hasVerdictFor(e){return this.#n===e}async report(e){if(this.#n===e.runId){ee.warn("Ignoring a second terminal verdict for a run this agent already reported",{runId:e.runId,ignoredReason:e.body.reason,stillUndelivered:this.#t!==null});return}let t=this.#t;t!==null&&t.runId!==e.runId&&ee.warn("Dropping an undelivered fail verdict \u2014 a different run needs one now",{droppedRunId:t.runId,droppedReason:t.body.reason,runId:e.runId}),this.#t={...e,attempt:0,nextAttemptAtMs:0},this.#n=e.runId,ee.error("Reporting run failure to the gateway",{runId:e.runId,...e.body}),await this.#r()}async retryPending(){let e=this.#t;e!==null&&(Date.now()<e.nextAttemptAtMs||await this.#r())}discardIfNotPublished(e){let t=this.#t;t!==null&&t.runId!==e&&(ee.info("Undelivered fail verdict discarded \u2014 its run is already terminal server-side",{runId:t.runId,reason:t.body.reason,publishedRunId:e}),this.#t=null)}async#r(){let e=this.#t;if(e!==null)try{let t=await this.#e.failRun(e.runId,e.body);ee.info("Fail verdict delivered",{runId:e.runId,reason:e.body.reason,status:t.status,attempts:e.attempt+1}),this.#t=null}catch(t){if(t instanceof E)throw t;if(t instanceof S)throw ee.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.body.reason,err:t.message}),this.#t=null,t;if(!(t instanceof k))throw t;let r=Ie({attempt:e.attempt,error:t});if(!r.retry){ee.error("Fail verdict abandoned \u2014 the gateway refused it definitively",{runId:e.runId,reason:e.body.reason,noRetryReason:r.reason,err:t.message}),this.#t=null;return}this.#t={runId:e.runId,body:e.body,attempt:e.attempt+1,nextAttemptAtMs:Date.now()+r.delayMs},ee.warn("Fail verdict not delivered \u2014 held for retry",{runId:e.runId,reason:e.body.reason,attempt:e.attempt+1,retryInMs:r.delayMs,err:t.message})}}};var Dt=120,Oe=Dt*1e3,En=3e4,Ne=3,Sn=45*1e3,Rn="agent shutdown";var Lt=p("task-launch-reconciler"),Gt=class{static{i(this,"TaskLaunchReconciler")}#e;#t=null;constructor(e){this.#e=e}async apply(e,t){let r=this.#t;(r===null||r.jobId!==e)&&(r={jobId:e,desired:new Set,attempted:new Set,closing:new Set},this.#t=r),r.desired=new Set(t);for(let o of this.#e.runtime.launchIdsWithInstance())r.desired.has(o)||r.closing.has(o)||this.#r(r,o);for(let o of r.desired)r.attempted.has(o)||(r.attempted.add(o),this.#n(r,o))}forgetJob(){this.#t=null}async handleLost(e){Lt.warn("Verification browser lost; its launch lease will end it, no restart or job fail",{...e})}async#n(e,t){let r=null;try{let o=await this.#e.client.issueLaunchSession(e.jobId,t);if(this.#t!==e||!e.desired.has(t))return;try{await Q({operation:`startLaunchInstance(${e.jobId}, ${t})`,timeoutMs:Oe,work:i(()=>this.#e.runtime.startLaunchInstance(e.jobId,t,o),"work")})}catch(s){r={stage:"launch",error:s}}}catch(o){r={stage:"session",error:o}}finally{await this.#e.detach(async()=>{if(r!==null){if(Lt.error("Verification browser could not start; the first-claim deadline ends its launch",{runId:e.jobId,launchId:t,stage:r.stage,err:r.error instanceof Error?r.error.message:String(r.error)}),r.stage==="launch"&&await this.#i(e,t),r.error instanceof E||r.error instanceof S)throw r.error;return}(this.#t!==e||!e.desired.has(t))&&await this.#i(e,t)})}}#r(e,t){e.closing.add(t),this.#i(e,t).finally(()=>{this.#e.detach(async()=>{e.closing.delete(t)})})}async#i(e,t){try{let r=await this.#e.runtime.disposeLaunchInstance(e.jobId,t);r!==null&&Lt.info("Verification browser disposed",{runId:e.jobId,launchId:t,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased})}catch(r){Lt.error("Verification browser cleanup failed",{runId:e.jobId,launchId:t,err:r instanceof Error?r.message:String(r)})}}};var Pe=p("run-monitor");function Ql(n,e){let t=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===n)?{healthy:!0}:ed(n,e.agentJob,t)?{healthy:!0}:{healthy:!1,reason:"playback_absent",detail:`the extension answered but nothing it holds describes a live run of ours (${td(e.tabs)}; ${nd(e.agentJob,t)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i(Ql,"judgeProbe");function ed(n,e,t){if(e===null||e.agentJobId!==n||e.updatedAt===null)return!1;let r=Date.parse(e.updatedAt);return Number.isNaN(r)?!1:t-r<=Sn}i(ed,"isJobPulseStanding");function td(n){if(n.length===0)return"tabStates is empty";let e=n.map(t=>t.playback===null?"none":t.playback.runId);return`${n.length} tab(s), playback run ids: ${e.join(", ")}`}i(td,"describeTabs");function nd(n,e){if(n===null)return"no job pulse is standing";if(n.updatedAt===null)return`job pulse: agentJobId=${n.agentJobId??"unreadable"}, updatedAt=unreadable`;let t=Date.parse(n.updatedAt),r=Number.isNaN(t)?"unparsable":`${String(e-t)}ms old`;return`job pulse: agentJobId=${n.agentJobId??"unreadable"}, ${r} (stale past ${String(Sn)}ms)`}i(nd,"describeJobMarker");var Ce=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#r=null;#i=0;#a=!1;constructor(e){this.#e=e;let t=Date.parse(e.deadlineAt);if(Number.isNaN(t))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=t}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());Pe.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:En,probeStrikeLimit:Ne}),this.#n=setInterval(()=>{this.#o()},En),this.#n.unref(),this.#r=setTimeout(()=>{this.#a||(this.stop(),Pe.error("Run reached its server-authored deadline",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt}),this.#e.onDeadline())},e),this.#r.unref()}stop(){this.#a=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#o(){if(this.#a)return;let e=Ql(this.#e.runId,await this.#s());if(this.#a)return;if(e.healthy){this.#i>0&&Pe.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#i}),this.#i=0;return}this.#i+=1;let t=`${e.reason}: ${e.detail}`;Pe.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#i,strikeLimit:Ne,reason:e.reason,detail:e.detail}),!(this.#i<Ne)&&(this.stop(),Pe.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Ne,detail:t}),this.#e.onBrowserGone(`${Ne} consecutive liveness probes failed (${t})`))}async#s(){try{return await this.#e.probe()}catch(e){let t=e instanceof Error?e.message:String(e);return Pe.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,identityId:this.#e.identityId,err:t}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:t}}}};var J=p("identity-reconciler"),Ut=class{static{i(this,"IdentityReconciler")}#e;#t;#n;#r=null;constructor(e){this.#e=e.runtime,this.#t=e.client,this.#n=e.detach}async apply(e,t,r){let o=this.#r;(o===null||o.jobId!==e)&&(this.forgetJob(),o={jobId:e,deadlineAt:t,desired:new Set,launching:new Set,closing:new Set,monitors:new Map},this.#r=o);let s=new Set(r),a=s.size!==o.desired.size||[...s].some(l=>!o.desired.has(l));o.desired=s,a&&J.info("Identities of the task job changed",{runId:e,identityIds:[...s],identityIdsWithInstance:this.#e.identityIdsWithInstance()});for(let l of this.#e.identityIdsWithInstance())s.has(l)||o.launching.has(l)||this.#l(o,l,"identity_left_run_block");for(let l of s)o.launching.has(l)||o.closing.has(l)||this.#e.identityIdsWithInstance().includes(l)||this.#i(o,l)}forgetJob(){let e=this.#r;if(e!==null){for(let t of e.monitors.values())t.stop();e.monitors.clear(),this.#r=null}}async handleLost(e){let t=this.#r;if(t===null||t.jobId!==e.jobId){J.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#m(t,e.identityId),this.#c(t,e.identityId,`the instance disappeared (${e.source})`)}#i(e,t){e.launching.add(t),this.#a(e,t)}async#a(e,t){let r=null;try{let o=await this.#t.issueIdentitySession(e.jobId,t);try{await Q({operation:`startIdentityInstance(${e.jobId}, ${t})`,timeoutMs:Oe,work:i(()=>this.#e.startIdentityInstance(e.jobId,t,o),"work")})}catch(s){r={stage:"launch",err:s}}}catch(o){r={stage:"session",err:o}}await this.#n(()=>this.#o(e,t,r))}async#o(e,t,r){e.launching.delete(t);let o=this.#r===e;if(r!==null){if(J.error("The instance of an identity could not be launched \u2014 no fail is reported",{runId:e.jobId,identityId:t,stage:r.stage,jobStillRunning:o,stillInRunBlock:e.desired.has(t),err:r.err instanceof Error?r.err.message:String(r.err)}),r.stage==="session"){if(r.err instanceof E||r.err instanceof S)throw r.err;return}await this.#u(e,t,"launch_failure");return}if(!o){await this.#u(e,t,"job_gone");return}if(!e.desired.has(t)){this.#l(e,t,"identity_left_run_block");return}this.#s(e,t)}#s(e,t){let r=new Ce({runId:e.jobId,identityId:t,deadlineAt:e.deadlineAt,probe:i(()=>this.#e.probeIdentityInstance(t),"probe"),onBrowserGone:i(o=>{this.#n(()=>this.#d(e,t,o))},"onBrowserGone"),onDeadline:i(()=>{this.#n(()=>this.#h(e,t,"max_duration"))},"onDeadline")});e.monitors.set(t,r),r.start(),J.info("Identity instance is up and monitored",{runId:e.jobId,identityId:t})}async#d(e,t,r){this.#r===e&&(e.monitors.delete(t),J.error("An identity instance lost its identity \u2014 closing it, no fail is reported",{runId:e.jobId,identityId:t,detail:r}),await this.#u(e,t,"pulse_lost"),this.#c(e,t,r))}#c(e,t,r){if(this.#r===e){if(!e.desired.has(t)){J.info("A lost identity instance is not relaunched \u2014 the identity left the run block",{runId:e.jobId,identityId:t,cause:r});return}e.launching.has(t)||e.closing.has(t)||(J.warn("Relaunching the instance of an identity that is still in the run block",{runId:e.jobId,identityId:t,cause:r}),this.#i(e,t))}}#l(e,t,r){e.closing.has(t)||(e.closing.add(t),this.#m(e,t),this.#p(e,t,r))}async#p(e,t,r){await this.#u(e,t,r),await this.#n(async()=>{e.closing.delete(t),this.#c(e,t,"the departed instance finished closing")})}async#h(e,t,r){this.#m(e,t),await this.#u(e,t,r)}#m(e,t){e.monitors.get(t)?.stop(),e.monitors.delete(t)}async#u(e,t,r){try{let o=await this.#e.disposeIdentityInstance(e.jobId,t);if(o===null)return;J.info("Identity instance disposed",{runId:e.jobId,identityId:t,trigger:r,disposeOutcome:o.outcome,instanceReleased:o.instanceReleased,durationMs:o.durationMs})}catch(o){J.error("Identity instance dispose finished with a failed cleanup step",{runId:e.jobId,identityId:t,trigger:r,err:o instanceof Error?o.message:String(o)})}}};var U=p("launch-run");async function Mo(n){let e;try{e=await rd(n)}finally{n.onClaimAnswered()}return e.kind!=="claimed"?e:id(n,e.payload)}i(Mo,"claimAndLaunch");async function rd(n){try{let e=await n.client.claimRun(n.runId);return U.info("Run claimed",od(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof E)throw e;if(e instanceof S)throw U.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:n.runId,err:e.message}),e;if(e instanceof ye||e instanceof oe)return U.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:n.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof k))throw e;return U.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:n.runId,err:e.message}),{kind:"claim_unavailable"}}}i(rd,"claimRun");function od(n){if(!("kind"in n))return{kind:"playback",runId:n.runId,scenarioId:n.scenarioId,projectId:n.projectId,runPurpose:n.runPurpose,headful:n.headful,maxRunDurationSec:n.maxRunDurationSec};if(n.kind==="swarm")return{kind:n.kind,runId:n.runId,workflowId:n.command.workflowId,headful:n.headful,maxRunDurationSec:n.maxRunDurationSec};if(n.kind==="scenario_launch")return{kind:n.kind,runId:n.runId,projectId:n.command.projectId,launchId:n.command.launchId,headful:n.headful,maxRunDurationSec:n.maxRunDurationSec};let e=n;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}i(od,"describeClaim");async function id(n,e){try{await Q({operation:`startRun(${e.runId})`,timeoutMs:Oe,work:i(()=>n.runtime.startRun({runId:e.runId,entryUrl:e.entryUrl,headful:e.headful,maxRunDurationSec:e.maxRunDurationSec,extensionSession:e.extensionSession,command:e.command}),"work")})}catch(r){return{kind:"failed",body:ad(n.runId,r)}}let t=n.runtime.getActiveInstance();return t===null||t.runId!==e.runId?(U.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:t===null?null:t.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:t}}i(id,"launchClaimedRun");var Go=500,Uo="\u2026";function sd(n){return n.length<=Go?n:n.slice(0,Go-Uo.length)+Uo}i(sd,"fitFailMessageToWire");function ad(n,e){if(e instanceof X){let t=sd(`stage ${e.stage}: ${fn(e)}`);if(e.stage==="entry_navigation"){let r=To(e);return U.error("Launch failed",{runId:n,stage:e.stage,failReason:e.failReason,entryFailure:r,err:e.message}),{reason:e.failReason,message:t,entryFailure:r}}return U.error("Launch failed",{runId:n,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:t}}return e instanceof Ke?(U.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:n,launchTimeoutSec:Dt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Dt}s`}):e instanceof z?(U.error("Launch refused by the instance fence \u2014 the run cannot be started here",{runId:n,userDataDir:e.userDataDir,err:e.message}),{reason:"launch_error",message:"a leftover instance directory blocks this run"}):(U.error("Launch failed with an unexpected error class",{runId:n,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}i(ad,"describeLaunchFailure");var M=p("instance-reconciler");function ld(n){let e=i(()=>{},"markSettled"),t=new Promise(a=>{e=a}),r=i(()=>{},"resolveClaimAnswer"),o=new Promise(a=>{r=a}),s={runId:n,cancelledBy:null,claimAnswered:!1,claimAnswer:o,markClaimAnswered:i(()=>{s.claimAnswered=!0,r()},"markClaimAnswered"),settled:t,markSettled:e};return s}i(ld,"createPendingLaunch");var q={kind:"reconciled"},Mt=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#r;#i=new Set;#a=null;#o=null;#s=null;#d;#c;#l=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#c=new Gt(e),this.#d=new Ut({runtime:e.runtime,client:e.client,detach:e.detach})}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#i=new Set(e.outcomes.map(t=>t.runId)),M.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#i]})}async reconcile(e){let t=e.run;this.#n.discardIfNotPublished(t===null?null:t.runId),this.#l=t===null?null:{runId:t.runId,identityIds:$o(t),launchIds:Fo(t)};let r=this.#o;if(r!==null)return t!==null&&t.runId===r.runId?t.phase!=="queued"?q:{kind:"claim_issued",runId:t.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}:(r.cancelledBy!==null||await this.#f(r,t===null?"desired_state_run_absent":"desired_state_runid_mismatch"),q);let o=this.#t.getActiveInstance();return t===null?(o!==null&&await this.dispose(o.runId,"desired_state_run_absent"),q):o!==null?o.runId===t.runId?(await this.#d.apply(o.runId,o.deadlineAt,$o(t)),await this.#c.apply(o.runId,Fo(t)),q):(await this.dispose(o.runId,"desired_state_runid_mismatch"),q):this.#n.hasVerdictFor(t.runId)?q:t.phase==="queued"?this.#s===t.runId?(M.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:t.runId}),{kind:"claim_issued",runId:t.runId,claimAnswer:null}):(this.#s=t.runId,this.#p(t.runId),q):(await this.#g(t.runId,t.phase),q)}async cancelLaunchAndSettle(e){let t=this.#o;return t===null?null:(M.warn("Stopping a launch that is still in flight",{runId:t.runId,trigger:e}),t.cancelledBy=e,this.#r(()=>this.dispose(t.runId,e)),await t.settled,t.runId)}async handleIdentityInstanceLost(e){await this.#d.handleLost(e)}async handleLaunchInstanceLost(e){await this.#c.handleLost(e)}async handleInstanceLost(e){M.error("The runtime reported a lost browser instance",{...e}),await this.#y(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,t){this.stopMonitor(),this.#d.forgetJob(),this.#c.forgetJob();try{let r=await this.#t.disposeRun(e);M.info("Instance disposed",{runId:e,trigger:t,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){M.error("Dispose finished with a failed cleanup step",{runId:e,trigger:t,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#a?.stop(),this.#a=null}#p(e){let t=ld(e);this.#o=t,this.#h(t)}async#h(e){try{let t=await this.#m(e);await this.#r(()=>this.#u(e,t))}finally{e.markSettled()}}async#m(e){try{return{kind:"outcome",outcome:await Mo({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(t){return{kind:"thrown",error:t}}}async#u(e,t){if(this.#o===e&&(this.#o=null),t.kind==="thrown")throw t.error;let r=t.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){M.warn("A cancelled launch completed anyway \u2014 disposing what it brought up",{runId:e.runId,trigger:e.cancelledBy}),await this.dispose(e.runId,e.cancelledBy);return}this.#w(r.instance.runId,r.instance.deadlineAt),this.#l?.runId===r.instance.runId&&(await this.#d.apply(r.instance.runId,r.instance.deadlineAt,this.#l.identityIds),await this.#c.apply(r.instance.runId,this.#l.launchIds));return;case"claim_refused":case"claim_unavailable":case"instance_lost_immediately":return;case"failed":if(await this.dispose(e.runId,"launch_failure"),e.cancelledBy!==null){M.info("A cancelled launch failed on the way down \u2014 no verdict is sent",{runId:e.runId,trigger:e.cancelledBy,suppressedReason:r.body.reason});return}await this.#n.report({runId:e.runId,body:r.body});return}}async#f(e,t){M.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:t}),e.cancelledBy=t,await this.dispose(e.runId,t)}#w(e,t){this.#a=new Ce({runId:e,identityId:null,deadlineAt:t,probe:i(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:i(r=>{this.#r(()=>this.#y(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:i(()=>{this.#r(()=>this.#y(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#g(e,t){let r=this.#i.has(e),o=r?"browser_gone":"launch_error";M.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:t,sweptAtStartup:r,reason:o}),await this.#n.report({runId:e,body:{reason:o,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"}})}async#y(e,t,r,o){await this.dispose(e,o),await this.#n.report({runId:e,body:{reason:t,message:r}})}};function $o(n){return n.identities===void 0?[]:n.identities.map(e=>e.identityId)}i($o,"identityIdsOf");function Fo(n){return n.launches===void 0?[]:n.launches.map(e=>e.launchId)}i(Fo,"launchIdsOf");var jo="Create a new enrollment code in Progon (Settings \u2192 Agents) and run 'progon-agent enroll <code>' to enroll this machine again. The wipe removed the state file, so an installed package now takes the deployment it was built for; on a source checkout add --server <url>.",Bo={revoked:{exitCode:1,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+jo},reenroll_required:{exitCode:1,level:"error",message:"progon-agent stopped: this machine's agent token was superseded and the server no longer accepts it, so the credential has been wiped. This is not a revocation \u2014 the token was replaced and the replacement could not be kept. "+jo},credential_unusable:{exitCode:1,level:"error",message:"progon-agent stopped: the server no longer accepts the agent token this daemon was given in PROGON_AGENT_TOKEN, and a credential the operator owns is not one this daemon can replace. NOTHING WAS WIPED \u2014 the state directory belongs to an enrollment this mode never reads and may still be perfectly valid. Set PROGON_AGENT_TOKEN to a current token and start the daemon again, or unset it and enroll this machine so the daemon can rotate on its own."},fatal:{exitCode:1,level:"error",message:"progon-agent stopped: the desired-state poll was refused definitively and no repetition can change that answer, so the daemon has disposed its browser and stopped instead of live-locking. The preceding error line names the reason and the server's own message. Restarting is the process supervisor's call once that condition has been fixed."},stopped:{exitCode:null,level:"info",message:"progon-agent stopped"}},Wo={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var x=p("token-rotation"),Ko=1440*60*1e3,$t=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#i=!1;#a=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let t=this.#r;if(t!==null)return t;let r=this.#o(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return x.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(t){if(t instanceof S)return"reenroll_required";if(t instanceof E)throw t;if(t instanceof k)return x.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:t.operation,err:t.message}),"alive";throw t}}async settle(){let e=this.#r;e!==null&&await e.then(()=>{},()=>{})}async#o(e){if(this.#n==="env_token")return this.#i||(this.#i=!0,x.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#a)return{kind:"superseded_in_grace"};let t=this.#u();if(t.kind!=="identity")return this.#f(t);let r=t.identity,o=await this.#s(e);return o.kind!=="status"?o.outcome:o.value.rotationDue?await this.#c(r,o.value.tokenRotatedAt,e):this.#d(r,o.value.tokenRotatedAt)}async#s(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(t){if(t instanceof S)return x.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(t instanceof E)throw t;if(t instanceof k)return x.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:t.operation,err:t.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw t}}#d(e,t){return e.tokenRotatedAt===t?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#m({...e,tokenRotatedAt:t},"first observed rotation marker"),{kind:"not_due"}):(this.#a=!0,x.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:t}),{kind:"superseded_in_grace"})}async#c(e,t,r){let o;try{o=(await this.#e.rotateToken()).agentToken}catch(a){if(a instanceof E)throw a;if(a instanceof S)return await this.#l(r);if(a instanceof k)return x.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:a.operation,err:a.message}),await this.#p(t);throw a}this.#m({...e,agentToken:o,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(o);let s=await this.#h();return s.kind==="reenroll_required"?s:(s.kind==="observed"&&this.#m({...e,agentToken:o,tokenRotatedAt:s.tokenRotatedAt},"rotation marker of the new agent token"),x.info("Agent token rotated"),{kind:"rotated"})}async#l(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#a=!0,x.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#p(e){let t=await this.#s(void 0);return t.kind!=="status"?t.outcome:t.value.tokenRotatedAt===e?(x.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#a=!0,x.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:t.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#h(){let e=await this.#s(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(x.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#m(e,t){try{return me(this.#t,e),!0}catch(r){return x.error(`The ${t} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#u(){let e;try{e=F(this.#t)}catch(t){return{kind:"unreadable",err:t instanceof Error?t.message:String(t)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#f(e){return e.kind==="unreadable"?(x.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(x.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var A=p("run-supervisor"),kn=i(()=>Promise.resolve(),"noVerdictOwed"),Ft=class{static{i(this,"RunSupervisor")}#e;#t;#n;#r=new Pt;#i;#a;#o=null;#s=0;#d=0;#c=!1;#l=new AbortController;#p=null;#h=!1;#m=!1;#u;#f=null;#w=null;constructor(e){this.#e=e.client,this.#i=e.stateDir,this.#a=e.pollWaitSec,this.#u=e.tokenRotation,this.#t=new Ct(e.client),this.#l.signal.addEventListener("abort",()=>this.#L(),{once:!0});let t=e.createRuntime({onInstanceLost:i(r=>{this.#E(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:i(r=>{this.#E(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost"),onLaunchInstanceLost:i(r=>{this.#E(()=>this.#n.handleLaunchInstanceLost(r))},"onLaunchInstanceLost")});this.#n=new Mt({client:e.client,runtime:t,reporter:this.#t,detach:i(r=>this.#E(r),"detach")})}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#C();if(e!==null)return e;for(this.#I(),await this.#y();!this.#c;){let t=this.#p;if(t!==null)return await this.#k(t),"revoked";if(this.#h)return await this.#b(),"reenroll_required";if(this.#m)return await this.#A(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#G();this.#s=0;let o=await this.#r.run(()=>this.#n.reconcile(r));await this.#U(o)}catch(r){if(r instanceof E)return await this.#k(r),"revoked";if(r instanceof S&&await this.#x(r))return await this.#b(),"reenroll_required";if(this.#c)break;if(this.#S())continue;let o=await this.#F(r);if(o!==null)return o==="credential_unusable"?await this.#A():await this.#$(),o}}return this.#g()}async#g(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#y(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(await this.#N(e),this.#S())return;if(!(e instanceof k))throw e;A.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let t=this.#w;if(t!==null)return A.info("A shutdown is already in progress \u2014 joining it",{cause:e}),t;let r=this.#P(e);return this.#w=r,r}async#P(e){A.info("Shutting down",{cause:e}),await this.#_(e==="fatal"?"fatal":"stopped",t=>this.#T(t))}async#_(e,t){this.#c=!0,this.#o?.abort(),this.#l.abort();let r=Wo[e],o=await this.#n.cancelLaunchAndSettle(r);await this.#r.run(async()=>{this.#n.stopMonitor();let s=this.#n.activeRunId;s!==null&&await this.#n.dispose(s,r),await t({activeRunId:s,launchingRunId:o})}),await this.#u.settle()}async#T(e){let{activeRunId:t,launchingRunId:r}=e;if(t!==null){await this.#v(()=>this.#t.report({runId:t,body:{reason:"browser_gone",message:Rn}}));return}if(r!==null){await this.#v(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:Rn}}));return}await this.#v(()=>this.#t.retryPending())}async#C(){try{if((await this.#u.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof E)return await this.#k(e),"revoked";throw e}return await this.#b(),"reenroll_required"}#I(){if(this.#c||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#f=null,this.#D().finally(()=>{this.#I()})},Ko);e.unref(),this.#f=e}async#D(){try{if((await this.#u.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#h=!0,this.#o?.abort()}catch(e){await this.#O(e)}}#L(){this.#f!==null&&(clearTimeout(this.#f),this.#f=null)}async#x(e){A.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#u.diagnoseSuperseded(this.#l.signal)==="reenroll_required"}catch(t){if(t instanceof E)return this.#p=t,!1;throw t}}async#G(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#a,signal:e.signal})}finally{this.#o=null}}async#U(e){if(e.kind==="reconciled"){this.#d=0;return}await this.#M(e.runId,e.claimAnswer)}async#M(e,t){let r=le(this.#d);A.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#d,waitMs:r,claimOnTheWire:t!==null}),this.#d+=1;let o=new AbortController;if(this.#o=o,this.#l.signal.aborted||this.#S()){this.#o=null;return}t?.then(()=>o.abort());try{await Je(r,o.signal)}finally{this.#o=null}}async#R(){await this.#u.settle(),Rr(this.#i)}async#k(e){A.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#_("revoked",kn),await this.#R()}async#A(){A.error("The server refuses the credential this daemon runs on as superseded, and this daemon has no way to replace it \u2014 disposing the browser and stopping so the operator, and the process supervisor, both learn it now. The state directory is left untouched: this credential did not come from there."),await this.#_("credential_unusable",kn)}async#$(){await this.#_("fatal",e=>this.#T(e))}async#b(){A.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#_("reenroll_required",kn),await this.#R()}async#F(e){if(!(e instanceof k))throw e;let t=this.#j(e);return t.kind==="exit"?t.exit:(this.#s+=1,await Je(t.delayMs,this.#l.signal),null)}#j(e){if(e instanceof S){if(!this.#u.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=le(this.#s);return A.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#s,retryInMs:r}),{kind:"retry",delayMs:r}}let t=Ie({attempt:this.#s,error:e});return t.retry?(A.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#s,retryInMs:t.delayMs,err:e.message}),{kind:"retry",delayMs:t.delayMs}):(A.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:t.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#E(e){return this.#r.run(e).catch(t=>this.#O(t))}async#O(e){await this.#N(e)||A.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#N(e){if(e instanceof E)return this.#p=e,this.#o?.abort(),!0;if(!(e instanceof S))return!1;try{await this.#x(e)?this.#h=!0:this.#u.canDiagnoseFromTheWire||(this.#m=!0)}catch(t){return A.error("The superseded diagnosis failed after a gateway refusal off the poll",{operation:e.operation,err:t instanceof Error?t.message:String(t)}),!0}return this.#S()&&this.#o?.abort(),!0}#S(){return this.#p!==null||this.#h||this.#m}async#v(e){try{await e()}catch(t){if(t instanceof S){A.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:t.operation});return}if(t instanceof E){await this.#R(),A.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:t.signal});return}throw t}}};var Jo=p("supervisor-boot");async function qo(){let n=fe();Jo.info("Config loaded",{serverUrlOrigin:new URL(n.serverUrl).origin,serverUrlSource:n.serverUrlSource,stateDir:n.stateDir,headfulOverride:n.headfulOverride,allowInsecureHttps:n.allowInsecureHttps});let e=Ae(),t=await xe({config:n,machine:e});Jo.info("Agent identity resolved",{source:t.source,agentId:t.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=Gr({overridePath:n.extensionDistOverride,stateDir:n.stateDir,agentId:t.agentId});await ze({stdio:"pipe"});let o=new ut({serverUrl:n.serverUrl,agentToken:t.agentToken}),s=new $t({client:o,stateDir:n.stateDir,identitySource:t.source});return new Ft({client:o,stateDir:n.stateDir,pollWaitSec:t.pollWaitSec,tokenRotation:s,createRuntime:i(({onInstanceLost:a,onIdentityInstanceLost:l,onLaunchInstanceLost:c})=>new Ot({stateDir:n.stateDir,extensionDist:r,headfulOverride:n.headfulOverride,allowInsecureHttps:n.allowInsecureHttps,onInstanceLost:a,onIdentityInstanceLost:l,onLaunchInstanceLost:c}),"createRuntime")})}i(qo,"bootRunSupervisor");var bn=p("daemon");async function Ho(){Or(),bn.info("progon-agent starting");let n=await qo();Nr(async r=>{await n.shutdown(r)});let e;try{e=await n.run()}catch(r){throw await n.shutdown("fatal").catch(o=>{throw new AggregateError([r,o],`${Vo(r)} \u2014 and the teardown after it failed too, so the browser may still be running: ${Vo(o)}`)}),r}let t=Bo[e];return t.level==="error"?bn.error(t.message):bn.info(t.message),t.exitCode}i(Ho,"runDaemon");function Vo(n){return n instanceof Error?n.message:String(n)}i(Vo,"describe");import{createHash as wd,randomBytes as yd}from"node:crypto";import{z as I}from"zod";var Yo=I.object({requestId:I.uuid(),mode:I.literal("device"),userCode:I.string().min(1),verificationUrl:I.url(),expiresAt:I.iso.datetime({offset:!0}),pollIntervalSec:I.number().int().positive()}),Xo=I.object({status:I.literal("authorization_pending"),expiresAt:I.iso.datetime({offset:!0}),pollIntervalSec:I.number().int().positive()}),dd=I.object({companyName:I.string(),approvedByEmail:I.string(),approvedAt:I.string()}),zo=I.object({credential:Ye,approval:dd});var Zo=p("gateway-enrollment-request"),jt=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??pt}async create(e){let t=await ie({operation:"enrollment_request_create",method:"POST",url:P(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Fr}),r=O("enrollment_request_create",Yo.safeParse(t));return Zo.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let t=await ie({operation:"enrollment_request_poll",method:"POST",url:P(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:jr}),r=typeof t=="object"&&t!==null?t:null;if(r!==null&&"credential"in r){let o=O("enrollment_request_poll",zo.safeParse(t));return Zo.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=O("enrollment_request_poll",Xo.safeParse(t));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new B("enrollment_request_poll","the 2xx body is neither the authorization_pending answer nor the success envelope CONTRACT-phase-c \xA74.1 M2 defines")}async cancel(e){await ie({operation:"enrollment_request_cancel",method:"POST",url:P(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Br})}};import{spawn as cd}from"node:child_process";var qe=p("browser-open");function Bt(n){return n!==void 0&&n!==""}i(Bt,"isSet");function ud(n,e){return!(Bt(n.SSH_CONNECTION)||Bt(n.SSH_TTY)||e==="linux"&&!Bt(n.DISPLAY)&&!Bt(n.WAYLAND_DISPLAY))}i(ud,"shouldAttemptBrowserOpen");var pd=/[&|^<>"'` ]/;function hd(n){let e;try{e=new URL(n)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||n!==e.href?!1:!pd.test(n)}i(hd,"isSpawnSafeUrl");function md(n,e){switch(e){case"darwin":return{command:"open",args:[n]};case"linux":return{command:"xdg-open",args:[n]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",n]};default:return null}}i(md,"browserOpenCommand");function Qo(n,e,t){if(!ud(e,t)){qe.debug("Not opening a browser: this host has no desktop to open one on",{platform:t});return}if(!hd(n)){qe.warn('Not opening a browser: the verification URL the server returned is not safe to hand to a spawned process. Follow the "Approve at:" link printed above instead',{platform:t});return}let r=md(n,t);if(r===null){qe.debug("Not opening a browser: no opener is defined for this platform",{platform:t});return}try{let o=cd(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",s=>{qe.debug("Could not start the browser; the approval URL was printed instead",{platform:t,command:r.command,err:s.message})}),o.unref()}catch(o){qe.debug("Could not start the browser; the approval URL was printed instead",{platform:t,command:r.command,err:o instanceof Error?o.message:String(o)})}}i(Qo,"openVerificationUrl");var fd=30,gd=5;function ei(n){return{intervalSec:n.pollIntervalSec,deadlineMs:n.timeoutSec===null?n.expiresAtMs:Math.min(n.expiresAtMs,n.nowMs+n.timeoutSec*1e3)}}i(ei,"initialPollSchedule");function Wt(n,e){if(e.kind==="pending")return{state:n,delayMs:n.intervalSec*1e3};if(e.kind==="slow_down"){let r=n.intervalSec+gd,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(o,fd);return{state:{intervalSec:s,deadlineMs:n.deadlineMs},delayMs:s*1e3}}let t=le(e.attempt,e.rng);return{state:n,delayMs:Math.max(n.intervalSec*1e3,t)}}i(Wt,"nextPollDelayMs");function ti(n,e){return e>=n.deadlineMs}i(ti,"isDeadlinePassed");function ni(n,e,t){return Math.max(0,Math.min(e,n.deadlineMs-t))}i(ni,"clampDelayToDeadline");var Le=p("device-enrollment"),_d=24,Ed=2e3,vn=0,De=1,oi=130,Sd="This machine is already enrolled. Start the daemon with: progon-agent start",Rd="Enrollment was denied in the browser. Nothing was created on this machine.",kd="Cancelled. Nothing was saved on this machine.",bd="progon-agent: interrupted again \u2014 exiting immediately. The enrollment request was not withdrawn; it expires on its own. Nothing was saved on this machine.";function ri(n){return`Enrollment request expired. Run: progon-agent enroll --server ${n}`}i(ri,"expiredLine");function vd(n,e,t){return`This machine is already enrolled against ${n}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
35
35
  To enroll this machine for ${e} as well, give the second agent its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll --server ${e} \u2014 and give 'progon-agent start' the same variable, since that directory is where the second credential and its server live.
36
- To move this machine to ${e} instead, remove the state file in ${n} first, then run: progon-agent enroll --server ${e}`}i(ad,"otherDeploymentLine");function sd(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(sd,"timedOutLine");function ld(t){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${t}`}i(ld,"alreadyCompletedLine");function dd(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}i(dd,"noLongerValidLine");async function Ko(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=ue(),r=be(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return md(n,r,t.fetchImpl,t.rng);let a=$(n.stateDir);if(a!==null)return Ze(a.serverUrl,n.serverUrl)?(process.stdout.write(`${nd}
37
- `),pn):(process.stdout.write(`${ad(a.serverUrl,n.serverUrl,n.stateDir)}
38
- `),ve);let s=Ql(ed).toString("base64url"),d=new Ot(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),c=await d.create(fd(s));return pd(c),t.openBrowser&&Mo(c.verificationUrl,e,process.platform),cd({client:d,config:n,created:c,deviceSecret:s,timeoutSec:t.timeoutSec,rng:t.rng})}i(Ko,"runDeviceEnrollment");async function cd(t){let{client:e,config:n,created:r,deviceSecret:o,timeoutSec:a,rng:s}=t,d=Date.parse(r.expiresAt),c=$o({pollIntervalSec:r.pollIntervalSec,expiresAtMs:d,timeoutSec:a,nowMs:Date.now()}),g=c.intervalSec*1e3,y=0,w={signal:null},f=new AbortController,R=i(v=>{w.signal!==null&&(process.stderr.write(`${id}
39
- `),process.exit(Bo)),w.signal=v,f.abort()},"onSignal");process.on("SIGINT",R),process.on("SIGTERM",R);try{for(;;){if(await Ue(jo(c,g,Date.now()),f.signal),w.signal!==null)return await ud(e,o,w.signal);if(Fo(c,Date.now()))return a!==null&&c.deadlineMs<d?process.stdout.write(`${sd(a,r.verificationUrl)}
40
- `):process.stdout.write(`${Wo(n.serverUrl)}
41
- `),ve;let v;try{v=await e.poll(o)}catch(A){if(A instanceof ge)return process.stdout.write(`${rd}
42
- `),ve;if(A instanceof we)return process.stdout.write(`${Wo(n.serverUrl)}
43
- `),ve;if(A instanceof ye)return Ae.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:A.errorCode,status:A.status}),process.stdout.write(`${ld(n.serverUrl)}
44
- `),ve;if(A instanceof _e)return Ae.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:A.errorCode,status:A.status}),process.stdout.write(`${dd(n.serverUrl)}
45
- `),ve;if(A instanceof fe){let xe=Pt(c,{kind:"slow_down",retryAfterSec:A.retryAfterSec});c=xe.state,g=xe.delayMs,Ae.warn("The server asked this machine to poll more slowly",{intervalSec:c.intervalSec,retryAfterSec:A.retryAfterSec});continue}if(A instanceof F||A instanceof b&&A.status>=500){let xe=Pt(c,{kind:"transport_error",attempt:y,rng:s});y+=1,c=xe.state,g=xe.delayMs,Ae.warn("The enrollment poll failed; retrying until the request expires",{attempt:y,delayMs:g,err:A.message});continue}throw A}if(v.kind==="enrolled")return ce(n.stateDir,{agentId:v.credential.agentId,agentToken:v.credential.agentToken,protocolVersion:v.credential.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${v.approval.companyName} (approved by ${v.approval.approvedByEmail}). Start the daemon: progon-agent start
46
- `),pn;y=0;let $e=Pt(c,{kind:"pending"});c=$e.state,g=$e.delayMs}}finally{process.off("SIGINT",R),process.off("SIGTERM",R)}}i(cd,"waitForApproval");async function ud(t,e,n){try{await bt({operation:"device enrollment cancel",timeoutMs:td,work:i(()=>t.cancel(e),"work")})}catch(r){Ae.warn("The enrollment request could not be withdrawn on the server; it expires on its own within its TTL and no agent was created",{signal:n,err:r instanceof Error?r.message:String(r)})}return process.stdout.write(`${od}
47
- `),Bo}i(ud,"cancelRequest");async function md(t,e,n,r){let o=await Re({config:t,machine:e,fetchImpl:n,rng:r});return St(o,t),Ae.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:e.hostname,stateDir:t.stateDir}),pn}i(md,"redeemLegacyEnrollmentCode");function pd(t){process.stdout.write(`Enrollment requested for this machine.
48
- Confirmation code: ${t.userCode}
49
- Approve at: ${t.verificationUrl}
50
- Waiting for approval (expires in ${hd(t.expiresAt)})...
51
- `)}i(pd,"printRequestOpened");function hd(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}i(hd,"describeExpiry");function fd(t){return Zl("sha256").update(t,"utf8").digest("hex")}i(fd,"sha256Hex");var yd=m("cli"),qo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
36
+ To move this machine to ${e} instead, remove the state file in ${t} first, then run: progon-agent enroll --server ${e}`}i(vd,"otherDeploymentLine");function Td(n,e){return`Timed out after ${n}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(Td,"timedOutLine");function Id(n){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${n}`}i(Id,"alreadyCompletedLine");function xd(n){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${n}`}i(xd,"noLongerValidLine");async function ii(n){let e=n.env??process.env;n.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=n.serverUrl);let t=fe(),r=Ae(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return Nd(t,r,n.fetchImpl,n.rng);let s=F(t.stateDir);if(s!==null)return rt(s.serverUrl,t.serverUrl)?(process.stdout.write(`${Sd}
37
+ `),vn):(process.stdout.write(`${vd(s.serverUrl,t.serverUrl,t.stateDir)}
38
+ `),De);let a=yd(_d).toString("base64url"),l=new jt(n.fetchImpl===void 0?{serverUrl:t.serverUrl,machine:r}:{serverUrl:t.serverUrl,machine:r,fetchImpl:n.fetchImpl}),c=await l.create(Dd(a));return Pd(c),n.openBrowser&&Qo(c.verificationUrl,e,process.platform),Ad({client:l,config:t,created:c,deviceSecret:a,timeoutSec:n.timeoutSec,rng:n.rng})}i(ii,"runDeviceEnrollment");async function Ad(n){let{client:e,config:t,created:r,deviceSecret:o,timeoutSec:s,rng:a}=n,l=Date.parse(r.expiresAt),c=ei({pollIntervalSec:r.pollIntervalSec,expiresAtMs:l,timeoutSec:s,nowMs:Date.now()}),w=c.intervalSec*1e3,f=0,g={signal:null},m=new AbortController,v=i(b=>{g.signal!==null&&(process.stderr.write(`${bd}
39
+ `),process.exit(oi)),g.signal=b,m.abort()},"onSignal");process.on("SIGINT",v),process.on("SIGTERM",v);try{for(;;){if(await Je(ni(c,w,Date.now()),m.signal),g.signal!==null)return await Od(e,o,g.signal);if(ti(c,Date.now()))return s!==null&&c.deadlineMs<l?process.stdout.write(`${Td(s,r.verificationUrl)}
40
+ `):process.stdout.write(`${ri(t.serverUrl)}
41
+ `),De;let b;try{b=await e.poll(o)}catch(T){if(T instanceof Ee)return process.stdout.write(`${Rd}
42
+ `),De;if(T instanceof Se)return process.stdout.write(`${ri(t.serverUrl)}
43
+ `),De;if(T instanceof Re)return Le.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${Id(t.serverUrl)}
44
+ `),De;if(T instanceof ke)return Le.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${xd(t.serverUrl)}
45
+ `),De;if(T instanceof _e){let Ge=Wt(c,{kind:"slow_down",retryAfterSec:T.retryAfterSec});c=Ge.state,w=Ge.delayMs,Le.warn("The server asked this machine to poll more slowly",{intervalSec:c.intervalSec,retryAfterSec:T.retryAfterSec});continue}if(T instanceof j||T instanceof R&&T.status>=500){let Ge=Wt(c,{kind:"transport_error",attempt:f,rng:a});f+=1,c=Ge.state,w=Ge.delayMs,Le.warn("The enrollment poll failed; retrying until the request expires",{attempt:f,delayMs:w,err:T.message});continue}throw T}if(b.kind==="enrolled")return me(t.stateDir,{agentId:b.credential.agentId,agentToken:b.credential.agentToken,protocolVersion:b.credential.protocolVersion,serverUrl:t.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${b.approval.companyName} (approved by ${b.approval.approvedByEmail}). Start the daemon: progon-agent start
46
+ `),vn;f=0;let Ve=Wt(c,{kind:"pending"});c=Ve.state,w=Ve.delayMs}}finally{process.off("SIGINT",v),process.off("SIGTERM",v)}}i(Ad,"waitForApproval");async function Od(n,e,t){try{await Q({operation:"device enrollment cancel",timeoutMs:Ed,work:i(()=>n.cancel(e),"work")})}catch(r){Le.warn("The enrollment request could not be withdrawn on the server; it expires on its own within its TTL and no agent was created",{signal:t,err:r instanceof Error?r.message:String(r)})}return process.stdout.write(`${kd}
47
+ `),oi}i(Od,"cancelRequest");async function Nd(n,e,t,r){let o=await xe({config:n,machine:e,fetchImpl:t,rng:r});return Nt(o,n),Le.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:e.hostname,stateDir:n.stateDir}),vn}i(Nd,"redeemLegacyEnrollmentCode");function Pd(n){process.stdout.write(`Enrollment requested for this machine.
48
+ Confirmation code: ${n.userCode}
49
+ Approve at: ${n.verificationUrl}
50
+ Waiting for approval (expires in ${Cd(n.expiresAt)})...
51
+ `)}i(Pd,"printRequestOpened");function Cd(n){let e=Date.parse(n)-Date.now();return`${Math.ceil(e/6e4)}m`}i(Cd,"describeExpiry");function Dd(n){return wd("sha256").update(n,"utf8").digest("hex")}i(Dd,"sha256Hex");var Ud=p("cli"),si=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
52
52
 
53
53
  Usage:
54
54
  progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
@@ -113,10 +113,10 @@ Environment (see CONTRACT-la \xA78 for the full list):
113
113
  name one (\xA71 D-C, \xA715 A30.1).
114
114
  PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
115
115
  state file and over enrollment.
116
- PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function Yo(t){let[e,...n]=t;return e===void 0||e==="--help"||e==="-h"||e==="help"?{kind:"usage",reason:null}:e==="start"?n.length>0?{kind:"usage",reason:"'start' takes no arguments"}:{kind:"start"}:e==="install-browser"?n.length>0?{kind:"usage",reason:"'install-browser' takes no arguments"}:{kind:"install-browser"}:e==="enroll"?Ed(n):{kind:"usage",reason:`unknown command '${e}'`}}i(Yo,"parseCliArgs");function _d(t){return t.startsWith("-")&&t.length<32}i(_d,"isOptionInCodeSlot");function Ed(t){let[e,...n]=t;if(e===void 0||_d(e))return Sd(t);if(n.length===0)return{kind:"enroll",code:e,serverUrl:void 0};let[r,o,...a]=n;return r!=="--server"?{kind:"usage",reason:`unknown option '${String(r)}' for 'enroll'`}:o===void 0?{kind:"usage",reason:"'--server' needs a URL"}:a.length>0?{kind:"usage",reason:"unexpected arguments after '--server'"}:{kind:"enroll",code:e,serverUrl:o}}i(Ed,"parseEnroll");var Vo=1,Ho=3600;function Sd(t){let e,n=!0,r=null;for(let o=0;o<t.length;o+=1){let a=t[o];if(a==="--no-open"){n=!1;continue}if(a==="--server"){let s=t[o+1];if(s===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=s,o+=1;continue}if(a==="--timeout"){let s=t[o+1];if(s===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(s))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${s}'`};let d=Number(s);if(d<Vo||d>Ho)return{kind:"usage",reason:`'--timeout' must be between ${Vo} and ${Ho} seconds, got '${s}'`};r=d,o+=1;continue}return{kind:"usage",reason:`unknown option '${String(a)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r}}i(Sd,"parseEnrollDevice");async function Rd(t){let e=Yo(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${qo}
116
+ PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function ci(n){let[e,...t]=n;return e===void 0||e==="--help"||e==="-h"||e==="help"?{kind:"usage",reason:null}:e==="start"?t.length>0?{kind:"usage",reason:"'start' takes no arguments"}:{kind:"start"}:e==="install-browser"?t.length>0?{kind:"usage",reason:"'install-browser' takes no arguments"}:{kind:"install-browser"}:e==="enroll"?$d(t):{kind:"usage",reason:`unknown command '${e}'`}}i(ci,"parseCliArgs");function Md(n){return n.startsWith("-")&&n.length<32}i(Md,"isOptionInCodeSlot");function $d(n){let[e,...t]=n;if(e===void 0||Md(e))return Fd(n);if(t.length===0)return{kind:"enroll",code:e,serverUrl:void 0};let[r,o,...s]=t;return r!=="--server"?{kind:"usage",reason:`unknown option '${String(r)}' for 'enroll'`}:o===void 0?{kind:"usage",reason:"'--server' needs a URL"}:s.length>0?{kind:"usage",reason:"unexpected arguments after '--server'"}:{kind:"enroll",code:e,serverUrl:o}}i($d,"parseEnroll");var ai=1,li=3600;function Fd(n){let e,t=!0,r=null;for(let o=0;o<n.length;o+=1){let s=n[o];if(s==="--no-open"){t=!1;continue}if(s==="--server"){let a=n[o+1];if(a===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=a,o+=1;continue}if(s==="--timeout"){let a=n[o+1];if(a===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(a))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${a}'`};let l=Number(a);if(l<ai||l>li)return{kind:"usage",reason:`'--timeout' must be between ${ai} and ${li} seconds, got '${a}'`};r=l,o+=1;continue}return{kind:"usage",reason:`unknown option '${String(s)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:t,timeoutSec:r}}i(Fd,"parseEnrollDevice");async function jd(n){let e=ci(n);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${si}
117
117
  `),0):(process.stderr.write(`progon-agent: ${e.reason}
118
118
 
119
- ${qo}
120
- `),2);case"enroll":return kd(e.code,e.serverUrl);case"enroll-device":return Ko({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return bd();case"start":return Co()}}i(Rd,"runAgentCli");async function bd(){return await Ve({stdio:"inherit"}),0}i(bd,"installBrowser");async function kd(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=ue(),r=be(),o=await Re({config:n,machine:r});return St(o,n),yd.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:n.stateDir}),0}i(kd,"enrollThisMachine");function Td(t,e){let n=M(t instanceof Error?t.message:String(t));if((e.kind==="enroll"||e.kind==="enroll-device")&&t instanceof p)return`${n}
121
- `;let o=t instanceof Error?t.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:n,stack:o===void 0?void 0:M(o)})+`
122
- `}i(Td,"formatCliFailure");function vd(t){Rd(t).then(e=>{e!==null&&process.exit(e)}).catch(e=>{process.stderr.write(Td(e,Yo(t))),process.exit(1)})}i(vd,"runAgentCliProcess");var Jo=process.argv[1];Jo!==void 0&&import.meta.url===wd(gd(Jo)).href&&vd(process.argv.slice(2));export{Td as formatCliFailure,Yo as parseCliArgs,Rd as runAgentCli,vd as runAgentCliProcess};
119
+ ${si}
120
+ `),2);case"enroll":return Wd(e.code,e.serverUrl);case"enroll-device":return ii({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return Bd();case"start":return Ho()}}i(jd,"runAgentCli");async function Bd(){return await ze({stdio:"inherit"}),0}i(Bd,"installBrowser");async function Wd(n,e){process.env.PROGON_AGENT_ENROLL_CODE=n,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let t=fe(),r=Ae(),o=await xe({config:t,machine:r});return Nt(o,t),Ud.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:t.stateDir}),0}i(Wd,"enrollThisMachine");function Kd(n,e){let t=$(n instanceof Error?n.message:String(n));if((e.kind==="enroll"||e.kind==="enroll-device")&&n instanceof h)return`${t}
121
+ `;let o=n instanceof Error?n.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:t,stack:o===void 0?void 0:$(o)})+`
122
+ `}i(Kd,"formatCliFailure");function Jd(n){jd(n).then(e=>{e!==null&&process.exit(e)}).catch(e=>{process.stderr.write(Kd(e,ci(n))),process.exit(1)})}i(Jd,"runAgentCliProcess");var di=process.argv[1];di!==void 0&&import.meta.url===Gd(Ld(di)).href&&Jd(process.argv.slice(2));export{Kd as formatCliFailure,ci as parseCliArgs,jd as runAgentCli,Jd as runAgentCliProcess};