progon-agent 1.5.1 → 1.5.3

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 (73) hide show
  1. package/README.md +288 -29
  2. package/dist/supervisor/cli.js +315 -50
  3. package/extension-bundle.json +3 -3
  4. package/extension-dist/background/background.js +151 -122
  5. package/extension-dist/card/card.css +1 -1
  6. package/extension-dist/card/card.html +12 -10
  7. package/extension-dist/card/card.js +3 -3
  8. package/extension-dist/chunks/shared-B3glEBMw.js +1 -0
  9. package/extension-dist/chunks/shared-B9oC2P3-.js +8 -0
  10. package/extension-dist/chunks/shared-BByPq6Kh.js +1 -0
  11. package/extension-dist/chunks/shared-BGvIl9us.js +1 -0
  12. package/extension-dist/chunks/shared-BMIAtDPv.js +45 -0
  13. package/extension-dist/chunks/shared-BTOXSk0k.js +118 -0
  14. package/extension-dist/chunks/shared-C-Q9DKcM.js +1 -0
  15. package/extension-dist/chunks/shared-C4rk8dhz.js +1 -0
  16. package/extension-dist/chunks/shared-CHDbyhV4.js +1 -0
  17. package/extension-dist/chunks/shared-CmGCWsjS.js +15 -0
  18. package/extension-dist/chunks/shared-D7P2v9Mb.js +372 -0
  19. package/extension-dist/chunks/shared-DKBOqKL2.css +1 -0
  20. package/extension-dist/chunks/shared-Dnq0mR_F.css +1 -0
  21. package/extension-dist/chunks/shared-Dor6Qf-t.js +1 -0
  22. package/extension-dist/chunks/shared-DwL_iWMx.js +1 -0
  23. package/extension-dist/chunks/shared-GBy7ssZb.js +1 -0
  24. package/extension-dist/chunks/shared-QityJbuK.css +1 -0
  25. package/extension-dist/chunks/shared-XKyaHtl9.js +1 -0
  26. package/extension-dist/chunks/shared-gmwevruS.js +159 -0
  27. package/extension-dist/chunks/shared-iMtAwxmT.js +351 -0
  28. package/extension-dist/chunks/shared-mCuRTIv8.js +129 -0
  29. package/extension-dist/chunks/shared-rQyAr3p-.js +1 -0
  30. package/extension-dist/chunks/shared-yvJVPBBs.css +1 -0
  31. package/extension-dist/content/canvas-interceptor.js +1 -1
  32. package/extension-dist/content/canvas-mapbox-bridge-main.js +1 -1
  33. package/extension-dist/content/content.css +1 -1
  34. package/extension-dist/content/content.js +289 -336
  35. package/extension-dist/content/early-nonce-inject.js +1 -1
  36. package/extension-dist/content/frame.js +160 -0
  37. package/extension-dist/content/main-world-nav.js +1 -1
  38. package/extension-dist/manifest.json +39 -45
  39. package/extension-dist/offscreen/offscreen.html +3 -2
  40. package/extension-dist/offscreen/offscreen.js +1 -1
  41. package/extension-dist/popup/popup.css +1 -1
  42. package/extension-dist/popup/popup.html +10 -9
  43. package/extension-dist/popup/popup.js +9 -3
  44. package/extension-dist/sidepanel/sidepanel.css +1 -1
  45. package/extension-dist/sidepanel/sidepanel.html +14 -13
  46. package/extension-dist/sidepanel/sidepanel.js +1 -1
  47. package/extension-dist/workspace/workspace.css +1 -1
  48. package/extension-dist/workspace/workspace.html +15 -13
  49. package/extension-dist/workspace/workspace.js +115 -53
  50. package/npm-shrinkwrap.json +469 -0
  51. package/package.json +17 -12
  52. package/extension-dist/chunks/shared-B5u-B6Qn.css +0 -1
  53. package/extension-dist/chunks/shared-BLDboBjL.js +0 -348
  54. package/extension-dist/chunks/shared-BdUzhaBn.js +0 -39
  55. package/extension-dist/chunks/shared-Bl2B_Px5.js +0 -1
  56. package/extension-dist/chunks/shared-CD1T06ac.js +0 -98
  57. package/extension-dist/chunks/shared-CDXdhl3P.js +0 -8
  58. package/extension-dist/chunks/shared-CVlB4Tu3.js +0 -15
  59. package/extension-dist/chunks/shared-Cz00vYCW.js +0 -1
  60. package/extension-dist/chunks/shared-D8QWnY4m.css +0 -1
  61. package/extension-dist/chunks/shared-DDffpwXS.js +0 -134
  62. package/extension-dist/chunks/shared-D_QceNk9.js +0 -254
  63. package/extension-dist/chunks/shared-Dp2jkJ8R.js +0 -1
  64. package/extension-dist/chunks/shared-Jcq39euZ.js +0 -199
  65. package/extension-dist/chunks/shared-R5ipc0Sn.js +0 -1
  66. package/extension-dist/chunks/shared-eZL18n5t.css +0 -1
  67. package/extension-dist/chunks/shared-gwUGKre-.js +0 -1
  68. package/extension-dist/chunks/shared-hePW80VL.js +0 -1
  69. package/extension-dist/chunks/shared-kKZVALIt.js +0 -1
  70. package/extension-dist/chunks/shared-nJgqlX01.js +0 -1
  71. package/extension-dist/chunks/shared-q9EK7cIP.js +0 -1
  72. package/extension-dist/chunks/shared-tcQ7xPb-.js +0 -1
  73. package/extension-dist/content/canvas-mapbox-fiber-discovery.js +0 -1
@@ -1,70 +1,325 @@
1
1
  #!/usr/bin/env node
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.
2
+ const __runnerRoot = new URL('../../', import.meta.url);
3
+ if ((await import('node:fs')).existsSync(new URL('src/supervisor/cli.ts', __runnerRoot))) {
4
+ const { fingerprint } = await import(new URL('scripts/build-provenance.mjs', __runnerRoot));
5
+ if (fingerprint((await import('node:url')).fileURLToPath(__runnerRoot)) !== "b0756d0b7f9c878dd443166f56c19accb413c2290000bfcbb2d1bcada428da92") {
6
+ throw new Error('Runner build is stale. Run npm run build:publish before starting.');
7
+ }
8
+ }
9
+ var iu=Object.defineProperty;var o=(t,e)=>iu(t,"name",{value:e,configurable:!0});import{realpathSync as GS}from"node:fs";import{pathToFileURL as FS}from"node:url";import{z as es}from"zod";var su=/^[a-z_]{1,32}@\d{1,3}$/,ts=es.array(es.string().regex(su)).min(1).max(32),ns=["playback@1"],rs="swarm@1",os="swarm@2",is="scenario_launch@1",ss="browser_channel@1",as="task_launch@1",ls="conversation@1";import{z as v}from"zod";var vt=/^pgat_[0-9A-Za-z]{43}$/;var Ze="agent:command",Vn="agent:command-ack",cs="agent:active-job";import{z as f}from"zod";import{z as k}from"zod";import{z as y}from"zod";var au=["running","pausing","paused","stopping","completed","cancelled","failed"],ds=y.enum(au),us=["completed","cancelled","failed"],nE=y.enum(us),lu=["running","pausing","paused","stopping"],rE=y.enum(lu),cu=["running","pausing","stopping"],oE=y.enum(cu),du=["paused",...us],iE=y.enum(du),uu=["user","credits","user_credit_limit","provider_unavailable"],sE=y.enum(uu),pu=["exploring","curation","done"],aE=y.enum(pu),mu=["queued","running","done","failed","cancelled"],lE=y.enum(mu),fu=["done","failed","cancelled"],cE=y.enum(fu),hu=["lead_finished","user_cancelled","lead_failed"],dE=y.enum(hu);var gu=["none","attached","lost"],uE=y.enum(gu),yu=["idle","active","awaiting_user"],pE=y.enum(yu),wu=["atlas","make_auto","preset"],mE=y.enum(wu),Su=["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"],fE=y.enum(Su),Eu=["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"],vu=y.enum(Eu),bu=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],hE=y.enum(bu),gE=y.union([vu,y.literal("chat")]),_u=["browser","agent","none"],ku=y.enum(_u),Ru=["browser","agent"],yE=y.enum(Ru),Tu=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],wE=y.enum(Tu),xu=["file_bugs","write_tests","edit_project"],SE=y.enum(xu),Iu=["text","auto"],EE=y.enum(Iu),Ou=["project","scenarios","test_run","test_plan"],vE=y.enum(Ou),Au=["host_lost","awaiting_browser","awaiting_user","paused"],bE=y.enum(Au),Cu=["window","mcp_agent","agent"],_E=y.enum(Cu),Pu=["opening","idle","busy","closing","closed"],kE=y.enum(Pu),Nu=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],RE=y.enum(Nu),Lu=["lead","user","workflow_ended","no_connection","left"],TE=y.enum(Lu),Du=["lead","user","workflow_ended","workflow_paused","unit_ended"],xE=y.enum(Du),$u=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],IE=y.enum($u),Uu=["make_auto","atlas","run","agent","mcp_task","check_launch"],OE=y.enum(Uu);var Mu=["starting","running","ended"],AE=y.enum(Mu),Gu=["completed","cancelled","failed","start_failed","lost"],CE=y.enum(Gu),Fu=["user","lead","left","no_connection","workflow_ended","not_taken"],Bu=y.enum(Fu);var ju=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],PE=y.enum(ju),Wu=["lead_choice","role_default"],NE=y.enum(Wu),Hu=["observe","main","dangerous"],LE=y.enum(Hu),Ju=["main","dangerous"],ps=y.enum(Ju);var Ku=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],DE=y.enum(Ku),Vu=["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.identity_delivering","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"],$E=y.enum(Vu),UE=y.object({status:ds}),qu=y.object({status:ds}),Yu=["conversation_deleted","text_not_stored"],Xu=y.enum(Yu),ME=qu.extend({reason:Xu.extract(["conversation_deleted"]).optional()}),GE=y.object({segment:y.number().int().min(1)}),FE=y.object({executorKind:ku}),BE=y.object({reason:y.enum(["ended","no_browser"])}),jE=y.object({reason:y.literal("task_paused")}),WE=y.discriminatedUnion("outcome",[y.object({outcome:y.enum(["finished","stopped"]),lostReason:y.null()}),y.object({outcome:y.literal("lost"),lostReason:Bu})]),HE=y.object({taskIds:y.array(y.uuid()).min(2)}),JE=y.object({stepNumber:y.number().int().min(1),currentStepNumber:y.number().int().min(1).nullable()}),KE=y.object({leaseExpiresAt:y.iso.datetime()}),VE=y.object({workflowId:y.uuid()}),qE=y.object({agentId:y.uuid()});var QE=k.object({queueId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),applicationId:k.uuid().nullable(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),ms=k.object({launchId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),fs=k.object({projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),standMode:ps,accountLabel:k.string().min(1),role:k.string().min(1),locale:k.string().min(1),viewportWidth:k.number().int().min(1),viewportHeight:k.number().int().min(1)}).strict(),zu=k.object({...fs.shape,environmentId:k.uuid().nullable()}).strict(),ZE=k.union([fs,zu]),ev=k.object({workflowId:k.uuid(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),tv=k.object({conversationId:k.uuid(),headful:k.boolean()}).strict();import{z as bt}from"zod";import{z as De}from"zod";var hs=["passed","failed","infra","cancelled","abandoned"];var Qu=["queued","launching","in_progress"];var gs=["passed","failed"],Zu=["before_hook_failed","no_start_page","no_path_for_page"],ep=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Po=[...Zu,...ep],av=De.enum(Po).exclude(["before_hook_failed"]),lv=De.object({executorFailureReason:De.literal("launch_error").optional()}).strict().default({});var cv=[...hs,...Qu];var dv=De.object({by:De.literal("human"),outcome:De.enum(gs)}).strict(),uv=De.object({outcome:De.enum(gs)}).strict();var tp=["queued","launching","in_progress","completed","failed","cancelled"],gv=bt.enum(tp);var np=["queued","launching","in_progress"],ys=bt.enum(np);var rp=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Po,"result_not_saved","mcp_agent_disconnected","agent_revoked"],yv=bt.enum(rp),op=["launch_error","browser_gone","max_duration"],No=bt.enum(op),ip=["name_not_resolved","unreachable","certificate","timeout","other"],ws=bt.enum(ip);var sp=["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","agent_revoked"],ap=bt.enum(sp),lp=["workflow_host_lost"],wv=ap.exclude(lp);var cp=f.enum(["darwin","linux","win32"]),dp=f.enum(["x64","arm64"]),Es=f.enum(["official","debug"]),Rv=f.object({enrollmentCode:f.string().min(32),hostname:f.string().min(1).max(255),platform:cp,arch:dp,agentVersion:f.string().min(1).max(30),protocolVersion:f.number().int().min(1)}).strict(),qn=f.object({agentId:f.uuid(),agentToken:f.string().regex(vt),pollWaitSec:f.number().int().min(1).max(25),protocolVersion:f.literal(1)}).strict(),Tv=f.object({waitSec:f.coerce.number().int().min(0).max(25).optional()}).strict(),vs=f.object({agent:f.object({revoked:f.boolean()}).strict(),run:f.union([f.null(),f.object({runId:f.uuid(),phase:ys,main:f.boolean().optional(),identities:f.array(f.object({identityId:f.uuid()}).strict()).optional(),launches:f.array(f.object({launchId:f.uuid()}).strict()).optional()}).strict()])}).strict(),Lo=f.object({v:f.literal(1),kind:f.literal("playback"),runId:f.uuid(),scenarioId:f.uuid(),projectId:f.uuid(),projectDomain:f.string().min(1),applicationId:f.uuid().nullable(),environmentId:f.uuid().nullable(),executionMode:f.literal("auto"),issuedAt:f.iso.datetime()}).strict(),Do=f.object({v:f.literal(1),kind:f.literal("scenario_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),...ms.shape}).strict(),$o=f.object({v:f.literal(1),kind:f.literal("swarm"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid()}).strict(),up=f.object({v:f.literal(1),kind:f.literal("task_identity"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),identityId:f.uuid()}).strict(),pp=f.object({v:f.literal(1),kind:f.literal("task_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),launchId:f.uuid()}).strict(),Uo=f.object({v:f.literal(1),kind:f.literal("conversation"),runId:f.uuid(),issuedAt:f.iso.datetime(),conversationId:f.uuid()}).strict(),xv=f.union([Lo,$o,Do,up,pp,Uo]),mp={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0,task_launch:!0,conversation:!0},Iv=Object.keys(mp),Ov=f.object({agentJobId:f.uuid(),updatedAt:f.iso.datetime()}).strict(),fp=f.enum(["invalid_envelope","dispatch_failed"]),bs=f.discriminatedUnion("outcome",[f.object({runId:f.uuid(),outcome:f.literal("dispatched")}).strict(),f.object({runId:f.uuid(),outcome:f.literal("rejected"),reason:fp}).strict()]),_s=f.object({cancelRequested:f.boolean(),killRequested:f.boolean()}).strict(),hp=2147483646,gp=f.object({stepId:f.uuid(),stepIndex:f.number().int().min(0).max(hp),status:f.enum(["passed","failed","skipped"]),failureCode:f.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:f.string().max(4e3).nullable(),startedAt:f.iso.datetime().nullable(),completedAt:f.iso.datetime().nullable()}).strict(),Av=f.object({events:f.array(gp).min(1).max(50)}).strict(),Cv=f.object({updated:f.number().int().min(0),control:_s}).strict(),Pv=f.object({phase:f.enum(["running","paused"])}).strict(),Nv=f.object({control:_s}).strict(),Ss=f.string().max(500).optional(),Lv=f.discriminatedUnion("reason",[f.object({reason:f.literal(No.enum.launch_error),message:Ss,entryFailure:ws.optional()}).strict(),f.object({reason:No.exclude(["launch_error"]),message:Ss}).strict()]),ks=f.object({status:f.enum(["failed","already_terminal"])}).strict();var Fv=v.union([v.object({}).strict(),v.object({capabilities:ts}).strict()]);function Yn(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"})}o(Yn,"checkClaimRunIdAgreement");function yp(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"})}o(yp,"checkPlaybackClaimProjectAgreement");var wp=v.object({runId:v.uuid(),scenarioId:v.uuid(),projectId:v.uuid(),applicationId:v.uuid().nullable(),projectDomain:v.string().min(1),entryUrl:v.url({protocol:/^https?$/}),environmentId:v.uuid().nullable(),runPurpose:Es,headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(3600),extensionSession:v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),command:Lo}).strict().check(Yn).check(yp),Xn=v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),Go=v.object({extensionSession:Xn}).strict(),Sp=v.object({kind:v.literal("swarm"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:$o}).strict().check(Yn),Ep=v.object({kind:v.literal("scenario_launch"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:Do}).strict().check(Yn),vp=v.object({kind:v.literal("conversation"),runId:v.uuid(),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:Uo}).strict().check(Yn),Rs=v.union([wp,Sp,Ep,vp]);import{z as Ts}from"zod";var bp=["finished","cancelled","ai_disabled"],_p=Ts.enum(bp),Hv=Ts.object({outcome:_p}).strict();import{spawn as Pp}from"node:child_process";import{existsSync as Np}from"node:fs";import{createRequire as Lp}from"node:module";import{dirname as Ls,join as Dp}from"node:path";var kp=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Rp=/\b(?:pgat_|rr_|pgrt_|pgci_|pat_|mcp_at_)[A-Za-z0-9_-]+/g,ln="eyJ";function Is(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95}o(Is,"isWordChar");function Os(t,e){let n=e;for(;n<t.length;){let r=t.charCodeAt(n);if(!Is(r)&&r!==45)break;n++}return n}o(Os,"base64UrlRunEnd");function xs(t,e){if(t[e]!==".")return-1;let n=Os(t,e+1);return n===e+1?-1:n}o(xs,"segmentEndAfterDot");function Tp(t){let e=[],n=0,r=-1,i=t.indexOf(ln);for(;i!==-1;){let s=i+ln.length;if(i>0&&Is(t.charCodeAt(i-1))){i=t.indexOf(ln,s);continue}r<s&&(r=Os(t,s));let l=r>s?xs(t,r):-1,c=l===-1?-1:xs(t,l);if(c===-1){i=t.indexOf(ln,r);continue}e.push(t.slice(n,i),cn),n=c,i=t.indexOf(ln,n)}return e.length===0?t:(e.push(t.slice(n)),e.join(""))}o(Tp,"redactJwsSpans");var xp=["token","secret","password","authorization","api_key","api-key","apikey"],Ip=new RegExp(`([?&](?:${xp.join("|")})=)([^&\\s]+)`,"gi"),Op=/(\bhttps?:\/\/)[^\s/?#]*@/gi,cn="[REDACTED]";function As(t){let e=Tp(t);return e=e.replace(Rp,cn),e=e.replace(Ip,`$1${cn}`),e=e.replace(Op,`$1${cn}@`),e}o(As,"redactValueString");function et(t){if(Array.isArray(t))return t.map(et);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))kp.has(r.toLowerCase())?n[r]=cn:n[r]=et(e[r]);return n}return typeof t=="string"?As(t):t}o(et,"redactSecrets");function C(t){return As(t)}o(C,"redactSensitiveText");import Fo from"pino";var Cs=new Set(["trace","debug","info","warn","error","fatal","silent"]);function Ap(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&Cs.has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}o(Ap,"resolveLogLevel");function Cp(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Cp,"buildTransport");var Ps={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]"},Ns=Fo({name:"qa-runner",level:Ap(),transport:Cp(),base:{pid:process.pid},redact:Ps}),Bo=null;function jo(t,e){let n=null,r=o(()=>Bo===null?t:(n??=Bo.child(e),n),"sink");return{debug(i,s){s!==void 0?r().debug(et(s),i):r().debug(i)},info(i,s){s!==void 0?r().info(et(s),i):r().info(i)},warn(i,s){s!==void 0?r().warn(et(s),i):r().warn(i)},error(i,s){s!==void 0?r().error(et(s),i):r().error(i)},child(i){return jo(t.child(i),{...e,...i})}}}o(jo,"adaptPino");function w(t){let e={module:t};return jo(Ns.child(e),e)}o(w,"createLogger");var ob=jo(Ns,{});function zn(){let t=process.env.PROGON_LOG_LEVEL;Bo=Fo({name:"qa-runner",level:t!==void 0&&Cs.has(t)?t:"silent",base:{pid:process.pid},redact:Ps},Fo.destination({dest:2,sync:!0}))}o(zn,"routeLogsAwayFromStdout");var Wo=w("browser-provision"),$p=60*6e4,Q=class extends Error{static{o(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}},Ds=[" - 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(`
10
+ `);function Ho(){let t=Lp(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new Q(`[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=Dp(Ls(e),"cli.js");if(!Np(n))throw new Q(`[browser-provision] 'playwright-core' resolved to ${Ls(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"]}}o(Ho,"resolveInstallCommand");async function kt(t){let e=t.commandOverride===void 0?Ho():t.commandOverride,n=t.deadlineMs===void 0?$p:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],i=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,s=Date.now();Wo.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let l=Pp(e.execPath,[e.cliPath,...r],{env:process.env,stdio:["ignore","pipe","pipe"]}),{stdout:c,stderr:a}=l,d=t.stdio==="pipe"?Mp:Up;$s(c,"stdout",d),$s(a,"stderr",d);let u=!1,m=o(()=>{u=l.kill("SIGKILL")},"onAbort");t.signal?.aborted===!0?m():t.signal?.addEventListener("abort",m,{once:!0});let g=!1,E=setTimeout(()=>{g=!0,l.kill("SIGKILL")},n),S=new Map,b=o(()=>{for(let[N,z]of S)process.off(N,z);S.clear()},"removeSignalHandlers"),I=t.signal===void 0?["SIGTERM","SIGINT"]:[];for(let N of I){let z=o(()=>{l.kill("SIGKILL"),b(),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:N,installerPid:l.pid})+`
11
+ `),process.kill(process.pid,N)},"handler");S.set(N,z),process.on(N,z)}try{await new Promise((N,z)=>{l.once("error",ue=>{z(new Q(`[browser-provision] Could not start the Playwright installer (${i}): ${ue.message}`,{cause:ue}))}),l.once("close",(ue,Et)=>{if(g){z(new Q(`[browser-provision] Chromium installation did not finish within ${n}ms and was killed (${i}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
12
+ ${Ds}`,{exitCode:ue,timedOut:!0}));return}if(ue===0){N();return}if(u&&t.signal!==void 0&&ue===null&&Et==="SIGKILL"){z(t.signal.reason);return}let ou=ue===null?`was terminated by signal ${String(Et)}`:`exited with code ${ue}`;z(new Q(`[browser-provision] Chromium could not be installed: the Playwright installer ${ou} (${i}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
13
+ ${Ds}`,{exitCode:ue}))})})}finally{clearTimeout(E),t.signal?.removeEventListener("abort",m),b()}Wo.info("Chromium is provisioned",{durationMs:Date.now()-s})}o(kt,"provisionBrowser");function $s(t,e,n){let r="";t.setEncoding("utf8"),t.on("data",i=>{r+=i;let s=r.lastIndexOf(`
14
+ `);if(s===-1)return;let l=r.slice(0,s);r=r.slice(s+1);for(let c of l.split(`
15
+ `))n(c,e)}),t.on("end",()=>{let i=r;r="",n(i,e)})}o($s,"forwardLines");function Up(t,e){t!==""&&process[e].write(`${C(t)}
16
+ `)}o(Up,"printLine");function Mp(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Wo.info("Chromium provisioning output",{stream:e,line:n})}o(Mp,"logLine");import{homedir as Lm}from"node:os";import{isAbsolute as ia,join as or,resolve as Dm}from"node:path";var p=class extends Error{static{o(this,"OperatorRefusalError")}};var Gp=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Fp(t){return t.protocol==="https:"||t.protocol==="http:"&&Gp.has(t.hostname)}o(Fp,"usesTrustedHttpScheme");function Re(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL.")}if(!Fp(e))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)}.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}.`);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.");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).`)}o(Re,"validateServerUrl");function dn(t){if(!vt.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.")}o(dn,"validateRunnerToken");function Jo(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.`)}o(Jo,"validateRunnerMachineId");function Ko(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.`)}o(Ko,"validateProtocolVersion");import{Agent as Bp,EnvHttpProxyAgent as jp}from"undici";var Us=w("gateway-proxy"),Wp=["http_proxy","HTTP_PROXY"],Hp=["https_proxy","HTTPS_PROXY"],Jp=["no_proxy","NO_PROXY"];function Kp(t){return t.http!==void 0||t.https!==void 0}o(Kp,"gatewayIsProxied");var Vp=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,qp=/:\d+$/,Yp=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function Xp(t){let e=Yp.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(Xp,"withoutProxyCredentials");function Rt(t,e,n){return new p(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(Xp(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.`)}o(Rt,"refuseProxyValue");function Ms(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}o(Ms,"readProxyVariable");function zp(t){for(let e of Jp){let n=t[e];if(n!==void 0)return n}}o(zp,"readNoProxy");function Gs(t,e){if(Vp.test(e)){let l;try{l=new URL(e)}catch{throw Rt(t,e,"it carries a scheme but is not a URL that parses")}if(l.protocol!=="http:"&&l.protocol!=="https:")throw Rt(t,e,`its scheme is ${JSON.stringify(l.protocol)}, not http: or https:`);if(l.hostname==="")throw Rt(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(!qp.test(r))throw Rt(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let i=`http://${e}`,s;try{s=new URL(i)}catch{throw Rt(t,e,'it is neither a URL nor a "host:port" pair')}if(s.hostname==="")throw Rt(t,e,"it names no host");return{variable:t,url:i,schemeCompleted:!0}}o(Gs,"parseProxyValue");function un(t){let e=Ms(t,Wp),n=Ms(t,Hp);return{http:e===void 0?void 0:Gs(e.variable,e.raw),https:n===void 0?void 0:Gs(n.variable,n.raw),noProxy:zp(t)}}o(un,"resolveGatewayProxyConfig");function Fs(t,e,n){if(!Kp(t))return new Bp(e);Us.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 s of[t.http,t.https])s!==void 0&&s.schemeCompleted&&r.push(s.variable);r.length>0&&Us.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 i={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new jp(i)}o(Fs,"createProxyAwareDispatcher");function Qn(t){un(t)}o(Qn,"validateGatewayProxyEnv");import{X509Certificate as Qp}from"node:crypto";import{readFileSync as Zp,statSync as em}from"node:fs";import{isAbsolute as tm}from"node:path";import{rootCertificates as Bs}from"node:tls";var nm=w("gateway-tls-trust"),Zn="PROGON_AGENT_EXTRA_CA_CERTS",js="NODE_EXTRA_CA_CERTS";function rm(t,e,n){let r=`[config] ${Zn} 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 ${Zn} to trust only the public roots.`;return n===void 0?new p(r):new p(r,{cause:n})}o(rm,"refuseExtraCaValue");function er(t){let e=t[Zn];if(e===void 0||e==="")return;let n=Ws(e);if("because"in n)throw rm(e,n.because,n.cause);return{variable:Zn,path:e,pem:n.pem}}o(er,"resolveExtraCaTrust");function Ws(t){if(!tm(t))return{because:"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",cause:void 0};let e;try{e=em(t)}catch(r){return{because:"it cannot be read",cause:r}}if(!e.isFile())return{because:"it is not a file",cause:void 0};let n;try{n=Zp(t,"utf8")}catch(r){return{because:"its contents could not be read",cause:r}}try{new Qp(n)}catch(r){return{because:"it does not hold a PEM certificate",cause:r}}return{pem:n}}o(Ws,"readCaBundle");function Hs(t){let e=t[js];if(e===void 0||e==="")return;let n=Ws(e);if(!("because"in n))return e;let r=n.cause instanceof Error?` (${n.cause.message})`:"";throw new p(`${js} does not name a certificate bundle every start of the agent can use: ${n.because}${r}. Got: ${JSON.stringify(e)}. Where Node cannot use the file it ignores it and trusts only the public roots, so behind a TLS-intercepting gateway the Chromium download and the agent's connections fail. Point it at an ABSOLUTE path to a readable PEM file with the corporate root certificate, or unset it.`,n.cause===void 0?void 0:{cause:n.cause})}o(Hs,"inspectNodeExtraCaCerts");function Js(t){let e=er(t);if(e!==void 0)return nm.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:Bs.length}),[...Bs,e.pem]}o(Js,"readTrustedCaBundle");function tr(t){er(t)}o(tr,"validateExtraCaTrustEnv");import{readFileSync as lm}from"node:fs";import{dirname as cm,join as dm}from"node:path";import{fileURLToPath as um}from"node:url";function P(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}o(P,"isAbsentPathError");import{statSync as om}from"node:fs";import{dirname as im,join as sm}from"node:path";var Ks="package.json";function Se(t){let e=t;for(;;){if(am(e))return e;let n=im(e);if(n===e)throw new Error(`[package-root] No ${Ks} 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}}o(Se,"findPackageRoot");function am(t){try{return om(sm(t,Ks)),!0}catch(e){if(P(e))return!1;throw e}}o(am,"holdsPackageManifest");var pm="extension-bundle.json";function Tt(){return mm(dm(Se(cm(um(import.meta.url))),pm))}o(Tt,"readBundledAppUrl");function mm(t){let e;try{e=lm(t,"utf-8")}catch(i){if(P(i))return null;throw new p(`[extension-bundle] ${t} exists but could not be read: ${String(i)}. 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:i})}let n;try{n=JSON.parse(e)}catch(i){throw new p(`[extension-bundle] ${t} contains invalid JSON: ${String(i)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:i})}if(typeof n!="object"||n===null||Array.isArray(n)){let i=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[extension-bundle] ${t} must contain a JSON object, got: ${i}. 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{Re(r)}catch(i){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(i)}`,{cause:i})}return r}o(mm,"readBundledAppUrlFrom");import{unlinkSync as Pm}from"node:fs";import{readFileSync as bm,writeFileSync as _m,renameSync as km,existsSync as Rm,fchmodSync as Tm,openSync as qs,fsyncSync as Ys,closeSync as Xs,unlinkSync as xm}from"node:fs";import{join as zs}from"node:path";import{spawnSync as fm}from"node:child_process";import{chmodSync as hm,mkdirSync as gm}from"node:fs";import{resolve as ym}from"node:path";import{z as $e}from"zod";var tt="powershell.exe";function me(t){return`'${t.replace(/['‘’‚‛]/g,e=>e+e)}'`}o(me,"psQuote");function pn(t){return Buffer.from(t,"utf16le").toString("base64")}o(pn,"encodePowerShellCommand");var wm=3e4,Vs=new Set;function xt(t){let e=ym(t);if(gm(e,{recursive:!0,mode:448}),process.platform!=="win32"){hm(e,448);return}Vs.has(e)||(vm(e),Vs.add(e))}o(xt,"makeStateDirPrivate");function Sm(t){return`$ErrorActionPreference = 'Stop'
17
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
18
+ $path = ${me(t)}
19
+ $sidType = [System.Security.Principal.SecurityIdentifier]
20
+ $trusted = @([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value, 'S-1-5-18', 'S-1-5-32-544')
21
+ function NameOf($sid) { try { $sid.Translate([System.Security.Principal.NTAccount]).Value } catch { $sid.Value } }
22
+ function ForeignOwner($item) {
23
+ try { $owner = $item.GetAccessControl('Owner').GetOwner($sidType) } catch { return 'an owner this user cannot read' }
24
+ if ($trusted -contains $owner.Value) { return $null }
25
+ return NameOf $owner
26
+ }
27
+ $dir = Get-Item -LiteralPath $path -Force
28
+ $dirOwner = ForeignOwner $dir
29
+ if ($null -ne $dirOwner) { [pscustomobject]@{ kind = 'foreign-owner'; owner = $dirOwner } | ConvertTo-Json -Compress; exit 0 }
30
+ $acl = New-Object System.Security.AccessControl.DirectorySecurity
31
+ $acl.SetAccessRuleProtection($true, $false)
32
+ foreach ($sid in $trusted) {
33
+ $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier($sid)), 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow')))
34
+ }
35
+ $dir.SetAccessControl($acl)
36
+ $foreign = @(Get-ChildItem -LiteralPath $path -Force | ForEach-Object { $o = ForeignOwner $_; if ($null -ne $o) { $_.Name + ' (' + $o + ')' } })
37
+ [pscustomobject]@{ kind = 'private'; foreign = $foreign } | ConvertTo-Json -Compress`}o(Sm,"renderAccessListScript");var Em=$e.discriminatedUnion("kind",[$e.object({kind:$e.literal("foreign-owner"),owner:$e.string()}),$e.object({kind:$e.literal("private"),foreign:$e.array($e.string())})]);function vm(t){let e=fm(tt,["-NoProfile","-NonInteractive","-EncodedCommand",pn(Sm(t))],{encoding:"utf8",timeout:wm,windowsHide:!0});if(e.error!==void 0||e.status!==0){let i=e.error?.message??(e.stderr.trim()||e.stdout.trim()||`exit ${e.status}`);throw new p(`Could not make the state directory ${t} private to this user (${tt}: ${i.split(`
38
+ `).slice(0,3).join(" / ")}). The agent does not write its token into a directory other users may read. Fix the cause above, or pick another --state-dir.`)}let n=Em.safeParse(JSON.parse(e.stdout.replace(/^\uFEFF/,"")));if(!n.success)throw new Error(`[private-state-dir] PowerShell answered in a form this version does not read: ${n.error.message}`);let r=n.data;if(r.kind==="foreign-owner")throw new p(`The state directory ${t} belongs to ${r.owner}, who can give themselves access to its token at any time. Use a directory of your own: pick another --state-dir.`);if(r.foreign.length>0)throw new p(`The state directory ${t} is now private to this user, but these entries in it belong to another user, who can still read or change them: ${r.foreign.join(", ")}. Delete them (or the whole directory) and start again.`)}o(vm,"setOwnerOnlyAccessList");var nr=w("state-file");function nt(t){return zs(t,"runner-state.json")}o(nt,"stateFilePath");function mn(t){return zs(t,"runner-state.json.tmp")}o(mn,"stateTmpPath");function Qs(t){let e=nt(t);if(!Rm(e))return nr.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=bm(e,"utf-8")}catch(s){throw new p(`[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(n)}catch(s){throw new p(`[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 i=Am(r,e);return nr.info("State file loaded",{agentId:i.agentId,protocolVersion:i.protocolVersion}),i}o(Qs,"readState");function Zs(t,e){xt(t);let n=nt(t),r=mn(t),i=JSON.stringify(e,null,2);try{let s=qs(r,"w",384);try{Tm(s,384),_m(s,i,{encoding:"utf-8"}),Ys(s)}finally{Xs(s)}km(r,n),Om(t)}catch(s){throw Im(r),new p(`[state-file] Failed to write state file at ${n}: ${String(s)}. Check permissions on stateDir ${t}.`)}nr.info("State file written",{agentId:e.agentId,filePath:n})}o(Zs,"writeState");function Im(t){try{xm(t)}catch(e){if(e.code==="ENOENT")return;nr.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)})}}o(Im,"removeStateTmp");function Om(t){let e=qs(t,"r");try{Ys(e)}finally{Xs(e)}}o(Om,"fsyncDirectory");function Am(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let c=t===null?"null":Array.isArray(t)?"array":typeof t;throw new p(`[state-file] State file ${e} must contain a JSON object, got: ${c}`)}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).`);Jo(r);let i=n.agentToken;if(typeof i!="string"||i==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);dn(i);let s=n.protocolVersion;if(typeof s!="number"||!Number.isInteger(s))throw new p(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);Ko(s);let l=n.serverUrl;if(typeof l!="string"||l==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{Re(l)}catch(c){throw new p(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(c)}`)}return{agentId:r,agentToken:i,protocolVersion:s,serverUrl:l,tokenRotatedAt:Cm(n,e)}}o(Am,"validateState");function Cm(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}o(Cm,"readTokenRotatedAt");var ea=w("token-store");function L(t){return Qs(t)}o(L,"loadAgentIdentity");function It(t,e){Zs(t,e)}o(It,"saveAgentIdentity");function rr(t){let e=nt(t),n=mn(t),r=ta(n,"temporary state file"),i=ta(e,"identity");if(!i&&!r){ea.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}ea.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:i,removedTmp:r})}o(rr,"wipeAgentIdentity");function ta(t,e){try{return Pm(t),!0}catch(n){if(Nm(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.`)}}o(ta,"removeCredentialFile");function Nm(t){return t.code==="ENOENT"}o(Nm,"isFileNotFound");var na="extension-bundle.json";function Ue(t,e){return ra(t)===ra(e)}o(Ue,"isSameDeployment");function ra(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}o(ra,"normalizeDeployment");function oa(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return Re(e),{url:e,source:"env"};if(n){let l=Tt();if(l!==null)return{url:l,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.
39
+ This build carries no ${na} 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
40
  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
41
  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=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.
42
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let i=L(r);if(i!==null)return{url:i.serverUrl,source:"state_file"};let s=Tt();if(s!==null)return{url:s,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.
43
+ PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${na}, 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
44
  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
45
  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
46
  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(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}.
47
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}o(oa,"resolveServerUrl");function fn(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}o(fn,"getOptional");function Vo(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)}.`)}o(Vo,"getOptionalBool");var ir="progon-agent";function hn(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 or(n,"Library","Application Support",ir);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return or(n,".local","state",ir);if(!ia(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 or(r,ir)}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 or(r,ir)}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.`)}}o(hn,"resolveDefaultStateDir");function G(){let t=fn("PROGON_RUNNER_STATE_DIR");return t!==void 0?{path:Dm(t),source:"env"}:{path:hn(process.platform,process.env,Lm()),source:"default"}}o(G,"resolveStateDir");var sa=["PROGON_SERVER_URL","PROGON_LOG_LEVEL","PROGON_AGENT_EXTENSION_DIST","PROGON_AGENT_HEADFUL","PROGON_AGENT_ALLOW_INSECURE_HTTPS","PROGON_AGENT_DISABLE_BROWSER_SANDBOX","PROGON_AGENT_EXTRA_CA_CERTS","NODE_EXTRA_CA_CERTS","PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function gn(){let t=fn("PROGON_AGENT_EXTENSION_DIST");if(t!==void 0&&!ia(t))throw new p(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(t)}.`);return{extensionDistOverride:t,headfulOverride:Vo("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Vo("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),disableBrowserSandbox:Vo("PROGON_AGENT_DISABLE_BROWSER_SANDBOX",!1)}}o(gn,"loadBrowserRuntimeEnv");function Me(){Qn(process.env),tr(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&&dn(e);let n=G().path,r=oa({envUrl:fn("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),i=fn("PROGON_AGENT_ENROLL_CODE");if(i!==void 0&&i.length<32)throw new p(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${i.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,...gn(),enrollmentCode:i,nodeEnv:fn("NODE_ENV")??"production"}}o(Me,"loadConfig");import{randomUUID as Ug}from"node:crypto";function yn(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
48
+ `)}o(yn,"writeLine");function la(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:C(e),stack:n!==void 0?C(n):void 0}}o(la,"describeError");function aa(t,e,n){yn("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...la(e),...n})}o(aa,"writeFatalLine");function ca(){process.on("uncaughtException",(t,e)=>{aa("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{aa("unhandledRejection",t,{}),process.exit(1)})}o(ca,"installProcessGuards");var sr=["SIGTERM","SIGINT","SIGHUP"];function da(t){let e=!1,n=o(r=>{if(e){yn("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,yn("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(i){yn("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...la(i)}),process.exit(1)}yn("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");for(let r of sr)process.on(r,n);return n}o(da,"installShutdownHandlers");var $m=w("debug-env-guard"),Um=["pw:protocol","pw:api"];function Mm(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(Mm,"escapeRegExp");function ua(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Mm).join(".*?")}$`,n=new RegExp(e);return Um.some(r=>n.test(r))}o(ua,"enablesPlaywright");function Gm(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(i=>i.trim()).filter(i=>i!==""),n=e.filter(i=>ua(i));if(n.length===0)return[];let r=e.filter(i=>!ua(i));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),$m.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 written into the token database \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),n}o(Gm,"sanitizePlaywrightDebugEnv");Gm();import{statSync as fa}from"node:fs";import{isAbsolute as Jm,join as Km}from"node:path";import{createRequire as Fm}from"node:module";var Te=Fm(import.meta.url)("playwright-core"),rt=Te.chromium,W_=Te.firefox,H_=Te.webkit,J_=Te.selectors,K_=Te.devices,pa=Te.errors,V_=Te.request,q_=Te._electron,Y_=Te._android;import{writeFileSync as Bm}from"node:fs";import{join as jm}from"node:path";var Wm="Local State",Hm={async_dns:{enabled:!1},dns_over_https:{mode:"off"}};function ma(t){Bm(jm(t,Wm),JSON.stringify(Hm),{flag:"wx"})}o(ma,"writeOsResolverLocalState");var wn="chromium";var ar="instances",lr="instance.json";var Vm=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"],ha={handleSIGINT:!1,handleSIGTERM:!1,handleSIGHUP:!1};async function ga(t){return ma(t.userDataDir),rt.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:wn,...ha,viewport:null,ignoreHTTPSErrors:t.allowInsecureHttps,chromiumSandbox:!t.disableBrowserSandbox,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check","--silent-debugger-extension-api",...t.headful?[]:["--screen-info={1280x1024}"],...t.keepBackgroundWindowsRendering?Vm:[]]})}o(ga,"launchExtensionContext");async function ya(t){return rt.launchPersistentContext(t,{headless:!0,channel:wn,...ha,chromiumSandbox:!0})}o(ya,"launchSandboxedProbeContext");async function wa(t,e){let n=await t.newCDPSession(e);try{let{windowId:r}=await n.send("Browser.getWindowForTarget");await n.send("Browser.setContentsSize",{windowId:r,width:1280,height:720})}finally{await n.detach()}}o(wa,"setRunnerContentViewport");function qm(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}o(qm,"requireBrowser");function Sa(t){return qm(t).version()}o(Sa,"readChromeVersion");async function cr(t,e){let n,r=new Promise(i=>{n=setTimeout(()=>i({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),i=>({settled:"rejected",error:i})),r])}finally{n!==void 0&&clearTimeout(n)}}o(cr,"raceClose");function dr(t){if(!Jm(t))throw new p(`[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=fa(t)}catch(r){throw new p(`[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.`,{cause:r})}if(!e.isDirectory())throw new p(`[runtime] The extension dist path ${t} is not a directory.`);let n=Km(t,"manifest.json");try{fa(n)}catch(r){throw new p(`[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})}}o(dr,"assertUsableExtensionDist");import{fetch as nf}from"undici";import{z as Ga}from"zod";var A=class extends Error{static{o(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},Z=class extends A{static{o(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},x=class extends A{static{o(this,"GatewayHttpError")}status;errorCode;params;retryAfterMs;constructor(e,n,r,i,s,l=null){super(e,`[gateway] ${e} refused with HTTP ${n}: ${s}`),this.status=n,this.errorCode=r,this.params=i,this.retryAfterMs=l}},Ot=class extends x{static{o(this,"GatewayUnauthorizedError")}},O=class extends x{static{o(this,"TokenSupersededError")}},T=class extends A{static{o(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},At=class extends x{static{o(this,"EnrollmentCodeRejectedError")}},ot=class extends x{static{o(this,"ProtocolVersionMismatchError")}},ee=class extends x{static{o(this,"AgentUpgradeRequiredError")}constructor(e,n,r,i,s){super(e,n,r,i,`${s}. Update the agent with 'progon-agent update' and start it again.`)}},Ct=class extends x{static{o(this,"RunNotClaimableError")}},it=class extends x{static{o(this,"RunNotFoundError")}},fe=class extends A{static{o(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};import{readFileSync as Ym}from"node:fs";import{dirname as Xm,join as zm}from"node:path";import{fileURLToPath as Qm}from"node:url";var Zm=/^\d+\.\d+\.\d+$/,Ea=30,qo=null;function te(){if(qo!==null)return qo;let t=Se(Xm(Qm(import.meta.url))),e=JSON.parse(Ym(zm(t,"package.json"),"utf8")),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||!Zm.test(n))throw new Error(`[agent-version] The agent package.json in ${t} has no usable "version" field (got ${JSON.stringify(n)}, expected x.y.z), so the agent cannot state its version to the server. This is a packaging defect: the daemon must not run under an invented version.`);if(n.length>Ea)throw new Error(`[agent-version] The agent package version ${JSON.stringify(n)} is longer than the ${Ea} characters CONTRACT-la \xA75.1 allows for agentVersion.`);return qo=n,n}o(te,"readAgentVersion");function va(){return`agent/${te()}`}o(va,"agentClientHeaderValue");var Pt=class extends x{static{o(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,i,s,l){super(e,n,r,i,s),this.retryAfterSec=l}},Nt=class extends x{static{o(this,"EnrollmentAccessDeniedError")}},Lt=class extends x{static{o(this,"EnrollmentRequestExpiredError")}},Dt=class extends x{static{o(this,"EnrollmentAlreadyCompletedError")}},$t=class extends x{static{o(this,"EnrollmentRequestInvalidError")}};function ba(t,e){return e.status===426&&e.errorCode==="client.upgrade_required"?K(ee,t,e):null}o(ba,"mapClientVersionRefusal");function _a(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?K(At,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?K(ot,"enroll",t):ne("enroll",t)}o(_a,"mapEnrollError");function ka(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?K(ot,"enrollment_request_create",t):ne("enrollment_request_create",t)}o(ka,"mapEnrollmentRequestCreateError");function Ra(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 Pt("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?K(Nt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?K(Lt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?K(Dt,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?K($t,"enrollment_request_poll",t):ne("enrollment_request_poll",t)}o(Ra,"mapEnrollmentRequestPollError");function Ta(t){return ne("enrollment_request_cancel",t)}o(Ta,"mapEnrollmentRequestCancelError");function xa(t){return xe("poll_desired_state",t,()=>ne("poll_desired_state",t))}o(xa,"mapPollDesiredStateError");function Ia(t){return xe("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?K(Ct,"claim",t):t.status===404?K(it,"claim",t):ne("claim",t))}o(Ia,"mapClaimError");function Oa(t){return xe("fail",t,()=>t.status===404?K(it,"fail",t):ne("fail",t))}o(Oa,"mapFailError");function Aa(t){return xe("token_status",t,()=>ne("token_status",t))}o(Aa,"mapTokenStatusError");function Ca(t){return xe("token_rotate",t,()=>ne("token_rotate",t))}o(Ca,"mapTokenRotateError");function Pa(t){return xe("declare_capabilities",t,()=>ne("declare_capabilities",t))}o(Pa,"mapDeclareCapabilitiesError");function Na(t){return xe("identity_session",t,()=>ne("identity_session",t))}o(Na,"mapIdentitySessionError");function La(t){return xe("revoke",t,()=>ne("revoke",t))}o(La,"mapRevokeError");function Da(t){return xe("launch_session",t,()=>ne("launch_session",t))}o(Da,"mapLaunchSessionError");function xe(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new T(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?K(O,t,e):e.status===401?K(Ot,t,e):n()}o(xe,"bearerRoute");function K(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message,n.retryAfterMs)}o(K,"named");function ne(t,e){return K(x,t,e)}o(ne,"generic");var $a=w("gateway-http");async function st(t){let e={accept:"application/json","x-progon-client":va()};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),$a.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(i){throw new Z(t.operation,ur(i),i)}let r;try{r=await n.text()}catch(i){throw new Z(t.operation,ur(i),i)}if(!n.ok){let i=Xo(n,r);throw $a.debug("Gateway request refused",{operation:t.operation,status:i.status,errorCode:i.errorCode}),ba(t.operation,i)??t.mapHttpError(i)}try{return JSON.parse(r)}catch(i){throw new fe(t.operation,`the ${n.status} response body is not valid JSON`,i)}}o(st,"executeGatewayRequest");function V(t,e){if(e.success)return e.data;throw new fe(t,zo(e.error),e.error)}o(V,"parseGatewayBody");function pr(t,e){return new URL(`${t.replace(/\/+$/,"")}${e}`)}o(pr,"buildServerRouteUrl");function Xo(t,e){let{status:n}=t,r=ef(t.headers.get("retry-after")),i;try{i=JSON.parse(e)}catch{return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r}}if(typeof i!="object"||i===null||Array.isArray(i))return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r};let s=i,l=s.error_code,c=s.params,a=s.message;return{status:n,errorCode:typeof l=="string"?l:null,params:typeof c=="object"&&c!==null&&!Array.isArray(c)?c:null,message:typeof a=="string"?C(a):Yo,retryAfterMs:r}}o(Xo,"readErrorEnvelope");function ef(t){return t===null||!/^\d+$/.test(t)?null:Number(t)*1e3}o(ef,"parseRetryAfterMs");var Yo="the response body carried no Progon error envelope";function ur(t){if(!(t instanceof Error))return C(String(t));let e=tf(t.cause);return C(e===""?t.message:`${t.message}: ${e}`)}o(ur,"describeTransportCause");function tf(t){return t instanceof Error?t.message!==""||!(t instanceof AggregateError)?t.message:t.errors.map(e=>e instanceof Error?e.message:"").filter(e=>e!=="").join("; "):""}o(tf,"causeText");function zo(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 i=r.path;return!Array.isArray(i)||i.length===0?"<root>":i.map(s=>String(s)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}o(zo,"summarizeSchemaViolation");var mr=[...ns,rs,os,ss,is,as,ls];import{z as at}from"zod";var Ua=at.object({rotationDue:at.boolean(),tokenRotatedAt:at.string().nullable(),anchorAt:at.string(),intervalDays:at.number().int()}),Ma=at.object({agentToken:at.string().regex(vt)});var Sn=w("gateway-client"),rf=Ga.object({success:Ga.literal(!0)}),of="/api/agent-gateway";function q(t,e){return pr(t,`${of}${e}`)}o(q,"buildGatewayUrl");var Fa=3e5,ja=1e4,Ba={headersTimeout:Fa,bodyTimeout:Fa,connect:{timeout:ja}};function sf(){let t=Js(process.env);return Fs(un(process.env),t===void 0?Ba:{...Ba,connect:{timeout:ja,ca:t}},t)}o(sf,"buildGatewayDispatcher");var Qo,Mt=o((t,e)=>{if(Qo===void 0){let n=sf();Qo=o((r,i)=>nf(r,{...i,dispatcher:n}),"defaultGatewayFetch")}return Qo(t,e)},"pinnedGatewayFetch"),Ut=class{static{o(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Mt}async enroll(e,n){let r={...this.machine,enrollmentCode:e,protocolVersion:1},i=await st({operation:"enroll",method:"POST",url:q(this.serverUrl,"/enroll"),agentToken:null,body:r,signal:n?.signal,fetchImpl:this.fetchImpl,mapHttpError:_a}),s=V("enroll",qn.safeParse(i));return Sn.info("Agent enrolled",{agentId:s.agentId,pollWaitSec:s.pollWaitSec,protocolVersion:s.protocolVersion}),s}},Ge=class{static{o(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Mt}async authenticatedRequest(e){return st({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=q(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:xa}),i=V("poll_desired_state",vs.safeParse(r));if(i.agent.revoked)throw new T("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return i}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:mr},signal:void 0,mapHttpError:Ia});return V("claim",Rs.safeParse(n))}async issueIdentitySession(e,n){let r=await this.authenticatedRequest({operation:"identity_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/identities/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Na});return V("identity_session",Go.safeParse(r)).extensionSession}async issueLaunchSession(e,n){let r=await this.authenticatedRequest({operation:"launch_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/launches/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Da});return V("launch_session",Go.safeParse(r)).extensionSession}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Oa}),i=V("fail",ks.safeParse(r));return Sn.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:i.status}),i}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:q(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Aa});return V("token_status",Ua.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:q(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Ca});return V("token_rotate",Ma.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:q(this.serverUrl,"/capabilities"),body:{capabilities:mr},signal:e?.signal,mapHttpError:Pa}),Sn.info("Capabilities declared",{capabilities:mr})}async revokeSelf(){let e=await this.authenticatedRequest({operation:"revoke",method:"POST",url:q(this.serverUrl,"/revoke"),body:null,signal:void 0,mapHttpError:La});V("revoke",rf.safeParse(e)),Sn.info("Agent registration revoked on the server by this agent")}useAgentToken(e){this.agentToken=e,Sn.info("Adopted a rotated agent token for all subsequent gateway requests")}};import{z as R}from"zod";var fr=R.object({id:R.string().min(1),status:R.string(),revision:R.number(),counts:R.object({total:R.number().int(),queued:R.number().int(),running:R.number().int(),finished:R.number().int(),notStarted:R.number().int()}),current:R.string().nullable(),waitingForRunner:R.object({ahead:R.number().int()}).nullable(),verdict:R.string().nullable(),webUrl:R.string().min(1)}),Wa=R.object({runnerId:R.string().min(1),enrollmentCode:R.string().min(1)}),af=R.object({scenarioId:R.string(),scenarioName:R.string(),status:R.string(),outcome:R.string().nullable(),failureReason:R.string().nullable(),notStartedReason:R.string().nullable(),failedStep:R.object({number:R.string(),name:R.string()}).nullable()}),Ha=R.object({items:R.array(af),total:R.number().int()}),hr="finished",gr="passed",yr="failed",Ja="no_result",Zo="passed",ei="failed",Ka="finished",wr="not_started";var lf="/api/ci/v1",Fe=class extends Error{static{o(this,"CiApiError")}},he=class extends Fe{constructor(n,r,i,s,l){super(s);this.status=n;this.errorCode=r;this.params=i;this.retryAfterMs=l}static{o(this,"CiRefusalError")}},Gt=class extends Fe{static{o(this,"CiNoAnswerError")}},lt=class extends Fe{static{o(this,"CiBadAnswerError")}},cf=100,Sr=class{static{o(this,"CiApiClient")}serverUrl;key;requestTimeoutMs;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.key=e.key,this.requestTimeoutMs=e.requestTimeoutMs,this.fetchImpl=e.fetchImpl??Mt}async createRunner(e){let n=await this.call("POST","/runners",null,this.requestTimeoutMs,e);return this.parse(Wa,n)}async createLaunch(e,n){let r=await this.call("POST","/launches",e,this.requestTimeoutMs,n);return this.parse(fr,r)}async getLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}`,i=await this.call("GET",r,null,this.requestTimeoutMs,n);return this.parse(fr,i)}async listItems(e,n,r){let i=`/launches/${encodeURIComponent(e)}/items?offset=${n}&limit=${cf}`,s=await this.call("GET",i,null,this.requestTimeoutMs,r);return this.parse(Ha,s)}async stopLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}/stop`,i=await this.call("POST",r,null,n,void 0);return this.parse(fr,i)}async call(e,n,r,i,s){let l=pr(this.serverUrl,`${lf}${n}`),c={accept:"application/json",authorization:`Bearer ${this.key}`};r!==null&&(c["content-type"]="application/json");let a=new AbortController,d=!1,u=setTimeout(()=>{d=!0,a.abort()},i),m=o(()=>a.abort(),"onCallerAbort");s!==void 0&&(s.aborted?a.abort():s.addEventListener("abort",m,{once:!0}));let g,E;try{g=await this.fetchImpl(l,{method:e,headers:c,body:r===null?void 0:JSON.stringify(r),signal:a.signal}),E=await g.text()}catch(S){throw new Gt(d?`no answer within ${Math.round(i/1e3)}s`:ur(S))}finally{clearTimeout(u),s?.removeEventListener("abort",m)}if(!g.ok){let S=Xo(g,E);throw new he(S.status,S.errorCode,S.params,S.message,S.retryAfterMs)}try{return JSON.parse(E)}catch{throw new lt(`the ${g.status} answer of Progon is not valid JSON`)}}parse(e,n){let r=e.safeParse(n);if(r.success)return r.data;throw new lt(`the answer of Progon does not match this CLI: ${zo(r.error)}`)}};var Va=`progon-agent ci run \u2014 run Progon scenarios as a step of a CI pipeline
49
+
50
+ Usage:
51
+ progon-agent ci run (--spec <id> | --scenario <id> [--scenario <id> ...]) [options]
52
+
53
+ Options:
54
+ --spec <id> run every scenario of this spec
55
+ --scenario <id> run this scenario; repeat the flag for more scenarios
56
+ --environment <id> the environment; absent: the default environment of the project
57
+ --entry-url <url> one start address for the whole launch: any http or https address
58
+ the browser can open, localhost and preview addresses included
59
+ --runner <id> the CI runner; absent: the only online CI runner of the company
60
+ --in-job run the browser inside this job; not with --runner
61
+ --timeout <duration> the time limit of the launch, for example 90s, 30m or 1h30m: Progon
62
+ stops the launch after it, and the exit code is the verdict; a launch
63
+ not created within it gives 3; absent: the launch has no deadline
64
+
65
+ Environment:
66
+ PROGON_CI_KEY the CI key of the project (required; there is no flag for it)
67
+ PROGON_SERVER_URL the address of Progon; absent: the address built into this package
68
+ PROGON_AGENT_DISABLE_BROWSER_SANDBOX --in-job: run Chromium without its sandbox, where the
69
+ host gives it none (read the risk in the documentation first)
70
+ GITHUB_STEP_SUMMARY set by GitHub Actions: the result is also written to the job summary
71
+ The commit, the branch or tag and the run address that GitHub Actions, GitLab CI and Bitbucket
72
+ Pipelines set go with the launch into its report.
73
+
74
+ Exit codes:
75
+ 0 every scenario passed
76
+ 1 at least one scenario failed
77
+ 2 the launch was not created: fix the pipeline setup (command, key, scenarios, runner)
78
+ 3 no result: runner offline or queue full, Progon or network failure, --timeout expired
79
+ before the launch was created, or a launch that ended without a failed scenario but not
80
+ fully passed`;function qa(t){let[e,...n]=t;return e===void 0?{kind:"refused",reason:"'ci' needs a command: run"}:df(e)?{kind:"help"}:e!=="run"?{kind:"refused",reason:`unknown command 'ci ${e}'`}:uf(n)}o(qa,"parseCiArgs");function df(t){return t==="--help"||t==="-h"||t==="help"}o(df,"isHelpFlag");function uf(t){let e=null,n=[],r=null,i=null,s=null,l=!1,c=null;for(let d=0;d<t.length;d+=1){let u=t[d];if(u==="--help"||u==="-h")return{kind:"help"};if(u==="--in-job"){if(l)return En(u);l=!0;continue}if(!pf.has(u))return{kind:"refused",reason:`unknown option '${u}' for 'ci run'`};let m=t[d+1];if(m===void 0||m===""||m.startsWith("--"))return{kind:"refused",reason:`'${u}' needs a value`};switch(d+=1,u){case"--spec":if(e!==null)return{kind:"refused",reason:"'--spec' is given twice"};e=m;break;case"--scenario":n.push(m);break;case"--environment":if(r!==null)return En(u);r=m;break;case"--entry-url":if(i!==null)return En(u);i=m;break;case"--runner":if(s!==null)return En(u);s=m;break;case"--timeout":{if(c!==null)return En(u);let g=mf(m);if(g===null)return{kind:"refused",reason:`'--timeout' takes a duration like 90s, 30m or 1h30m, got '${m}'`};c=g;break}}}if(l&&s!==null)return{kind:"refused",reason:"'--runner' cannot be used with '--in-job'"};if(e!==null&&n.length>0)return{kind:"refused",reason:"give either '--spec' or '--scenario', not both"};let a=e!==null?{kind:"spec",specNodeId:e}:n.length>0?{kind:"scenarios",scenarioIds:n}:null;return a===null?{kind:"refused",reason:"give '--spec <id>' or '--scenario <id>'"}:{kind:"run",options:{selection:a,environmentId:r,entryUrl:i,runnerId:s,inJob:l,timeoutMs:c}}}o(uf,"parseRunFlags");var pf=new Set(["--spec","--scenario","--environment","--entry-url","--runner","--timeout"]);function En(t){return{kind:"refused",reason:`'${t}' is given twice`}}o(En,"repeatedFlag");function mf(t){let e=/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(t);if(e===null||t==="")return null;let[,n,r,i]=e,s=o(c=>c===void 0?0:Number(c),"unitValue"),l=(s(n)*3600+s(r)*60+s(i))*1e3;return l>0&&l<=2147483647?l:null}o(mf,"parseDurationMs");var ti=0,ff=1,ct=2,U=3,hf=new Map([[409,new Set(["agents.runner_ambiguous","agents.capability_missing","agent_enroll.protocol_version","agents.one_shot_used"])],[426,new Set(["client.upgrade_required"])]]);function vn(t,e){return t===400||t===401||t===403||t===404||t===422||e!==null&&hf.get(t)?.has(e)===!0?ct:U}o(vn,"exitCodeOfRefusalBeforeLaunch");function Ya(t){return t===gr?ti:t===yr?ff:U}o(Ya,"exitCodeOfVerdict");function D(t,e){let n=t[e];return n===void 0||n===""?null:n}o(D,"readJobVariable");function Xa(t){return t.GITHUB_ACTIONS==="true"?gf(t):t.GITLAB_CI==="true"?yf(t):D(t,"BITBUCKET_BUILD_NUMBER")!==null?wf(t):null}o(Xa,"readCiJobFacts");function gf(t){let e=t.GITHUB_EVENT_NAME==="pull_request"?D(t,"GITHUB_HEAD_REF"):D(t,"GITHUB_REF_NAME"),n=D(t,"GITHUB_SERVER_URL"),r=D(t,"GITHUB_REPOSITORY"),i=D(t,"GITHUB_RUN_ID"),s=n===null||r===null||i===null?null:`${n}/${r}/actions/runs/${i}`;return ni(D(t,"GITHUB_SHA"),e,s)}o(gf,"fromGitHub");function yf(t){return ni(D(t,"CI_COMMIT_SHA"),D(t,"CI_COMMIT_REF_NAME"),D(t,"CI_JOB_URL"))}o(yf,"fromGitLab");function wf(t){let e=D(t,"BITBUCKET_REPO_FULL_NAME"),n=D(t,"BITBUCKET_BUILD_NUMBER"),r=e===null||n===null?null:`https://bitbucket.org/${e}/pipelines/results/${n}`,i=D(t,"BITBUCKET_BRANCH"),s=i===null?D(t,"BITBUCKET_TAG"):i;return ni(D(t,"BITBUCKET_COMMIT"),s,r)}o(wf,"fromBitbucket");function ni(t,e,n){return t===null&&e===null&&n===null?null:{...t===null?{}:{commit:t},...e===null?{}:{ref:e},...n===null?{}:{runUrl:n}}}o(ni,"factsOf");import{mkdtempSync as bg,rmSync as _g}from"node:fs";import{tmpdir as kg}from"node:os";import{join as hc}from"node:path";import{chmodSync as Rf,cpSync as Tf,mkdirSync as xf,readdirSync as If,renameSync as Of,rmSync as ii,statSync as ol,writeFileSync as Af}from"node:fs";import{dirname as Cf,join as Ft}from"node:path";import{fileURLToPath as Pf}from"node:url";import{randomBytes as Sf}from"node:crypto";import{lstatSync as za,readFileSync as Ef,renameSync as vf,rmSync as bf,writeFileSync as _f}from"node:fs";import{join as Qa}from"node:path";var kf=w("cleanup-ownership"),Er="progon-agent-cleanup.json";function Za(t){return/^progon-agent-cleanup\.json\.tmp-\d+-[0-9a-f]{16}$/.test(t)}o(Za,"isCleanupTemporaryEntry");var vr={version:1,serviceFiles:!1,extensionCopy:!1,profiles:[]};function br(t){let e=Qa(t,Er),n;try{if(!za(e).isFile())throw new Error("Cleanup ownership marker is not a regular file");n=JSON.parse(Ef(e,"utf8"))}catch(s){if(P(s))return null;throw s}if(typeof n!="object"||n===null)throw new Error("Invalid cleanup ownership marker");let r=n,i=r.profiles;if(r.version!==1||typeof r.serviceFiles!="boolean"||typeof r.extensionCopy!="boolean"||!Array.isArray(i)||!i.every(s=>typeof s=="string"&&s!==""&&s!=="."&&s!==".."&&!/[\\/\0]/.test(s)))throw new Error("Invalid cleanup ownership marker");return{version:1,serviceFiles:r.serviceFiles,extensionCopy:r.extensionCopy,profiles:i}}o(br,"readCleanupOwnership");function _r(t,e){let n=Qa(t,Er),r=`${n}.tmp-${process.pid}-${Sf(8).toString("hex")}`;try{_f(r,JSON.stringify(e),{flag:"wx",mode:384,flush:!0}),vf(r,n)}finally{bf(r,{force:!0})}}o(_r,"writeCleanupOwnership");function el(t){try{za(t)}catch(e){if(P(e))return;throw e}nl(t,"serviceFiles")}o(el,"rememberServiceCleanup");function tl(t){nl(t,"extensionCopy")}o(tl,"rememberExtensionCopy");function nl(t,e){let n=br(t)??vr;n[e]||_r(t,{...n,[e]:!0})}o(nl,"remember");function kr(t,e){return rl(t,e,"remember")}o(kr,"rememberProfileCleanup");function ri(t,e){return rl(t,e,"forget")}o(ri,"forgetProfileCleanup");function rl(t,e,n){try{let r=br(t)??vr,{profiles:i}=r;return i.includes(e)===(n==="remember")||_r(t,{...r,profiles:n==="remember"?[...i,e]:i.filter(s=>s!==e)}),!0}catch(r){return kf.warn("Could not update profile cleanup ownership",{stateDir:t,runId:e,operation:n,err:r instanceof Error?r.message:String(r)}),!1}}o(rl,"updateProfileCleanup");var Rr=w("extension-dist"),Nf="extension-dist",ai="extension-dist",si=`${ai}.tmp-`,li="agent-manifest.json";function sl(t){return t.startsWith(si)&&/^\d+$/.test(t.slice(si.length))}o(sl,"isStagingDirName");function al(t){return t===ai||sl(t)}o(al,"isExtensionWorkingCopyName");var il="manifest.json";function Lf(){return Se(Cf(Pf(import.meta.url)))}o(Lf,"packageRoot");function Df(){return $f(Ft(Lf(),Nf))}o(Df,"resolveBundledExtensionSource");function $f(t){let e;try{e=ol(t)}catch(r){throw P(r)?new Error(oi(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(oi(t,"that path is not a directory"));let n=Ft(t,il);try{ol(n)}catch(r){throw P(r)?new Error(oi(t,`it holds no ${il}`),{cause:r}):r}return t}o($f,"assertBundledExtensionSource");function oi(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
19
81
  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(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.
82
+ 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).`}o(oi,"bundledMissingMessage");function Uf(t){let{stateDir:e,agentId:n}=t;if(n==="")throw new Error(`[extension-dist] agentId is required: ${li} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=t.sourceDir??Df(),i=Ft(e,ai),s=Ft(e,`${si}${process.pid}`);return xf(e,{recursive:!0,mode:448}),tl(e),Gf(e),ii(s,{recursive:!0,force:!0}),Tf(r,s,{recursive:!0}),Rf(s,448),Mf(s,n),ii(i,{recursive:!0,force:!0}),Of(s,i),Rr.info("Agent-mode extension dist prepared",{extensionDist:i,sourceDir:r,agentId:n,protocolVersion:1}),i}o(Uf,"prepareAgentExtensionDist");function Mf(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};Af(Ft(t,li),JSON.stringify(n,null,2)+`
83
+ `,"utf8")}o(Mf,"writeAgentManifest");function Gf(t){let e;try{e=If(t,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return;throw n}for(let n of e){if(!sl(n.name))continue;let r=Ft(t,n.name);try{ii(r,{recursive:!0,force:!0}),Rr.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(i){Rr.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:i instanceof Error?i.message:String(i)})}}}o(Gf,"removeLeftoverStagingDirs");function Tr(t){return t.overridePath!==void 0?(Rr.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:t.overridePath}),t.overridePath):Uf({stateDir:t.stateDir,agentId:ci(t.agentId)})}o(Tr,"resolveExtensionDist");function ci(t){if(t===null)throw new p(`[extension-dist] Cannot prepare the agent-mode extension dist: this daemon authenticated with PROGON_AGENT_TOKEN, which carries no agentId, and ${li} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
84
+ 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 t}o(ci,"requireManifestAgentId");function ge(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)}o(ge,"computeBackoffDelayMs");function Be(t){let e=Ff(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:ge(t.attempt,t.rng)}}o(Be,"decideGatewayRetry");function Ff(t){if(t instanceof T)return"terminal_signal";if(t instanceof fe)return"contract_breach";if(t instanceof ee)return"upgrade_required";if(t instanceof O)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof Z||t instanceof Ot)return null;if(t instanceof x)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.`)}o(Ff,"classifyFailure");import{mkdtempSync as th,rmSync as nh}from"node:fs";import{tmpdir as rh}from"node:os";import{join as oh}from"node:path";import{execFile as jf}from"node:child_process";import{promisify as Wf}from"node:util";import{setTimeout as ul}from"node:timers/promises";var xr=Wf(jf),Ir={timeout:5e3};function pl(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:""}}o(pl,"asExecFailure");function Hf(t){let e=[];for(let n of t.split(`
85
+ `)){let r=n.trim();if(r==="")continue;let i=Number(r);!Number.isInteger(i)||i===process.pid||e.push(i)}return e}o(Hf,"parsePidLines");var di="--user-data-dir=",Jf=new Set([" "," ",'"',"'"]),Kf=new Set([" "," ",'"',"'"]);function Vf(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}o(Vf,"escapeEre");function qf(t){return`(^|[[:space:]'"])${Vf(`${di}${t}`)}([[:space:]'"]|$)`}o(qf,"buildAnchorPattern");function Yf(t,e){let n=t.toLowerCase(),r=`${di}${e}`.toLowerCase();for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let s=i===0?void 0:n[i-1],l=n[i+r.length],c=s===void 0||Jf.has(s),a=l===void 0||Kf.has(l);if(c&&a)return!0}return!1}o(Yf,"matchesAnchor");async function Xf(t){try{let{stdout:e}=await xr("pgrep",["-f",qf(t)],Ir);return Hf(e)}catch(e){let n=pl(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}o(Xf,"discoverPosix");async function ll(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${di}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await xr("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],Ir),i=[];for(let s of r.split(`
86
+ `)){let l=s.indexOf(" ");if(l===-1)continue;let c=Number(s.slice(0,l).trim()),a=s.slice(l+1);!Number.isInteger(c)||c===process.pid||Yf(a,t)&&i.push(c)}return i}o(ll,"discoverWin32");async function cl(){let{stdout:t}=await xr("ps",["-A","-o","pid=,ppid=,pgid="],Ir),e=[];for(let n of t.split(`
87
+ `)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[i,s,l]=r,c=Number(i),a=Number(s),d=Number(l);!Number.isInteger(c)||!Number.isInteger(a)||!Number.isInteger(d)||e.push({pid:c,ppid:a,pgid:d})}return e}o(cl,"readProcessTable");function zf(t,e){let n=new Map;for(let a of t){let d=n.get(a.ppid);d===void 0?n.set(a.ppid,[a.pid]):d.push(a.pid)}let r=new Set(e),i=[...e];for(let a=i.pop();a!==void 0;a=i.pop()){let d=n.get(a);if(d!==void 0)for(let u of d)r.has(u)||(r.add(u),i.push(u))}let s=t.find(a=>a.pid===process.pid),l=s===void 0?null:s.pgid,c=new Set;for(let a of t)r.has(a.pid)&&(a.pgid<=0||l!==null&&a.pgid===l||c.add(a.pgid));return r.delete(process.pid),{members:[...r],groups:[...c]}}o(zf,"expandTree");function Qf(t){try{return process.kill(t,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}o(Qf,"sigkill");async function Bt(t){return process.platform==="win32"?eh(t):Zf(t)}o(Bt,"killProcessTree");async function Zf(t){let e=await Xf(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await cl(),{members:r,groups:i}=zf(n,e),s=[];for(let a of r)Qf(a)==="signalled"&&s.push(a);for(let a of i)try{process.kill(-a,"SIGKILL")}catch(d){if(typeof d!="object"||d===null||d.code!=="ESRCH")throw d}await ul(500);let l=await cl(),c=new Set(l.map(a=>a.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:s,survivorPids:r.filter(a=>c.has(a))}}o(Zf,"killProcessTreePosix");async function eh(t){let e=await ll(t),n=[];for(let i of e)try{await xr("taskkill.exe",["/T","/F","/PID",String(i)],Ir),n.push(i)}catch(s){let l=pl(s);if(l===null||l.code!==128)throw s}await ul(500);let r=await ll(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}o(eh,"killProcessTreeWin32");var ml=w("browser-sandbox-probe"),ih=[" - Ubuntu 23.10 or newer restricts user namespaces with AppArmor. Give Chromium an AppArmor"," profile: https://chromium.googlesource.com/chromium/src/+/main/docs/security/apparmor-userns-restrictions.md"," - In a container, Docker's default seccomp profile blocks the namespaces Chromium needs. Use"," a seccomp profile that allows them, and run as a user other than root."," - Chromium refuses to use its sandbox as root. Run the agent as an ordinary user."," - If you accept the risk on this machine, set PROGON_AGENT_DISABLE_BROWSER_SANDBOX=true. A"," renderer exploit on any page a run opens then gets this user's rights."].join(`
88
+ `);async function Or(){let t=Date.now(),e=th(oh(rh(),"progon-agent-sandbox-probe-")),n=null;try{n=await ya(e),await(await n.newPage()).evaluate("1")}catch(r){throw new p(`[browser-sandbox] Chromium could not start with its sandbox on this machine, so the agent is not starting.
89
+ ${ih}
90
+ Chromium's output: ${r instanceof Error?r.message:String(r)}`,{cause:r})}finally{await sh(n,e)}ml.info("Chromium runs with its sandbox on this machine",{durationMs:Date.now()-t})}o(Or,"probeBrowserSandbox");async function sh(t,e){try{t!==null&&(await cr(t,2e4)).settled==="closed"||await Bt(e),nh(e,{recursive:!0,force:!0})}catch(n){ml.error("Could not clean up the sandbox probe: a browser or its profile may be left",{userDataDir:e,err:n instanceof Error?n.message:String(n)})}}o(sh,"closeProbeBrowser");var ah=w("run-browser-preparation");async function Ar(t){if(await kt({stdio:"pipe",signal:t.signal}),t.signal?.throwIfAborted(),t.disableBrowserSandbox){ah.warn("PROGON_AGENT_DISABLE_BROWSER_SANDBOX is set: Chromium runs without its sandbox, so a renderer exploit on any page a run opens gets this user's rights");return}await Or()}o(Ar,"prepareRunBrowser");var lh=w("worker-evaluate"),ui=class extends Error{static{o(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 Ie(t){let e=t.evaluate(),n=!1;e.catch(s=>{n&&lh.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,l)=>{r=setTimeout(()=>{n=!0,l(new ui(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Ie,"evaluateWithDeadline");var fl={name:"progon-session",version:1,store:"tokens"},hl="accessToken",gl="refreshToken";async function wl(t,e){await Ie({operation:"write the run session into the token database",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,s,l,c])=>new Promise((a,d)=>{let u=indexedDB.open(r.name,r.version);u.onupgradeneeded=()=>{u.result.createObjectStore(r.store)},u.onerror=()=>d(new Error("the token database did not open")),u.onsuccess=()=>{let m=u.result,g=m.transaction(r.store,"readwrite"),E=g.objectStore(r.store);E.put(l,i),E.put(c,s),g.oncomplete=()=>{m.close(),a()},g.onabort=()=>{m.close(),d(new Error("the token write was aborted"))}}}),[fl,hl,gl,e.accessToken,e.refreshToken]),"evaluate")});let n=await Ie({operation:"read the run session back out of the token database",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,s])=>new Promise((l,c)=>{let a=indexedDB.open(r.name,r.version);a.onerror=()=>c(new Error("the token database did not open")),a.onsuccess=()=>{let d=a.result,u=d.transaction(r.store,"readonly"),m=u.objectStore(r.store),g=m.get(i),E=m.get(s);u.oncomplete=()=>{d.close(),l({accessTokenLength:typeof g.result=="string"?g.result.length:null,refreshTokenLength:typeof E.result=="string"?E.result.length:null})},u.onabort=()=>{d.close(),c(new Error("the token read was aborted"))}}}),[fl,hl,gl]),"evaluate")});if(n.accessTokenLength!==e.accessToken.length||n.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: the token database holds accessToken(len=${String(n.accessTokenLength)}), refreshToken(len=${String(n.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return n}o(wl,"seedRunSession");function yl(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}o(yl,"canonicalise");async function Sl(t,e){await Ie({operation:`write the command envelope to chrome.storage.session['${Ze}']`,timeoutMs:1e4,evaluate:o(()=>t.evaluate(([l,c])=>new Promise(a=>chrome.storage.session.set({[l]:c},()=>chrome.storage.local.set({[l]:!0},()=>a()))),[Ze,e]),"evaluate")});let n=await Ie({operation:"read the command envelope back out of chrome.storage.session",timeoutMs:1e4,evaluate:o(()=>t.evaluate(l=>new Promise(c=>chrome.storage.session.get([l],a=>{let d=a[l];c(d===void 0?null:d)})),Ze),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.session['${Ze}'] does not hold the envelope`);let r=yl({...e}),i=yl(n);if(r!==i)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${i}`);let s=await Ie({operation:"read the command marker back out of chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(l=>new Promise(c=>chrome.storage.local.get([l],a=>{let d=a[l];c(d===void 0?null:d)})),Ze),"evaluate")});if(s!==!0)throw new Error(`command marker read-back returned ${JSON.stringify(s)} \u2014 chrome.storage.local['${Ze}'] does not hold it`)}o(Sl,"seedCommandEnvelope");async function dh(t,e,n){let r=await Ie({operation:`read chrome.storage.session['${Vn}']`,timeoutMs:n,evaluate:o(()=>t.evaluate(s=>new Promise(l=>chrome.storage.session.get([s],c=>{let a=c[s];l(a===void 0?null:a)})),Vn),"evaluate")});if(r===null)return{kind:"absent"};let i=bs.safeParse(r);return i.success?i.data.runId!==e?{kind:"other_run",detail:`the ack under that key belongs to run ${i.data.runId}`}:{kind:"ack",ack:i.data}:{kind:"invalid",detail:`the value under that key failed agentCommandAckSchema: ${String(i.error)}`}}o(dh,"pollCommandAck");async function El(t,e,n){let r=Date.now()+n,i="no ack was written";for(;;){let s=r-Date.now();if(s<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${i}. chrome.storage.session['${Vn}'] is the only success signal (CONTRACT-la \xA75.4).`);let l=t.serviceWorkers()[0];if(l===void 0)i="the context exposed no service worker while polling (evicted, restarting)";else{let c;try{c=await dh(l,e,s)}catch(a){i=`the last poll failed: ${a instanceof Error?a.message:String(a)}`,c={kind:"invalid",detail:i}}if(c.kind==="ack")return c.ack;c.kind!=="absent"&&(i=c.detail)}await new Promise(c=>setTimeout(c,250))}}o(El,"waitForCommandAck");async function vl(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}o(vl,"waitForServiceWorker");async function bl(t,e){let n,r=new Promise((i,s)=>{n=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 i=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof i!="string"||i==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(i)} \u2014 expected a non-empty extension id`);return i}finally{n!==void 0&&clearTimeout(n)}}o(bl,"readRuntimeId");function Cr(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}o(Cr,"remainingBudgetMs");async function kl(t){let e=Date.now(),n=e+45e3,r=n-5e3,i=await vl(t,Math.min(5e3,Cr(r,"the service-worker target wait")));try{let s=await bl(i,Cr(r,"the first readiness evaluate"));return{worker:i,extensionId:s,serviceWorkerUrl:i.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(s){let l=await t.newPage();try{let c=await vl(t,Math.min(5e3,Cr(n,"the retry service-worker target wait"))),a=await bl(c,Cr(n,"the retry readiness evaluate"));return{worker:c,extensionId:a,serviceWorkerUrl:c.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(c){let a=s instanceof Error?s.message:String(s),d=c instanceof Error?c.message:String(c);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${a}. Page-open retry: ${d}.`,{cause:c})}finally{await l.close()}}}o(kl,"probeExtensionReadiness");var je=class extends Error{static{o(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,i){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:i}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function mi(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)}o(mi,"deepestCauseMessage");var uh=/^\s*(?:- )?\[pid=\d+\]\[err\] ?(.*)$/;function Rl(t){let e=[];for(let n of t.split(`
91
+ `)){let r=uh.exec(n)?.[1];r!==void 0&&r!==""&&e.push(r)}return e.length===0?null:e.join(" | ")}o(Rl,"browserStderrOf");var ph=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),mh=/\bnet::(ERR_[A-Z0-9_]+)\b/;function Tl(t){if(fh(t))return"timeout";let e=mh.exec(mi(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":ph.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}o(Tl,"entryFailureOf");function fh(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof pa.TimeoutError)return!0;e.add(n),n=n.cause}return!1}o(fh,"causeChainHasTimeout");var We=class extends Error{static{o(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}},jt=class extends Error{static{o(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}};var re=w("browser-instance");async function Pr(t){let e=await ae(t.runId,"browser_launch",()=>ga({userDataDir:t.userDataDir,extensionDist:t.extensionDist,headful:t.headful,allowInsecureHttps:t.allowInsecureHttps,disableBrowserSandbox:t.disableBrowserSandbox,keepBackgroundWindowsRendering:t.keepBackgroundWindowsRendering}));t.onContext(e),t.assertNotAborted();let n=await ae(t.runId,"browser_version",()=>Sa(e)),r=await ae(t.runId,"readiness_probe",()=>kl(e));await gh(t,r.worker);let{entryUrl:i}=t;return i===null?await ae(t.runId,"empty_tab",()=>Eh(e)):await ae(t.runId,"entry_navigation",()=>Sh(e,i)),await yh(t,e),{context:e,chromeVersion:n,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}o(Pr,"bringUpBrowser");async function gh(t,e){let n=await ae(t.runId,"token_seed",()=>wl(e,t.extensionSession));re.info("Run session seeded into the browser profile",{runId:t.runId,userDataDir:t.userDataDir,accessTokenLength:n.accessTokenLength,refreshTokenLength:n.refreshTokenLength}),await ae(t.runId,"command_seed",()=>Sl(e,t.command)),re.info("Command envelope seeded",{runId:t.runId,userDataDir:t.userDataDir,command:t.command})}o(gh,"seed");async function yh(t,e){let n=await ae(t.runId,"command_ack",()=>El(e,t.runId,15e3));if(n.outcome==="rejected")throw new je(t.runId,"command_ack",`the extension refused the command envelope: ${n.reason}`);re.info("Command envelope dispatched by the extension",{runId:t.runId,userDataDir:t.userDataDir,kind:t.command.kind})}o(yh,"awaitDispatchAck");async function _n(t,e){let n=Date.now(),r="closed",i=null,s=null;if(e.context!==null){let g=await cr(e.context,e.timeoutMs);g.settled==="closed"?r="closed":g.settled==="timeout"?(r="timeout-force-killed",re.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",re.error("context.close() rejected \u2014 force-killing",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g.error instanceof Error?g.error.message:String(g.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{i=await Bt(e.userDataDir)}catch(g){s=g,re.error("Force-kill of the run process tree failed",{runId:e.instanceKey,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:g instanceof Error?g.message:String(g)})}let c=s===null&&(i===null||i.survivorPids.length===0),a=null,d=!1;if(c)try{t.release(e.instanceKey),d=!0}catch(g){a=g,re.error("Failed to remove the instance directory after teardown",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g instanceof Error?g.message:String(g)})}else re.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:i===null?null:i.survivorPids});let u={runId:e.instanceKey,outcome:r,kill:i,instanceReleased:d,durationMs:Date.now()-n},m={runId:u.runId,disposeOutcome:u.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:u.kill,killFailed:s!==null,instanceReleased:u.instanceReleased,durationMs:u.durationMs};return s!==null||a!==null?re.error("Instance disposed with a failed cleanup step",m):re.info("Instance disposed",m),{result:u,killConfirmed:c,failure:wh(e,i,s,a)}}o(_n,"tearDownBrowser");function Nr(t,e){let{instanceKey:n}=e;if(!e.killConfirmed)throw re.error("Dispose repeated for an instance whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:n,disposeOutcome:e.result.outcome,kill:e.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for ${n} 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();re.warn("Dispose repeated for an instance whose directory survived \u2014 retrying",{runId:n,disposeOutcome:e.result.outcome}),t.release(n);let i={...e.result,instanceReleased:!0,durationMs:Date.now()-r};return re.info("Instance released on a repeated dispose",{runId:n,disposeOutcome:i.outcome,instanceReleased:!0,durationMs:i.durationMs}),i}o(Nr,"retryRetainedRelease");function wh(t,e,n,r){return r!==null?xl(r):n!==null?xl(n):e!==null&&e.survivorPids.length>0?new Error(`[runtime] force-kill for run ${t.instanceKey} left ${e.survivorPids.length} process(es) alive after the settle delay (${e.survivorPids.join(", ")}). The instance directory ${t.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`):null}o(wh,"teardownFailure");function xl(t){return t instanceof Error?t:new Error(String(t))}o(xl,"asError");async function ae(t,e,n){try{return await n()}catch(r){throw r instanceof je||r instanceof We?r:new je(t,e,r instanceof Error?r.message:String(r),r)}}o(ae,"stage");async function Sh(t,e){await(await Il(t)).goto(e,{waitUntil:"domcontentloaded"})}o(Sh,"navigateToEntry");async function Eh(t){await Il(t)}o(Eh,"prepareEmptyTab");async function Il(t){let e=t.pages()[0],n=e===void 0?await t.newPage():e;return await wa(t,n),n}o(Il,"sizedFirstPage");import Lr from"node:os";import{createRequire as vh}from"node:module";var Ol=vh(import.meta.url);function bh(){let t=Ol.resolve("playwright-core/package.json"),e=Ol(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}o(bh,"readPlaywrightCoreVersion");function Al(t){return{node:process.version,platform:`${Lr.platform()} ${Lr.release()} ${Lr.arch()}`,cpus:Lr.cpus().length,playwrightCore:bh(),chromiumExecutable:rt.executablePath(),channel:wn,extensionDist:t}}o(Al,"buildEnvFingerprint");async function Dr(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 i=await Ie({operation:"read playback, job pulse and identity detach from chrome.storage.session",timeoutMs:1e4,evaluate:o(()=>r.evaluate(async s=>{let l=await new Promise(g=>chrome.storage.session.get(["tabStates",s,"agent:detached-identity"],g)),c=l.tabStates,a=typeof c!="object"||c===null?[]:Object.entries(c).map(([g,E])=>{let S=typeof E=="object"&&E!==null?E.playback:null;if(typeof S!="object"||S===null)return{tabId:g,playback:null};let b=S;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}}}),d=l[s],u=typeof d!="object"||d===null?null:(()=>{let g=d;return{agentJobId:typeof g.agentJobId=="string"?g.agentJobId:null,updatedAt:typeof g.updatedAt=="string"?g.updatedAt:null}})(),m=l["agent:detached-identity"];if(m===void 0)return{tabs:a,agentJob:u};if(typeof m!="object"||m===null||!("agentJobId"in m)||typeof m.agentJobId!="string"||!("identityId"in m)||typeof m.identityId!="string")throw new Error("Unreadable identity detach acknowledgement in chrome.storage.session");return{tabs:a,agentJob:u,detachedIdentity:{agentJobId:m.agentJobId,identityId:m.identityId}}},cs),"evaluate")});return{ok:!0,observedAt:e,...i}}catch(i){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:i instanceof Error?i.message:String(i)}}}o(Dr,"probePlaybackSession");var Wt=w("task-browser-instances"),fi=class extends Error{static{o(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}},Ht=class{static{o(this,"TaskBrowserInstances")}#e;#t;#n;#r;#i;#a;#s=new Map;#o=new Map;constructor(e){this.#e=e.registry,this.#t=e.extensionDist,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onLost,this.#a=e.kind}subjectIdsWithInstance(){return[...this.#s.keys()]}async start(e,n,r,i){let s=this.#s.get(n);if(s!==void 0)throw new Error(`[runtime] task browser subject ${n} already has an instance in state ${s.state}`);let l=this.#m(e.jobId,n),c=await ae(e.jobId,"instance_reserve",()=>{let u=this.#o.get(l);return u!==void 0&&this.#d(u),this.#e.reserve(l,e.deadlineAt)}),a={subjectId:n,jobId:e.jobId,instanceKey:l,userDataDir:c.userDataDir,state:"launching",context:null,contextAtTeardown:null,teardown:null};this.#s.set(n,a),Wt.info("Launching the browser task browser instance",{runId:e.jobId,workflowId:e.workflowId,subjectId:n,headful:e.headful,userDataDir:c.userDataDir,deadlineAt:e.deadlineAt});let d=Date.now();try{let u=await Pr({runId:e.jobId,userDataDir:c.userDataDir,extensionDist:this.#t,headful:e.headful,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:!0,extensionSession:r,command:i,entryUrl:i.kind==="task_launch"?e.entryUrl:null,onContext:o(m=>{a.context=m},"onContext"),assertNotAborted:o(()=>this.#l(a),"assertNotAborted")});this.#l(a),a.state="active",this.#u(a,u.context),Wt.info("Task browser instance launched",{runId:e.jobId,subjectId:n,chromeVersion:u.chromeVersion,extensionId:u.extensionId,readinessAttempts:u.readinessAttempts,readyAfterMs:u.readyAfterMs,launchDurationMs:Date.now()-d})}catch(u){let m=o(g=>{Wt.error("Teardown after a failed task browser launch did not finish",{runId:e.jobId,subjectId:n,err:g instanceof Error?g.message:String(g)})},"logTeardownFailure");if(a.teardown===null)await this.#c(a,"launch_failure").catch(m);else if(await a.teardown.catch(m),a.context!==null&&a.context!==a.contextAtTeardown){let g=await _n(this.#e,{instanceKey:a.instanceKey,context:a.context,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:"dispose_during_launch"});this.#p(a,g),g.failure!==null&&m(g.failure)}throw u}}async dispose(e,n){let r=this.#s.get(n);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 i=this.#o.get(this.#m(e,n));return i!==void 0?this.#d(i):null}async disposeAll(e){let n=new Set;for(let s of this.#s.values())s.jobId===e&&n.add(s.subjectId);for(let s of this.#o.values())s.jobId===e&&n.add(s.subjectId);if(n.size===0)return;let i=(await Promise.allSettled([...n].map(s=>this.dispose(e,s)))).find(s=>s.status==="rejected");if(i!==void 0)throw i.reason}async probe(e){let n=this.#s.get(e);return n===void 0||n.state!=="active"||n.context===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:`the runtime owns no running instance of task browser subject ${e}`}:Dr(n.context)}#l(e){if(e.teardown!==null)throw new fi(e.subjectId)}#u(e,n){let r=o(s=>{if(e.state!=="active"||e.teardown!==null)return;let l=this.#c(e,"instance_lost"),c={jobId:e.jobId,subjectId:e.subjectId,at:new Date().toISOString(),source:s};Wt.warn("Task browser instance disappeared without a dispose",{...c}),l.catch(a=>{Wt.error("Teardown after a lost task browser instance failed",{runId:e.jobId,subjectId:e.subjectId,err:a instanceof Error?a.message:String(a)})}).finally(()=>this.#i(c))},"report");n.on("close",()=>r("context_closed"));let i=n.browser();i!==null&&i.on("disconnected",()=>r("browser_disconnected"))}#c(e,n){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let i=await _n(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:n});if(Wt.info("Task browser instance closed",{runId:e.jobId,subjectId:e.subjectId,trigger:n,disposeOutcome:i.result.outcome,instanceReleased:i.result.instanceReleased}),this.#p(e,i),i.failure!==null)throw i.failure;return i.result}finally{this.#s.get(e.subjectId)===e&&this.#s.delete(e.subjectId)}})();return e.teardown=r,r}#p(e,n){if(n.result.instanceReleased){this.#o.delete(e.instanceKey);return}this.#o.set(e.instanceKey,{instanceKey:e.instanceKey,jobId:e.jobId,subjectId:e.subjectId,result:n.result,killConfirmed:n.killConfirmed})}#m(e,n){return this.#a==="identity"?`${e}~${n}`:`${e}~launch~${n}`}#d(e){let n=Nr(this.#e,e);return this.#o.delete(e.instanceKey),n}};var $r=class{static{o(this,"IdentityInstances")}#e;constructor(e){this.#e=new Ht({...e,kind:"identity",onLost:o(({subjectId:n,...r})=>e.onLost({...r,identityId:n}),"onLost")})}identityIdsWithInstance(){return this.#e.subjectIdsWithInstance()}async start(e,n,r){await this.#e.start(e,n,r,{v:1,kind:"task_identity",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,identityId:n})}dispose(e,n){return this.#e.dispose(e,n)}disposeAll(e){return this.#e.disposeAll(e)}probe(e){return this.#e.probe(e)}};var Ur=class{static{o(this,"TaskJobInstances")}identities;launches;constructor(e){this.identities=new $r(e),this.launches=new Ht({...e,kind:"launch",onLost:o(({subjectId:n,...r})=>e.onLaunchLost({...r,launchId:n}),"onLost")})}async startLaunch(e,n,r){await this.launches.start(e,n,r,{v:1,kind:"task_launch",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,launchId:n})}async disposeAll(e){let n=await Promise.allSettled([this.identities.disposeAll(e),this.launches.disposeAll(e)]);for(let r of n)if(r.status==="rejected")throw r.reason}};import{mkdirSync as Cl,lstatSync as kh,readdirSync as Rh,readFileSync as Th,renameSync as xh,rmSync as Ih,writeFileSync as Oh}from"node:fs";import{join as kn}from"node:path";var dt=w("instance-registry");function Mr(t){return typeof t=="string"&&t!==""}o(Mr,"isNonEmptyString");function Ah(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(!Mr(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!Mr(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!Mr(n.startedAt)||!Mr(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}}o(Ah,"parseInstanceRecord");function Ch(t,e){let n=`${t}.tmp`;Oh(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),xh(n,t)}o(Ch,"writeMarkerAtomically");var ut=class{static{o(this,"InstanceRegistry")}#e;#t;constructor(e){this.#t=e,this.#e=kn(e,ar)}get instancesRoot(){return this.#e}userDataDirFor(e){return kn(this.#e,e)}reserve(e,n){Cl(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Cl(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new We(e,r,s):s}let i=new Date().toISOString();try{kr(this.#t,e),Ch(kn(r,lr),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:i,deadlineAt:n})}catch(s){try{this.release(e)}catch(l){dt.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:l instanceof Error?l.message:String(l)})}throw s}return dt.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:i,deadlineAt:n}}read(e){return this.#r(kn(this.userDataDirFor(e),lr))}release(e){let n=this.userDataDirFor(e);try{kh(n)}catch(i){if(!P(i))throw i;ri(this.#t,e);return}let r=kr(this.#t,e);try{Ih(n,{recursive:!0,force:!0})}catch(i){throw r||kr(this.#t,e),i}ri(this.#t,e),dt.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Rh(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.#n(r));return n.length>0?dt.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):dt.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#n(e){let n=this.userDataDirFor(e),r=kn(n,lr),i=null,s;try{i=this.#r(r),s="valid"}catch(c){s=(typeof c=="object"&&c!==null?c.code:null)==="ENOENT"?"missing":"unreadable",dt.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:s,err:c instanceof Error?c.message:String(c)})}let l=await Bt(n);return dt.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:s,kill:l}),this.release(e),{runId:e,userDataDir:n,marker:s,record:i,kill:l,removed:!0}}#r(e){let n=Th(e,"utf8");return Ah(JSON.parse(n),e)}};var Oe=w("playwright-execution-runtime"),hi=class extends Error{static{o(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}},Gr=class{static{o(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#i;#a;#s;#o;#l=null;#u=null;#c=null;#p=!1;#m=null;#d=null;constructor(e){dr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onInstanceLost,this.#a=new ut(e.stateDir),this.#s=Al(e.extensionDist),this.#o=new Ur({registry:this.#a,extensionDist:e.extensionDist,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox,onLost:e.onIdentityInstanceLost,onLaunchLost:e.onLaunchInstanceLost}),Oe.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#l;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,n,r){await this.#o.identities.start(this.#g(e),n,r)}async startLaunchInstance(e,n,r){await this.#o.startLaunch(this.#g(e),n,r)}disposeLaunchInstance(e,n){return this.#o.launches.dispose(e,n)}launchIdsWithInstance(){return this.#o.launches.subjectIdsWithInstance()}async disposeIdentityInstance(e,n){return this.#o.identities.dispose(e,n)}async probeIdentityInstance(e){return this.#o.identities.probe(e)}identityIdsWithInstance(){return this.#o.identities.identityIdsWithInstance()}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#l;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:Dr(e.context)}prepareTaskJob(e){if(e.command.kind!=="swarm"||e.entryUrl===null)throw new Error(`[runtime] job ${e.runId} is not a task claim with an entry address`);let n=this.#u?.jobId??this.#l?.runId??this.#c?.runId;if(n!==void 0)throw new jt(e.runId,n);let r=Pl(e);return this.#u={jobId:e.runId,workflowId:e.command.workflowId,entryUrl:e.entryUrl,headful:this.#h(e),deadlineAt:r},r}#g(e){let n=this.#u;if(n===null||n.jobId!==e)throw new Error(`[runtime] job ${e} is not the claimed task job`);return n}async startRun(e){let n=this.#l;if(n!==null)throw new jt(e.runId,n.runId);let r=Date.now();e.command.kind==="swarm"&&this.#u===null&&this.prepareTaskJob(e);let i=this.#u;if(i!==null&&i.jobId!==e.runId)throw new jt(e.runId,i.jobId);let s=i?.deadlineAt??Pl(e),l=this.#h(e),c=await ae(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,s));this.#d?.runId===e.runId&&(this.#d=null);let a={runId:e.runId,userDataDir:c.userDataDir,context:null,disposeRequested:!1};this.#c=a;let d=e.command.kind==="swarm"||e.command.kind==="conversation";Oe.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:d,userDataDir:c.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:s,envFingerprint:this.#s});let u=null;try{let m=await Pr({runId:e.runId,userDataDir:c.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:d,extensionSession:e.extensionSession,command:e.command,entryUrl:e.command.kind==="swarm"?null:e.entryUrl,onContext:o(E=>{u=E,a.context=E},"onContext"),assertNotAborted:o(()=>this.#w(a),"assertNotAborted")}),g={runId:e.runId,context:m.context,userDataDir:c.userDataDir,headful:l,extensionId:m.extensionId,chromeVersion:m.chromeVersion,startedAt:c.startedAt,deadlineAt:s};this.#w(a),this.#S(g),this.#l=g,this.#c===a&&(this.#c=null),Oe.info("Run launched",{runId:e.runId,chromeVersion:m.chromeVersion,extensionId:m.extensionId,readinessAttempts:m.readinessAttempts,readyAfterMs:m.readyAfterMs,launchDurationMs:Date.now()-r})}catch(m){throw this.#c===a&&(this.#c=null),await this.#y({runId:e.runId,context:u,userDataDir:c.userDataDir,timeoutMs:2e4,trigger:a.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#c===a&&(this.#c=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){this.#u?.jobId===e&&(this.#u=null);let[r,i]=await Promise.allSettled([this.#o.disposeAll(e),this.#f(e,n)]);if(i.status==="rejected")throw i.reason;if(r.status==="rejected")throw r.reason;return i.value}async#f(e,n){let r=this.#m;if(r!==null&&r.runId===e)return Oe.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let i=this.#c;if(i!==null&&i.runId===e)return i.disposeRequested=!0,Oe.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:i.userDataDir,contextPresent:i.context!==null}),this.#y({runId:e,context:i.context,userDataDir:i.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let s=this.#l;return s===null||s.runId!==e?this.#v(e):(this.#l=null,this.#y({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:n,trigger:"dispose"}))}#h(e){return e.headful||this.#t}#w(e){if(e.disposeRequested)throw new hi(e.runId)}#S(e){let n=o(i=>{if(this.#p||this.#l?.runId!==e.runId)return;this.#l=null;let s=this.#y({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#m={runId:e.runId,promise:s},s.catch(c=>{Oe.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:c instanceof Error?c.message:String(c)})}).finally(()=>{this.#m?.promise===s&&(this.#m=null)});let l={runId:e.runId,at:new Date().toISOString(),source:i};Oe.error("Browser instance disappeared without a dispose",{...l}),this.#i(l)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#v(e){let n=this.#d;if(n===null||n.runId!==e)return Oe.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#l===null?null:this.#l.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return Oe.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;let r=Nr(this.#a,{instanceKey:e,result:n.result,killConfirmed:n.killConfirmed});return this.#d={runId:e,result:r,killConfirmed:!0},r}async#y(e){this.#p=!0;try{let n=await _n(this.#a,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#d={runId:e.runId,result:n.result,killConfirmed:n.killConfirmed},n.failure!==null)throw n.failure;return n.result}finally{this.#p=!1}}};function Pl(t){return new Date(Date.now()+t.maxRunDurationSec*1e3).toISOString()}o(Pl,"deadlineOf");import{setTimeout as Ph}from"node:timers/promises";var He=w("supervisor-identity");function gi(t){if(t.initialToken!==void 0)return{source:"env_token",agentToken:t.initialToken};let e=L(t.stateDir);return e===null?null:(Gh(e.serverUrl,t.serverUrl),{source:"state_file",agentToken:e.agentToken,agentId:e.agentId})}o(gi,"selectExistingCredential");async function Fr(t){let{config:e}=t,n=gi(e);if(n?.source==="env_token")return Nh(e,n.agentToken);if(n?.source==="state_file")return He.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 Dh(t,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
26
92
  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(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).
93
+ 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.`)}o(Fr,"resolveAgentIdentity");function Nh(t,e){return t.enrollmentCode!==void 0&&He.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)"),He.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Lh(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}o(Nh,"identityFromEnvToken");function Lh(t){try{return L(t)===null?"absent":"present"}catch(e){return He.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"}}o(Lh,"describeStateFile");async function Dh(t,e){let{config:n,machine:r}=t;He.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let i=new Ut(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),s=await Uh(i,e,t.rng,t.signal);return It(n.stateDir,{agentId:s.agentId,agentToken:s.agentToken,protocolVersion:s.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),He.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:s.agentId,stateDir:n.stateDir}),{agentToken:s.agentToken,agentId:s.agentId,pollWaitSec:s.pollWaitSec,source:"enrollment"}}o(Dh,"enrollThisMachine");var Nl=900*1e3,$h=3e4;async function Uh(t,e,n,r){let i=Date.now()+Nl;for(let s=0;;s+=1)try{return await Mh(t,e,r)}catch(l){if(r?.throwIfAborted(),!(l instanceof A))throw l;let c=Be({attempt:s,error:l,rng:n});if(!c.retry)throw He.warn("Enrollment refused definitively \u2014 not retrying",{attempt:s,reason:c.reason,err:l.message}),l;if(Date.now()+c.delayMs>=i)throw new p(`[progon-agent] Enrollment kept failing for the ${Nl/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${l.message}
94
+ Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:l});He.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:s,retryInMs:c.delayMs,err:l.message}),await Ph(c.delayMs,void 0,{signal:r}).catch(a=>{throw r?.throwIfAborted(),a})}}o(Uh,"enrollWithRetry");async function Mh(t,e,n){if(n===void 0)return t.enroll(e);n.throwIfAborted();let r=new AbortController,i,s=o(()=>{i=setTimeout(()=>r.abort(n.reason),$h)},"onStop");n.addEventListener("abort",s,{once:!0});try{return await t.enroll(e,{signal:r.signal})}finally{n.removeEventListener("abort",s),clearTimeout(i)}}o(Mh,"enrollOnce");function Ll(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).
29
95
  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
- `+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).
96
+ `+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).
31
97
  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
98
  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
- `+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
- 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 ${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)
99
+ `+n)}o(Ll,"assertEnrollmentCodeWasRedeemed");function Gh(t,e){if(!Ue(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.
100
+ 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 move this machine to ${e}: run 'progon-agent enroll <code> --server ${e}' in a terminal, which offers to reset this enrollment (revoking it on ${t}) first. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}o(Gh,"assertServerMatchesEnrollment");import{hostname as Fh}from"node:os";var Dl=["darwin","linux","win32"],$l=["x64","arm64"];function Bh(t){return Dl.includes(t)}o(Bh,"isSupportedPlatform");function jh(t){return $l.includes(t)}o(jh,"isSupportedArch");function Je(){let t=process.platform;if(!Bh(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Dl.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!jh(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${$l.join(", ")} (CONTRACT-la \xA75.1).`);let n=Fh();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:te()}}o(Je,"describeAgentMachine");var Ul=o(()=>{},"noop"),Br=class{static{o(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Ul,Ul),n}};var Ml=w("supervisor-deadline"),Rn=class extends Error{static{o(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 Ke(t){let e=t.work(),n=!1;e.then(()=>{n&&Ml.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},s=>{n&&Ml.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,l)=>{r=setTimeout(()=>{n=!0,l(new Rn(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Ke,"withDeadline");function oe(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);function i(){clearTimeout(r),n()}o(i,"onAbort"),e.addEventListener("abort",i,{once:!0})})}o(oe,"sleep");var Ve=w("fail-reporter"),jr=class{static{o(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){Ve.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&&Ve.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,Ve.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 n=this.#t;n!==null&&n.runId!==e&&(Ve.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#r(){let e=this.#t;if(e!==null)try{let n=await this.#e.failRun(e.runId,e.body);Ve.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 T)throw n;if(n instanceof O)throw Ve.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 A))throw n;let r=Be({attempt:e.attempt,error:n});if(!r.retry){Ve.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},Ve.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 Wr=120,Jt=Wr*1e3,yi=3e4,Kt=3,wi=45*1e3,Si="agent shutdown";var Hr=w("task-launch-reconciler"),Jr=class{static{o(this,"TaskLaunchReconciler")}#e;#t=null;constructor(e){this.#e=e}async apply(e,n){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(n);for(let i of this.#e.runtime.launchIdsWithInstance())r.desired.has(i)||r.closing.has(i)||this.#r(r,i);for(let i of r.desired)r.attempted.has(i)||(r.attempted.add(i),this.#n(r,i))}forgetJob(){this.#t=null}async handleLost(e){Hr.warn("Verification browser lost; its launch lease will end it, no restart or job fail",{...e})}async#n(e,n){let r=null;try{let i=await this.#e.client.issueLaunchSession(e.jobId,n);if(this.#t!==e||!e.desired.has(n))return;try{await Ke({operation:`startLaunchInstance(${e.jobId}, ${n})`,timeoutMs:Jt,work:o(()=>this.#e.runtime.startLaunchInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",error:s}}}catch(i){r={stage:"session",error:i}}finally{await this.#e.detach(async()=>{if(r!==null){if(Hr.error("Verification browser could not start; the first-claim deadline ends its launch",{runId:e.jobId,launchId:n,stage:r.stage,err:r.error instanceof Error?r.error.message:String(r.error)}),r.stage==="launch"&&await this.#i(e,n),r.error instanceof T||r.error instanceof O)throw r.error;return}(this.#t!==e||!e.desired.has(n))&&await this.#i(e,n)})}}#r(e,n){e.closing.add(n),this.#i(e,n).finally(()=>{this.#e.detach(async()=>{e.closing.delete(n)})})}async#i(e,n){try{let r=await this.#e.runtime.disposeLaunchInstance(e.jobId,n);r!==null&&Hr.info("Verification browser disposed",{runId:e.jobId,launchId:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased})}catch(r){Hr.error("Verification browser cleanup failed",{runId:e.jobId,launchId:n,err:r instanceof Error?r.message:String(r)})}}};var Vt=w("run-monitor");function Hh(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:Jh(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 (${Kh(e.tabs)}; ${Vh(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(Hh,"judgeProbe");function Jh(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<=wi}o(Jh,"isJobPulseStanding");function Kh(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(", ")}`}o(Kh,"describeTabs");function Vh(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(wi)}ms)`}o(Vh,"describeJobMarker");var qt=class{static{o(this,"RunMonitor")}#e;#t;#n=null;#r=null;#i=0;#a=!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());Vt.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:yi,probeStrikeLimit:Kt});let n=this.#e.probe;n!==null&&(this.#n=setInterval(()=>{this.#s(n)},yi),this.#n.unref());let r=this.#e;r.identityId===null&&(this.#r=setTimeout(()=>{this.#a||(this.stop(),Vt.error("Run reached its server-authored deadline",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt}),r.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#s(e){if(this.#a)return;let n=await this.#o(e);if(this.#a)return;let r=n.ok?n.detachedIdentity:void 0;if(this.#e.identityId!==null&&r?.agentJobId===this.#e.runId&&r.identityId===this.#e.identityId){this.stop(),this.#e.onIdentityDetached();return}let i=Hh(this.#e.runId,n);if(i.healthy){this.#i>0&&Vt.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#i}),this.#i=0;return}this.#i+=1;let s=`${i.reason}: ${i.detail}`;Vt.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#i,strikeLimit:Kt,reason:i.reason,detail:i.detail}),!(this.#i<Kt)&&(this.stop(),Vt.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Kt,detail:s}),this.#e.onBrowserGone(`${Kt} consecutive liveness probes failed (${s})`))}async#o(e){try{return await e()}catch(n){let r=n instanceof Error?n.message:String(n);return Vt.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,identityId:this.#e.identityId,err:r}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:r}}}};var ve=w("identity-reconciler"),Kr=class{static{o(this,"IdentityReconciler")}#e;#t;#n;#r=null;constructor(e){this.#e=e.runtime,this.#t=e.client,this.#n=e.detach}async apply(e,n,r){let i=this.#r;(i===null||i.jobId!==e)&&(this.forgetJob(),i={jobId:e,deadlineAt:n,desired:new Set,launching:new Set,closing:new Set,monitors:new Map},this.#r=i);let s=new Set(r),l=s.size!==i.desired.size||[...s].some(c=>!i.desired.has(c));i.desired=s,l&&ve.info("Identities of the task job changed",{runId:e,identityIds:[...s],identityIdsWithInstance:this.#e.identityIdsWithInstance()});for(let c of this.#e.identityIdsWithInstance())s.has(c)||i.launching.has(c)||this.#c(i,c,"identity_left_run_block");for(let c of s)i.launching.has(c)||i.closing.has(c)||this.#e.identityIdsWithInstance().includes(c)||this.#i(i,c)}forgetJob(e){let n=this.#r;if(n!==null){if(n.jobId===e){let r=this.#e.identityIdsWithInstance().filter(i=>n.monitors.has(i)||n.launching.has(i));r.length>0&&ve.error("Job deadline reached with identity journal and capture delivery unconfirmed",{event:"runner.identity_delivery_timeout",runId:n.jobId,identityIds:r,deadlineAt:n.deadlineAt})}for(let r of n.monitors.values())r.stop();n.monitors.clear(),this.#r=null}}async handleLost(e){let n=this.#r;if(n===null||n.jobId!==e.jobId){ve.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#m(n,e.identityId),this.#u(n,e.identityId,`the instance disappeared (${e.source})`)}#i(e,n){e.launching.add(n),this.#a(e,n)}async#a(e,n){let r=null;try{let i=await this.#t.issueIdentitySession(e.jobId,n);try{await Ke({operation:`startIdentityInstance(${e.jobId}, ${n})`,timeoutMs:Jt,work:o(()=>this.#e.startIdentityInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",err:s}}}catch(i){r={stage:"session",err:i}}await this.#n(()=>this.#s(e,n,r))}async#s(e,n,r){e.launching.delete(n);let i=this.#r===e;if(r!==null){if(ve.error("The instance of an identity could not be launched \u2014 no fail is reported",{runId:e.jobId,identityId:n,stage:r.stage,jobStillRunning:i,stillInRunBlock:e.desired.has(n),err:r.err instanceof Error?r.err.message:String(r.err)}),r.stage==="session"){if(r.err instanceof T||r.err instanceof O)throw r.err;return}await this.#d(e,n,"launch_failure");return}if(!i){await this.#d(e,n,"job_gone");return}if(!e.desired.has(n)){this.#c(e,n,"identity_left_run_block");return}this.#o(e,n)}#o(e,n){let r=new qt({runId:e.jobId,identityId:n,deadlineAt:e.deadlineAt,probe:o(()=>this.#e.probeIdentityInstance(n),"probe"),onBrowserGone:o(i=>{this.#n(()=>this.#l(e,n,i))},"onBrowserGone"),onIdentityDetached:o(()=>{this.#n(async()=>{this.#r!==e||e.monitors.get(n)!==r||this.#c(e,n,"identity_detached")})},"onIdentityDetached")});e.monitors.set(n,r),r.start(),ve.info("Identity instance is up and monitored",{runId:e.jobId,identityId:n})}async#l(e,n,r){this.#r===e&&(e.monitors.delete(n),ve.error("An identity instance lost its identity \u2014 closing it, no fail is reported",{runId:e.jobId,identityId:n,detail:r}),await this.#d(e,n,"pulse_lost"),this.#u(e,n,r))}#u(e,n,r){if(this.#r===e){if(!e.desired.has(n)){ve.info("A lost identity instance is not relaunched \u2014 the identity left the run block",{runId:e.jobId,identityId:n,cause:r});return}e.launching.has(n)||e.closing.has(n)||(ve.warn("Relaunching the instance of an identity that is still in the run block",{runId:e.jobId,identityId:n,cause:r}),this.#i(e,n))}}#c(e,n,r){e.closing.has(n)||(e.closing.add(n),this.#m(e,n),this.#p(e,n,r))}async#p(e,n,r){await this.#d(e,n,r),await this.#n(async()=>{e.closing.delete(n),this.#u(e,n,"the departed instance finished closing")})}#m(e,n){e.monitors.get(n)?.stop(),e.monitors.delete(n)}async#d(e,n,r){try{let i=await this.#e.disposeIdentityInstance(e.jobId,n);if(i===null)return;ve.info("Identity instance disposed",{runId:e.jobId,identityId:n,trigger:r,disposeOutcome:i.outcome,instanceReleased:i.instanceReleased,durationMs:i.durationMs})}catch(i){ve.error("Identity instance dispose finished with a failed cleanup step",{runId:e.jobId,identityId:n,trigger:r,err:i instanceof Error?i.message:String(i)})}}};var be=w("launch-run");async function Bl(t){let e;try{e=await qh(t)}finally{t.onClaimAnswered()}if(e.kind!=="claimed")return e;let n=Xh(e.payload);return n.command.kind==="swarm"?{kind:"task_claimed",request:n}:Ei(t.runtime,n)}o(Bl,"claimAndLaunch");async function qh(t){try{let e=await t.client.claimRun(t.runId);return be.info("Run claimed",Yh(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof T)throw e;if(e instanceof O)throw be.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof Ct||e instanceof it)return be.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof A))throw e;return be.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}o(qh,"claimRun");function Yh(t){if(!("kind"in t))return{kind:"playback",runId:t.runId,scenarioId:t.scenarioId,projectId:t.projectId,runPurpose:t.runPurpose,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="swarm")return{kind:t.kind,runId:t.runId,workflowId:t.command.workflowId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="scenario_launch")return{kind:t.kind,runId:t.runId,projectId:t.command.projectId,launchId:t.command.launchId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="conversation")return{kind:t.kind,runId:t.runId,conversationId:t.command.conversationId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};let e=t;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}o(Yh,"describeClaim");function Xh(t){return{runId:t.runId,entryUrl:"kind"in t&&t.kind==="conversation"?null:t.entryUrl,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec,extensionSession:t.extensionSession,command:t.command}}o(Xh,"launchRequestOf");async function Ei(t,e){try{await Ke({operation:`startRun(${e.runId})`,timeoutMs:Jt,work:o(()=>t.startRun(e),"work")})}catch(r){return{kind:"failed",body:Qh(e.runId,r)}}let n=t.getActiveInstance();return n===null||n.runId!==e.runId?(be.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}}o(Ei,"launchClaimedRun");var Gl=500,Fl="\u2026";function zh(t){return t.length<=Gl?t:t.slice(0,Gl-Fl.length)+Fl}o(zh,"fitFailMessageToWire");function Qh(t,e){if(e instanceof je){let n=mi(e),r=e.stage==="browser_launch"?Rl(n)??n:n,i=zh(`stage ${e.stage}: ${r}`);if(e.stage==="entry_navigation"){let s=Tl(e);return be.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:s,err:e.message}),{reason:e.failReason,message:i,entryFailure:s}}return be.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:i}}return e instanceof Rn?(be.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:Wr,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Wr}s`}):e instanceof We?(be.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"}):(be.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"})}o(Qh,"describeLaunchFailure");var _e=w("instance-reconciler");function Zh(t){let e=o(()=>{},"markSettled"),n=new Promise(l=>{e=l}),r=o(()=>{},"resolveClaimAnswer"),i=new Promise(l=>{r=l}),s={runId:t,cancelledBy:null,claimAnswered:!1,claimAnswer:i,markClaimAnswered:o(()=>{s.claimAnswered=!0,r()},"markClaimAnswered"),settled:n,markSettled:e};return s}o(Zh,"createPendingLaunch");var ye={kind:"reconciled"},Vr=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#i=new Set;#a=null;#s=null;#o=null;#l=null;#u;#c;#p=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#c=new Jr(e),this.#u=new Kr({runtime:e.runtime,client:e.client,detach:e.detach})}get activeRunId(){return this.#o?.runId??this.#t.getActiveInstance()?.runId??null}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#i=new Set(e.outcomes.map(({runId:n})=>n.replace(/~.*$/,""))),_e.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#i]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId),this.#p=n===null?null:{runId:n.runId,main:n.main===!0,identityIds:eg(n),launchIds:tg(n)};let r=this.#s;if(r!==null)return n!==null&&n.runId===r.runId?(await this.#h(),n.phase!=="queued"?ye:{kind:"claim_issued",runId:n.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}):(r.cancelledBy!==null||await this.#w(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),ye);let i=this.#o;if(i!==null)return n?.runId===i.runId?(await this.#h(),n.phase==="queued"?{kind:"claim_issued",runId:i.runId,claimAnswer:null}:ye):(await this.dispose(i.runId,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),ye);let s=this.#t.getActiveInstance();return n===null?(s!==null&&await this.dispose(s.runId,"desired_state_run_absent"),ye):s!==null?(s.runId===n.runId||await this.dispose(s.runId,"desired_state_runid_mismatch"),ye):this.#n.hasVerdictFor(n.runId)?ye:n.phase==="queued"?this.#l===n.runId?(_e.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.#l=n.runId,this.#m(n.runId),ye):(await this.#v(n.runId,n.phase),ye)}async cancelLaunchAndSettle(e){let n=this.#s;return n===null?null:(_e.warn("Stopping a launch that is still in flight",{runId:n.runId,trigger:e}),n.cancelledBy=e,this.#r(()=>this.dispose(n.runId,e)),await n.settled,n.runId)}async handleIdentityInstanceLost(e){await this.#u.handleLost(e)}async handleLaunchInstanceLost(e){await this.#c.handleLost(e)}async handleInstanceLost(e){_e.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,n){this.stopMonitor(),this.#o?.runId===e&&(this.#o=null),this.#s?.runId===e&&(this.#s.cancelledBy??=n),this.#u.forgetJob(n==="max_duration"?e:void 0),this.#c.forgetJob();try{let r=await this.#t.disposeRun(e);_e.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){_e.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#a?.stop(),this.#a=null}#m(e,n){let r=Zh(e);this.#s=r,n!==void 0&&r.markClaimAnswered();let i=n===void 0?()=>Bl({client:this.#e,runtime:this.#t,runId:e,onClaimAnswered:r.markClaimAnswered}):()=>Ei(this.#t,n);this.#d(r,i)}async#d(e,n){try{let r=await this.#g(n);await this.#r(()=>this.#f(e,r))}finally{e.markSettled()}}async#g(e){try{return{kind:"outcome",outcome:await e()}}catch(n){return{kind:"thrown",error:n}}}async#f(e,n){if(this.#s===e&&(this.#s=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"task_claimed":{if(e.cancelledBy!==null)return;let i=this.#t.prepareTaskJob(r.request);this.#o={runId:e.runId,deadlineAt:i,mainRequest:r.request},this.#S(e.runId,i,!1),await this.#h();return}case"launched":if(e.cancelledBy!==null){_e.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.#S(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){_e.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#h(){let e=this.#o,n=this.#p;if(!(e===null||n?.runId!==e.runId)&&(await this.#u.apply(e.runId,e.deadlineAt,n.identityIds),await this.#c.apply(e.runId,n.launchIds),n.main&&e.mainRequest!==null&&this.#s===null)){let r=e.mainRequest;e.mainRequest=null,this.#m(e.runId,r)}}async#w(e,n){_e.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)}#S(e,n,r=!0){this.stopMonitor(),this.#a=new qt({runId:e,identityId:null,deadlineAt:n,probe:r?()=>this.#t.probePlaybackSession():null,onBrowserGone:o(i=>{this.#r(()=>this.#y(e,"browser_gone",i,"browser_gone"))},"onBrowserGone"),onDeadline:o(()=>{this.#r(()=>this.#y(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#v(e,n){let r=this.#i.has(e),i=r?"browser_gone":"launch_error";_e.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:i}),await this.#n.report({runId:e,body:{reason:i,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,n,r,i){await this.dispose(e,i),await this.#n.report({runId:e,body:{reason:n,message:r}})}};function eg(t){return t.identities===void 0?[]:t.identities.map(e=>e.identityId)}o(eg,"identityIdsOf");function tg(t){return t.launches===void 0?[]:t.launches.map(e=>e.launchId)}o(tg,"launchIdsOf");function vi(t,e){return t!==78?t:e==="linux"?78:0}o(vi,"serviceExitCode");var jl="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>.",Wl={revoked:{exitCode:78,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+jl},reenroll_required:{exitCode:78,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. "+jl},credential_unusable:{exitCode:78,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."},upgrade_required:{exitCode:78,level:"error",message:"progon-agent stopped: the server no longer accepts this version of the agent. The line before names the minimum. Update with 'progon-agent update' and start again. Nothing was wiped: this machine stays enrolled."},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"}},Hl={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",upgrade_required:"shutdown",fatal:"shutdown",stopped:"shutdown"};var H=w("token-rotation"),Jl=1440*60*1e3,Yt=class{static{o(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 n=this.#r;if(n!==null)return n;let r=this.#s(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 H.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 O)return"reenroll_required";if(n instanceof T)throw n;if(n instanceof A)return H.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.#r;e!==null&&await e.then(()=>{},()=>{})}async#s(e){if(this.#n==="one_shot")return{kind:"unsupported_one_shot"};if(this.#n==="env_token")return this.#i||(this.#i=!0,H.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 n=this.#g();if(n.kind!=="identity")return this.#f(n);let r=n.identity,i=await this.#o(e);return i.kind!=="status"?i.outcome:i.value.rotationDue?await this.#u(r,i.value.tokenRotatedAt,e):this.#l(r,i.value.tokenRotatedAt)}async#o(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof O)return H.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 T)throw n;if(n instanceof A)return H.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}}#l(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#d({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#a=!0,H.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#u(e,n,r){let i;try{i=(await this.#e.rotateToken()).agentToken}catch(l){if(l instanceof T)throw l;if(l instanceof O)return await this.#c(r);if(l instanceof A)return H.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:l.operation,err:l.message}),await this.#p(n);throw l}this.#d({...e,agentToken:i,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(i);let s=await this.#m();return s.kind==="reenroll_required"?s:(s.kind==="observed"&&this.#d({...e,agentToken:i,tokenRotatedAt:s.tokenRotatedAt},"rotation marker of the new agent token"),H.info("Agent token rotated"),{kind:"rotated"})}async#c(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#a=!0,H.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 n=await this.#o(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(H.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,H.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#m(){let e=await this.#o(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(H.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"})}#d(e,n){try{return It(this.#t,e),!0}catch(r){return H.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}}#g(){let e;try{e=L(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#f(e){return e.kind==="unreadable"?(H.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"}):(H.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 B=w("run-supervisor"),qr=o(()=>Promise.resolve(),"noVerdictOwed"),Yr=class{static{o(this,"RunSupervisor")}#e;#t;#n;#r=new Br;#i;#a;#s;#o=null;#l=0;#u=0;#c=!1;#p=new AbortController;#m=null;#d=!1;#g=!1;#f;#h=null;#w=null;constructor(e){this.#e=e.client,this.#i=e.stateDir,this.#a=e.pollWaitSec,this.#s=e.capabilitiesDeclared,this.#f=e.tokenRotation,this.#t=new jr(e.client),this.#p.signal.addEventListener("abort",()=>this.#$(),{once:!0});let n=e.createRuntime({onInstanceLost:o(r=>{this.#b(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:o(r=>{this.#b(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost"),onLaunchInstanceLost:o(r=>{this.#b(()=>this.#n.handleLaunchInstanceLost(r))},"onLaunchInstanceLost")});this.#n=new Vr({client:e.client,runtime:n,reporter:this.#t,detach:o(r=>this.#b(r),"detach")})}get activeRunId(){return this.#n.activeRunId}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#L();if(e!==null)return e;for(this.#O(),this.#s||await this.#v();!this.#c;){let n=this.#m;if(n!==null)return await this.#R(n),"revoked";if(this.#d)return await this.#T(),"reenroll_required";if(this.#g)return await this.#C(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#U();this.#l=0;let i=await this.#r.run(()=>this.#n.reconcile(r));await this.#M(i)}catch(r){if(r instanceof T)return await this.#R(r),"revoked";if(r instanceof O&&await this.#A(r))return await this.#T(),"reenroll_required";if(this.#c)break;if(this.#_())continue;let i=await this.#j(r);if(i!==null)return i==="credential_unusable"?await this.#C():i==="upgrade_required"?await this.#F():await this.#B(),i}}return this.#S()}async#S(){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#v(){try{await this.#e.declareCapabilities({signal:this.#p.signal})}catch(e){if(await this.#N(e),this.#_())return;if(!(e instanceof A))throw e;B.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 B.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#y(e);return this.#w=r,r}async#y(e){B.info("Shutting down",{cause:e}),await this.#E(e==="fatal"?"fatal":"stopped",n=>this.#I(n))}async#E(e,n){this.#c=!0,this.#o?.abort(),this.#p.abort();let r=Hl[e],i=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 n({activeRunId:s,launchingRunId:i})}),await this.#f.settle()}async#I(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#x(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:Si}}));return}if(r!==null){await this.#x(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:Si}}));return}await this.#x(()=>this.#t.retryPending())}async#L(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof T)return await this.#R(e),"revoked";throw e}return await this.#T(),"reenroll_required"}#O(){if(this.#c||this.#p.signal.aborted)return;let e=setTimeout(()=>{this.#h=null,this.#D().finally(()=>{this.#O()})},Jl);e.unref(),this.#h=e}async#D(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return;this.#d=!0,this.#o?.abort()}catch(e){await this.#P(e)}}#$(){this.#h!==null&&(clearTimeout(this.#h),this.#h=null)}async#A(e){B.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#f.diagnoseSuperseded(this.#p.signal)==="reenroll_required"}catch(n){if(n instanceof T)return this.#m=n,!1;throw n}}async#U(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#a,signal:e.signal})}finally{this.#o=null}}async#M(e){if(e.kind==="reconciled"){this.#u=0;return}await this.#G(e.runId,e.claimAnswer)}async#G(e,n){let r=ge(this.#u);B.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#u,waitMs:r,claimOnTheWire:n!==null}),this.#u+=1;let i=new AbortController;if(this.#o=i,this.#p.signal.aborted||this.#_()){this.#o=null;return}n?.then(()=>i.abort());try{await oe(r,i.signal)}finally{this.#o=null}}async#k(){await this.#f.settle(),rr(this.#i)}async#R(e){B.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#E("revoked",qr),await this.#k()}async#C(){B.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.#E("credential_unusable",qr)}async#F(){await this.#E("upgrade_required",qr)}async#B(){await this.#E("fatal",e=>this.#I(e))}async#T(){B.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#E("reenroll_required",qr),await this.#k()}async#j(e){if(!(e instanceof A))throw e;let n=this.#W(e);return n.kind==="exit"?n.exit:(this.#l+=1,await oe(n.delayMs,this.#p.signal),null)}#W(e){if(e instanceof ee)return B.error("The server refuses this version of the agent \u2014 disposing the browser and stopping",{operation:e.operation,err:e.message}),{kind:"exit",exit:"upgrade_required"};if(e instanceof O){if(!this.#f.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=ge(this.#l);return B.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.#l,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Be({attempt:this.#l,error:e});return n.retry?(B.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#l,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(B.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"})}#b(e){return this.#r.run(e).catch(n=>this.#P(n))}async#P(e){await this.#N(e)||B.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#N(e){if(e instanceof T)return this.#m=e,this.#o?.abort(),!0;if(!(e instanceof O))return!1;try{await this.#A(e)?this.#d=!0:this.#f.canDiagnoseFromTheWire||(this.#g=!0)}catch(n){return B.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.#o?.abort(),!0}#_(){return this.#m!==null||this.#d||this.#g}async#x(e){try{await e()}catch(n){if(n instanceof O){B.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 T){await this.#k(),B.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 Kl=w("supervisor-boot");async function Vl(t){t?.throwIfAborted();let e=Me();Kl.info("Config loaded",{serverUrlOrigin:new URL(e.serverUrl).origin,serverUrlSource:e.serverUrlSource,stateDir:e.stateDir,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox});let n=Je(),r=await Fr({config:e,machine:n,signal:t});t?.throwIfAborted(),Kl.info("Agent identity resolved",{source:r.source,agentId:r.agentId,hostname:n.hostname,platform:n.platform,arch:n.arch,agentVersion:n.agentVersion});let i=Tr({overridePath:e.extensionDistOverride,stateDir:e.stateDir,agentId:r.agentId});await Ar({disableBrowserSandbox:e.disableBrowserSandbox,signal:t}),t?.throwIfAborted();let s=new Ge({serverUrl:e.serverUrl,agentToken:r.agentToken}),l=new Yt({client:s,stateDir:e.stateDir,identitySource:r.source});return bi({client:s,stateDir:e.stateDir,pollWaitSec:r.pollWaitSec,tokenRotation:l,extensionDist:i,browserEnv:e,capabilitiesDeclared:!1})}o(Vl,"bootRunSupervisor");function bi(t){let{client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,extensionDist:s,browserEnv:l}=t;return new Yr({client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,capabilitiesDeclared:t.capabilitiesDeclared,createRuntime:o(({onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d})=>new Gr({stateDir:n,extensionDist:s,headfulOverride:l.headfulOverride,allowInsecureHttps:l.allowInsecureHttps,disableBrowserSandbox:l.disableBrowserSandbox,onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d}),"createRuntime")})}o(bi,"wireRunSupervisor");import{z as Tn}from"zod";var ng="scenario_launches.scenarios_not_launchable",rg=Tn.object({items:Tn.array(Tn.object({scenarioId:Tn.string(),notStartedReason:Tn.string()}))});function ql(t){if(t.errorCode!==ng)return[];let e=rg.safeParse(t.params);return e.success?e.data.items.map(n=>` NOT STARTED scenario ${n.scenarioId} - ${n.notStartedReason}`):["Progon did not say which scenarios cannot start."]}o(ql,"refusedScenarioLines");import{stripVTControlCharacters as cg}from"node:util";import{appendFileSync as og,statSync as ig}from"node:fs";var sg=1024*1024,Yl=`
101
+ ### Progon
102
+
103
+ `;function Ql(t,e){let n;try{n=ig(t).size}catch(i){return{kind:"failed",reason:zl(i)}}let r=ag(e,sg-n);if(r===null)return{kind:"no_room",fileBytes:n};try{og(t,r,"utf8")}catch(i){return{kind:"failed",reason:zl(i)}}return{kind:"written"}}o(Ql,"appendStepSummary");function ag(t,e){let n=t.result.map(Xr).join(""),r=t.reportUrl===null?"":`
104
+ Report: <${t.reportUrl}>
105
+ `,i=pt(Yl)+pt(n)+pt(r),s=[];for(let d of t.details){let u=pt(Xr(d));if(i+u>e)break;i+=u,s.push(d)}let l=lg(t.details.slice(s.length));for(;l>0&&i+pt(Xl(l))>e;){let d=s.pop();if(d===void 0)break;i-=pt(Xr(d)),Zl(d)&&(l+=1)}let c=l>0?Xl(l):"",a=Yl+n+s.map(Xr).join("")+c+r;return pt(a)<=e?a:null}o(ag,"fitStepSummary");function Xr(t){return` ${t}
106
+ `}o(Xr,"codeLine");function Xl(t){return`
107
+ ${t} more line(s) are in the job log.
108
+ `}o(Xl,"omissionOf");function Zl(t){return t.trim()!==""}o(Zl,"isText");function lg(t){return t.filter(Zl).length}o(lg,"countText");function pt(t){return Buffer.byteLength(t,"utf8")}o(pt,"byteLength");function zl(t){return t instanceof Error?t.message:String(t)}o(zl,"describeError");var dg=/[\t\n\v\f\r\u0085\u2028\u2029]+/gu,ug=/[\p{Cc}\p{Bidi_Control}]/gu,pg=/^(\s*):(?=:)/u,mg=/##(?=[a-z]*\[)/giu;function fg(t){return cg(t).replace(dg," ").replace(ug,"")}o(fg,"toSingleLine");function hg(t){return t.replace(pg,"$1: ").replace(mg,"# #")}o(hg,"defuseCiCommands");function F(t,e){return{result:t,details:[],reportUrl:e}}o(F,"finalOf");var zr=class{constructor(e,n){this.stepSummaryPath=n;e!==null&&this.secrets.add(e)}static{o(this,"CiOutput")}secrets=new Set;lastLineAt=Date.now();addSecret(e){this.secrets.add(e)}line(e){this.write("stdout",this.render(e))}silentForMs(){return Date.now()-this.lastLineAt}errorLine(e){this.write("stderr",this.render(e))}final(e,n){let r={result:e.result.map(s=>this.render(s)),details:e.details.map(s=>this.render(s)),reportUrl:e.reportUrl===null?null:this.render(e.reportUrl)},i=o(s=>this.write(n,s),"write");i("");for(let s of[...r.result,...r.details])i(s);r.reportUrl!==null&&(i(""),i(`Report: ${r.reportUrl}`)),this.stepSummaryPath!==null&&this.summarize(this.stepSummaryPath,r)}flush(){return new Promise(e=>process.stdout.write("",()=>e()))}write(e,n){if(e==="stderr"){process.stderr.write(`${n}
109
+ `);return}process.stdout.write(`${n}
110
+ `),this.lastLineAt=Date.now()}summarize(e,n){let r=Ql(e,n);r.kind==="no_room"?this.line(`The step summary has no room for this result: the file of the step already holds ${r.fileBytes} bytes of its 1 MiB. Nothing was written to it.`):r.kind==="failed"&&this.line(`Could not write the step summary: ${r.reason}`)}render(e){return hg(this.mask(fg(e)))}mask(e){let n=C(e);for(let r of this.secrets)n=n.split(r).join("[REDACTED]");return n}};function ki(t){return t.status===Ka||t.status===wr}o(ki,"isItemOver");function xn(t){return t.status===wr?` NOT STARTED ${t.scenarioName}${_i(t.notStartedReason)}`:t.outcome===Zo?` PASSED ${t.scenarioName}`:t.outcome===ei?` FAILED ${t.scenarioName}${_i(gg(t))}`:` ${t.outcome??"no outcome reported"} ${t.scenarioName}${_i(t.failureReason)}`}o(xn,"formatItemLine");function _i(t){return t===null||t===""?"":` - ${t}`}o(_i,"detail");function gg(t){let e=[];return t.failedStep!==null&&e.push(`step ${t.failedStep.number} "${t.failedStep.name}"`),t.failureReason!==null&&e.push(t.failureReason),e.join(": ")}o(gg,"describeFailure");function ec(t){let{counts:e,waitingForRunner:n,current:r,status:i}=t;if(n!==null)return`Waiting for the runner: ${n.ahead>0?`${n.ahead} job(s) ahead of this launch`:"next in line"}. ${e.total} scenario(s) in the launch.`;let s=e.finished+e.notStarted,l=r===null?"":`, running: ${r}`;return`Launch ${i}: ${s} of ${e.total} scenario(s) done${l}.`}o(ec,"formatStatusLine");function tc(t){let e={passed:[],failed:[],notStarted:[],other:[]};for(let n of t)n.status===wr?e.notStarted.push(n):n.outcome===Zo?e.passed.push(n):n.outcome===ei?e.failed.push(n):e.other.push(n);return e}o(tc,"groupItems");function nc(t,e){let n=tc(e),r=t.counts.total;return{result:[yg(t.verdict,r,n.failed.length),`Scenarios: ${ic(n)} (of ${r}).`],details:oc(n),reportUrl:t.webUrl}}o(nc,"formatReport");function rc(t,e,n){let{total:r,finished:i,notStarted:s,running:l,queued:c}=e.counts,a=tc(n.filter(ki)),d=[`Latest counts from Progon: ${i} finished, ${s} did not start, ${l} running, ${c} queued (of ${r}).`,`Partial, as this job saw them end: ${ic(a)}.`,...oc(a)];return{result:[t],details:d,reportUrl:e.webUrl}}o(rc,"formatPartialReport");function oc({failed:t,notStarted:e,other:n}){let r=[];return t.length>0&&r.push("","Failed scenarios:",...t.map(xn)),e.length>0&&r.push("","Did not start:",...e.map(xn)),n.length>0&&r.push("","Other outcomes:",...n.map(xn)),r}o(oc,"detailsOf");function ic({passed:t,failed:e,notStarted:n,other:r}){let i=[`${t.length} passed`,`${e.length} failed`];return n.length>0&&i.push(`${n.length} did not start`),r.length>0&&i.push(`${r.length} other`),i.join(", ")}o(ic,"tallyOf");function yg(t,e,n){return t===gr?`Result: PASSED - all ${e} scenario(s) passed.`:t===yr?`Result: FAILED - ${n} of ${e} scenario(s) failed.`:t===Ja?"Result: NO RESULT - the launch ended without a full result.":t===null?"Result: NO RESULT - Progon reported no verdict for this launch.":`Result: NO RESULT - this CLI does not know the verdict "${t}".`}o(yg,"resultLine");var Qr=class{static{o(this,"CiStopControl")}#e=null;#t=new AbortController;#n;#r;constructor(e){if(e===null){this.#n=null,this.#r=null;return}this.#n=performance.now()+e,this.#r=setTimeout(()=>this.#i(),e)}get cause(){return this.#e}get signal(){return this.#t.signal}cancel(){this.#e="cancelled",this.#t.abort()}secondsLeft(){return this.#n===null?null:Math.floor((this.#n-performance.now())/1e3)}launchCreated(){this.close(),this.#e==="timeout"&&(this.#e=null,this.#t=new AbortController)}close(){this.#r!==null&&clearTimeout(this.#r)}#i(){this.#e===null&&(this.#e="timeout",this.#t.abort())}};function mt(t){return t==="timeout"?"--timeout expired.":"The job was cancelled."}o(mt,"describeStopCause");var Y=class extends Error{constructor(n,r){super("ci run ended");this.exitCode=n;this.final=r}static{o(this,"CiRunEnded")}},Xt=class extends Error{static{o(this,"CiReadFailed")}};function sc(t,e,n,r){return lc(t,n,r,i=>t.api.createLaunch(e,i))}o(sc,"createLaunchWithRetry");function ac(t,e){return lc(t,e,vg,n=>t.api.createRunner(n))}o(ac,"createRunnerWithRetry");async function lc(t,e,n,r){let{output:i,timings:s}=t,l=Date.now();for(let c=0;;c+=1){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was confirmed. No result.`],null));try{return await wg(t,e,r)}catch(a){if(a instanceof lt)throw new Y(U,F([`Progon gave an unreadable answer about ${n.noun}: ${a.message}`,"No result."],null));if(a instanceof he&&!Ri(a)){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} Progon refused ${n.noun}: ${Ae(a)}.`,"No launch was created. No result."],null));return Sg(n,a)}if(!cc(a))throw a;let d=dc(a,c),u=Date.now()-l+d<s.createBudgetMs;if(e.cause===null&&u){i.line(`Progon did not take ${n.noun} (${Ae(a)}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}let m=[`Progon did not take ${n.noun}: ${Ae(a)}. No result.`];throw n.mayExistAfterLostAnswer&&a instanceof Gt&&m.push("It may exist in Progon; this job could not confirm it."),new Y(U,F(m,null))}}}o(lc,"callBeforeLaunchWithRetry");async function wg(t,e,n){let r=new AbortController,i,s=o(()=>{i=setTimeout(()=>r.abort(),t.timings.signalStopTimeoutMs)},"startGrace");e.cause!==null?s():e.signal.addEventListener("abort",s,{once:!0});try{return await n(r.signal)}finally{clearTimeout(i),e.signal.removeEventListener("abort",s)}}o(wg,"callWithStopGrace");async function In(t,e,n,r){let{output:i,timings:s}=t,l=null,c=o(a=>{throw new Xt(`Could not read ${n}: ${Ae(a)}. No result.`)},"endAfterLaunch");for(let a=0;;a+=1)try{return await r(e)}catch(d){if(e.aborted)return null;if(d instanceof lt&&c(d),d instanceof he&&!Ri(d)&&c(d),!cc(d))throw d;let u=Date.now();l===null&&(l=u);let m=dc(d,a);u-l+m>=s.readBudgetMs&&c(d),i.line(`Progon does not answer about ${n} (${Ae(d)}); repeating in ${Math.ceil(m/1e3)}s.`),await oe(m,e)}}o(In,"readWithRetry");function cc(t){return t instanceof Gt||t instanceof he&&Ri(t)}o(cc,"isTemporaryFailure");function Ri(t){return t.status===429||t.status>=500}o(Ri,"isRepeatableRefusal");function dc(t,e){return t instanceof he&&t.status===429&&t.retryAfterMs!==null?t.retryAfterMs:ge(e)}o(dc,"retryDelayMs");function Sg(t,e){let n=[`Progon refused ${t.noun}: ${Ae(e)}.`],r=e.errorCode===null?void 0:t.hints.get(e.errorCode);throw r!==void 0&&n.push(r),n.push("No launch was created."),new Y(vn(e.status,e.errorCode),{result:n,details:ql(e),reportUrl:null})}o(Sg,"refuseBeforeLaunch");var uc=[["auth.invalid_token","Check the PROGON_CI_KEY secret of this pipeline."],["auth.token_expired","The CI key has expired: create a new one and update PROGON_CI_KEY."],["auth.token_revoked","The CI key was revoked: create a new one and update PROGON_CI_KEY."],["auth.wrong_auth_class","PROGON_CI_KEY must be a CI key of the project."]],Eg=new Map([...uc,["agents.offline","Start the CI runner and run the job again."],["agents.queue_full","The queue of the CI runner is full. Run the job again later."],["agents.capability_missing","The CI runner build is too old. Update progon-agent on it."]]),pc=new Map(uc),mc={noun:"the launch",hints:Eg,mayExistAfterLostAnswer:!0},fc={noun:"the launch",hints:pc,mayExistAfterLostAnswer:!0},vg={noun:"the runner of this job",hints:pc,mayExistAfterLostAnswer:!1};function Ae(t){return t instanceof he?t.errorCode===null?`${t.message} (HTTP ${t.status})`:`${t.message} (${t.errorCode})`:t.message}o(Ae,"describeFailure");var Rg="progon-agent-job-",Tg=new Set(["ENOENT","ENOTDIR","EACCES","EPERM","EROFS"]),eo=class{static{o(this,"CiJobRunner")}#e;#t;#n;#r=Ag();#i=null;#a=null;#s=!1;constructor(e){this.#e=e.deps,this.#t=e.serverUrl,this.#n=e.browserEnv}async start(e,n){await this.#o(e,n),this.#m("Registering the runner of this job in Progon.",n);let{runnerId:r,enrollmentCode:i}=await ac(this.#e,e);this.#e.output.addSecret(i);let s=new Ut({serverUrl:this.#t,machine:Je()}),l=await this.#l(e,"enroll the runner of this job",()=>s.enroll(i,{signal:e.signal}));this.#e.output.addSecret(l.agentToken);let c=new Ge({serverUrl:this.#t,agentToken:l.agentToken});await this.#l(e,"accept what this runner can run",()=>c.declareCapabilities({signal:e.signal}));let a=Tr({overridePath:this.#n.extensionDistOverride,stateDir:this.#r,agentId:l.agentId});return this.#d(e),this.#u(bi({client:c,stateDir:this.#r,pollWaitSec:l.pollWaitSec,tokenRotation:new Yt({client:c,stateDir:this.#r,identitySource:"one_shot"}),extensionDist:a,browserEnv:this.#n,capabilitiesDeclared:!0})),r}async dispose(){this.#s=!0;let{output:e}=this.#e,n=this.#i;if(n!==null)try{await n.shutdown("job_finished"),await this.#a}catch(r){e.line(`The browser of this job may still be running: ${Zr(r)}`)}try{_g(this.#r,{recursive:!0,force:!0})}catch(r){e.line(`Could not remove ${this.#r}: ${Zr(r)}`)}}async#o(e,n){this.#m("Preparing the browser inside this job.",n),this.#n.disableBrowserSandbox&&this.#e.output.line("PROGON_AGENT_DISABLE_BROWSER_SANDBOX is set: no browser sandbox.");try{await Ar({disableBrowserSandbox:this.#n.disableBrowserSandbox,signal:e.signal})}catch(r){throw this.#d(e),r instanceof Q?new Y(U,F([`The browser could not be prepared: ${r.message}`,"No launch was created."],null)):r}this.#d(e)}async#l(e,n,r){let{output:i,timings:s}=this.#e,l=Date.now();for(let c=0;;c+=1){this.#d(e);try{return await r()}catch(a){if(!(a instanceof A))throw a;a instanceof Z&&this.#d(e);let d=xg(a,c);if(d!==null&&e.cause===null&&Date.now()-l+d<s.createBudgetMs){i.line(`Progon did not ${n} (${a.message}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}throw new Y(e.cause===null?Ig(a):U,F([`Progon did not ${n}: ${a.message}`,"No launch was created."],null))}}}#u(e){this.#i=e,this.#a=e.run().then(n=>this.#c(n),n=>this.#p(n))}#c(e){this.#s||e==="stopped"||e==="revoked"||this.#e.output.line(`The runner of this job stopped (${e}). Waiting for Progon to end the launch.`)}async#p(e){let{output:n}=this.#e;if(n.errorLine(`progon-agent: the runner of this job failed: ${Zr(e)}`),!this.#s)try{await this.#i?.shutdown("fatal")}catch(r){n.line(`The browser of this job may still be running: ${Zr(r)}`)}}#m(e,n){n(e),this.#e.output.line(e)}#d(e){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was created. No result.`],null))}};function xg(t,e){if(t instanceof x&&t.status===429)return t.retryAfterMs??ge(e);let n=Be({attempt:e,error:t});return n.retry?n.delayMs:null}o(xg,"gatewayRetryDelayMs");function Ig(t){return t instanceof x?vn(t.status,t.errorCode):t instanceof T?vn(403,"agents.revoked"):U}o(Ig,"exitCodeOfGatewayFailure");function Og(){let t=kg();try{return bg(hc(t,Rg))}catch(e){let n=e instanceof Error?e.code:void 0;throw e instanceof Error&&n!==void 0&&Tg.has(n)?new p(`The temporary folder ${t} cannot be used: ${e.message}. Set TMPDIR to a writable folder in this pipeline.`,{cause:e}):e}}o(Og,"createJobStateDir");function Ag(){let t=Og();return process.env.XDG_CONFIG_HOME=hc(t,"xdg-config"),t}o(Ag,"prepareJobStateDir");function Zr(t){return t instanceof Error?t.message:String(t)}o(Zr,"describeError");var to=class{static{o(this,"CiItemTracker")}api;output;known=new Map;printed=new Set;firstUnprinted=0;readRevision=null;morePages=!1;constructor(e){this.api=e.api,this.output=e.output}async syncPage(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&!this.morePages)return;let r=this.firstUnprinted,i=await this.api.listItems(e.id,r,n);this.morePages=this.recordPage(r,i),this.readRevision=e.revision}async drain(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&this.firstUnprinted>=e.counts.total)return;let r=this.firstUnprinted;for(;;){let i=await this.api.listItems(e.id,r,n);if(this.recordPage(r,i),r+=i.items.length,i.items.length===0||r>=i.total)break}this.readRevision=e.revision,this.morePages=!1}items(){return[...this.known.entries()].sort(([e],[n])=>e-n).map(([,e])=>e)}recordPage(e,n){let r=this.firstUnprinted;for(n.items.forEach((i,s)=>{let l=e+s;this.known.set(l,i),ki(i)&&!this.printed.has(l)&&(this.printed.add(l),this.output.line(xn(i)))});this.printed.has(this.firstUnprinted);)this.firstUnprinted+=1;return this.firstUnprinted>r&&e+n.items.length<n.total}};var gc=new AbortController().signal;async function yc(t,e,n,r,i){let s="Creating the launch in Progon.",l=setInterval(()=>{t.output.silentForMs()>=t.timings.statusQuietMs&&t.output.line(s)},t.timings.statusCheckMs),c=o(a=>{s=a},"setStatus");try{let a=i===null?e.runnerId:await i.start(n,c);c("Creating the launch in Progon.");let d=Pg(e,r,a,Cg(n));return await Ng(t,d,n,c,i!==null)}catch(a){if(a instanceof Y)return{exitCode:a.exitCode,final:a.final};throw a}finally{clearInterval(l)}}o(yc,"runCiLaunch");function Cg(t){let e=t.secondsLeft();if(e!==null&&e<1)throw new Y(U,F(["--timeout left less than one second for the launch. No launch was created. No result."],null));return e}o(Cg,"timeoutSecOf");function Pg(t,e,n,r){let i=t.selection.kind==="spec"?{specNodeId:t.selection.specNodeId}:{scenarioIds:t.selection.scenarioIds};return{idempotencyKey:e.idempotencyKey,...i,...t.environmentId===null?{}:{environmentId:t.environmentId},...t.entryUrl===null?{}:{entryUrl:t.entryUrl},...n===null?{}:{runnerId:n},...r===null?{}:{timeoutSec:r},...e.ci===null?{}:{ci:e.ci}}}o(Pg,"createBody");async function Ng(t,e,n,r,i){let{output:s,timings:l}=t,a=await sc(t,e,n,i?fc:mc);n.launchCreated(),s.line(`Launch ${a.id} created. Report: ${a.webUrl}`);let d=new to(t),u=!1;try{for(;;){if(n.cause!==null)return await Lg(t,a,d,i,r);if(a.status===hr){let S=a;if(await In(t,n.signal,"the scenarios of the launch",I=>d.drain(S,I))===null)continue;return wc(a,d)}let m=ec(a);r(m),a.waitingForRunner!==null!==u&&(u=a.waitingForRunner!==null,s.line(m));let g=a;if(await In(t,n.signal,"the scenarios of the launch",S=>d.syncPage(g,S)),await oe(l.pollIntervalMs,n.signal),n.cause!==null)continue;let E=await In(t,n.signal,"the state of the launch",S=>t.api.getLaunch(g.id,S));E!==null&&(a=E)}}catch(m){if(m instanceof Xt)return zt(m.message,a,d);throw m}}o(Ng,"driveLaunch");function wc(t,e){return{exitCode:Ya(t.verdict),final:nc(t,e.items())}}o(wc,"reportAndExit");async function Lg(t,e,n,r,i){let{api:s,output:l,timings:c}=t;l.line(`${mt("cancelled")} Stopping launch ${e.id}.`);let a;try{a=await s.stopLaunch(e.id,c.signalStopTimeoutMs)}catch(d){if(d instanceof he&&d.errorCode==="scenario_launches.not_running")return $g(t,e,n);if(d instanceof Fe)return zt(`Could not stop the launch: ${Ae(d)}. No result.`,e,n);throw d}return r?Dg(t,a,n,i):zt("The launch was stopped; no verdict was waited for. No result.",a,n)}o(Lg,"stopLaunchOnce");async function Dg(t,e,n,r){let{api:i,output:s,timings:l}=t,c=e;if(c.status!==hr){let a=`Launch ${c.id} is stopping; the browser of this job stays up until it ends.`;s.line(a),r(a)}try{for(;c.status!==hr;){await oe(l.pollIntervalMs,gc);let{id:a}=c,d=await In(t,gc,"the state of the launch",u=>i.getLaunch(a,u));if(d===null)throw new Error("a read that nothing interrupts returned the interrupted answer");c=d}}catch(a){if(a instanceof Xt)return zt(a.message,c,n);throw a}return zt("The launch was stopped and has ended. No result.",c,n)}o(Dg,"awaitStoppedLaunch");async function $g(t,e,n){try{let r=await t.api.getLaunch(e.id,void 0);return await n.drain(r,void 0),wc(r,n)}catch(r){if(r instanceof Fe)return zt(`Could not read the ended launch: ${Ae(r)}. No result.`,e,n);throw r}}o($g,"reportEndedLaunch");function zt(t,e,n){return{exitCode:U,final:rc(t,e,n.items())}}o(zt,"noResult");var Mg=3e4,Gg={pollIntervalMs:1e4,statusCheckMs:1e4,statusQuietMs:4e4,createBudgetMs:12e4,readBudgetMs:3e5,signalStopTimeoutMs:5e3},Fg=25e3;async function vc(t){zn();let e=D(process.env,"PROGON_CI_KEY"),n=new zr(e,D(process.env,"GITHUB_STEP_SUMMARY")),r={current:null},i=o(s=>{Ec(n,s),Jg(r.current)},"onDefect");process.on("uncaughtException",i),process.on("unhandledRejection",i);try{let s=await Bg(t,e,n,r);return await n.flush(),s}catch(s){return s instanceof p?(n.final(F([s.message],null),"stdout"),await n.flush(),ct):(Ec(n,s),await n.flush(),U)}}o(vc,"runCiCommand");async function Bg(t,e,n,r){let i=qa(t);if(i.kind==="help")return Sc(l=>n.line(l)),ti;if(i.kind==="refused")return Sc(l=>n.errorLine(l)),n.final(F([`progon-agent: ${i.reason}`],null),"stderr"),ct;if(e===null)return n.final(F(["PROGON_CI_KEY is not set. Add the CI key of the project to the secrets of this pipeline."],null),"stdout"),ct;if(/[^\x21-\x7e]/.test(e))return n.final(F(["PROGON_CI_KEY contains whitespace or an invalid character. Paste the key again, whole."],null),"stdout"),ct;Qn(process.env),tr(process.env);let s=i.options.inJob?jg():null;return Hg(i.options,e,Wg(s),s,n,r)}o(Bg,"runParsedCommand");function jg(){let t=gn();return t.extensionDistOverride!==void 0&&dr(t.extensionDistOverride),t}o(jg,"loadJobBrowserEnv");function Wg(t){let e=D(process.env,"PROGON_SERVER_URL");if(e===null){let n=Tt();if(n!==null)return n;throw new p("PROGON_SERVER_URL is not set and this package has no built-in address of Progon. Set PROGON_SERVER_URL in this pipeline.")}if(Re(e),t!==null&&t.extensionDistOverride===void 0){let n=Tt();if(n!==null&&!Ue(e,n))throw new p(`--in-job: PROGON_SERVER_URL is ${e}, but the extension in this package works only with ${n}. Remove PROGON_SERVER_URL, or install the progon-agent package of ${e}.`)}return e}o(Wg,"resolveCiServerUrl");async function Hg(t,e,n,r,i,s){let l=new Qr(t.timeoutMs),c=o(()=>l.cancel(),"onSignal");for(let g of sr)process.on(g,c);let d={api:new Sr({serverUrl:n,key:e,requestTimeoutMs:Mg}),output:i,timings:Gg},u={idempotencyKey:Ug(),ci:Xa(process.env)},m=null;try{m=r===null?null:new eo({deps:d,serverUrl:n,browserEnv:r}),s.current=m;let g=await yc(d,t,l,u,m);return i.final(g.final,"stdout"),g.exitCode}finally{l.close(),m!==null&&await m.dispose(),s.current=null;for(let g of sr)process.removeListener(g,c)}}o(Hg,"runWithControls");async function Jg(t){if(t!==null){let e,n=new Promise(r=>{e=setTimeout(r,Fg)});await Promise.race([t.dispose(),n]),clearTimeout(e)}process.exit(U)}o(Jg,"exitAfterDefect");function Sc(t){for(let e of Va.split(`
111
+ `))t(e)}o(Sc,"writeUsage");function Ec(t,e){t.final(F([`progon-agent: internal error: ${Kg(e)}`],null),"stderr")}o(Ec,"writeDefect");function Kg(t){return t instanceof Error?t.stack??t.message:String(t)}o(Kg,"describeDefect");import{resolve as Vg}from"node:path";var bc=` progon-agent --version Print this package's version. No network.
112
+ progon-agent status [--state-dir <path>] What is installed, enrolled and running for the
113
+ state directory. No network; changes nothing.
114
+ progon-agent stop [--state-dir <path>] Stop the agent running for the state directory
115
+ (graceful: the browser is closed, the run reported).
116
+ progon-agent reset [--state-dir <path>] Disconnect this machine: stop the agent, revoke its
117
+ registration on the server, delete its credential
118
+ and browser profiles. Package and browser stay.
119
+ progon-agent doctor [--state-dir <path>] Check this machine: configuration, proxy and
120
+ certificates, what start connects to, Chromium
121
+ (installed if missing) and its sandbox.
122
+ progon-agent update [--version <x.y.z>] Update the package with npm (default: the latest
123
+ [--state-dir <path>] release). Stops the agent of the state directory
124
+ first; the enrollment is kept.
125
+ progon-agent uninstall [--state-dir <path>] Stop, revoke and delete everything progon-agent
126
+ created \u2014 the standard state directory,
127
+ PROGON_RUNNER_STATE_DIR and each --state-dir
128
+ (repeatable) \u2014 then its Chromium and the package.
129
+ progon-agent service <verb> [--state-dir <path>]
130
+ Run the agent of the state directory as an OS
131
+ service: Linux \u2014 systemd user service, started at
132
+ boot; macOS \u2014 LaunchAgent, at login; Windows \u2014
133
+ Task Scheduler, at login. The registration IS the
134
+ autostart. Verbs:
135
+ enable register and start it (a runner started in a terminal hands over to it);
136
+ the settings come from this environment (proxy, CA, server \u2014 never the token)
137
+ disable stop it and remove the registration; the enrollment stays
138
+ start start it (enable first if it is not registered)
139
+ stop stop it; it starts again at the next boot/login
140
+ restart stop, then start
141
+ status what the OS holds for it and what runs
142
+
143
+ 'start' also takes --state-dir <path>.`,qg=new Set(["service","status","stop","reset","doctor","update","uninstall"]),Yg=/^\d+\.\d+\.\d+$/;function _c(t){return t==="--version"||qg.has(t)}o(_c,"isLifecycleVerb");function On(t,e){let n=t[e+1];return n===void 0||n===""?{reason:"'--state-dir' needs a directory"}:n.startsWith("-")?{reason:`'--state-dir' needs a directory, got the option '${n}' (a directory named so: ./${n})`}:{path:Vg(n)}}o(On,"readStateDirFlag");var Xg=new Set(["enable","disable","start","stop","restart","status"]);function zg(t){return t!==void 0&&Xg.has(t)}o(zg,"isServiceVerb");function kc(t,e){if(t==="--version")return e.length>0?le("'--version' takes no arguments"):{kind:"invocation",invocation:{command:"version"}};if(t==="service"){let[s,...l]=e;if(!zg(s))return le(s===void 0?"'service' needs a verb: enable, disable, start, stop, restart or status":`unknown verb '${s}' for 'service' (enable, disable, start, stop, restart, status)`);if(l.length===0)return{kind:"invocation",invocation:{command:t,verb:s,stateDir:void 0}};if(l[0]!=="--state-dir")return le(`unknown option '${String(l[0])}' for 'service ${s}'`);let c=On(l,0);return"reason"in c?le(c.reason):l.length>2?le("unexpected arguments after '--state-dir'"):{kind:"invocation",invocation:{command:t,verb:s,stateDir:c.path}}}let n,r=[],i=null;for(let s=0;s<e.length;s+=1){let l=e[s];if(l==="--state-dir"){let c=On(e,s);if("reason"in c)return le(c.reason);if(t==="uninstall")r.push(c.path);else{if(n!==void 0)return le("'--state-dir' is given twice");n=c.path}s+=1;continue}if(l==="--version"&&t==="update"){let c=e[s+1];if(c===void 0)return le("'--version' needs a version, such as 1.6.0");if(!Yg.test(c))return le(`'--version' takes one release as x.y.z, got '${c}'`);if(i!==null)return le("'--version' is given twice");i=c,s+=1;continue}return le(`unknown option '${String(l)}' for '${t}'`)}switch(t){case"status":case"stop":case"reset":case"doctor":return{kind:"invocation",invocation:{command:t,stateDir:n}};case"update":return{kind:"invocation",invocation:{command:t,stateDir:n,version:i}};case"uninstall":return{kind:"invocation",invocation:{command:t,stateDirs:r}};default:return le(`unknown command '${t}'`)}}o(kc,"parseLifecycleArgs");function le(t){return{kind:"refusal",reason:t}}o(le,"refusal");import{accessSync as vw,existsSync as bw,constants as _w,statSync as kw}from"node:fs";import{createHash as gy}from"node:crypto";import{statSync as yy}from"node:fs";import{connect as Gc}from"node:net";import{resolve as wy}from"node:path";import{z as M}from"zod";import{createHmac as Qg,randomBytes as Ti,timingSafeEqual as Zg}from"node:crypto";import{chmodSync as ey,linkSync as ty,readFileSync as ny,statSync as ry,unlinkSync as oy,writeFileSync as iy}from"node:fs";import{join as no}from"node:path";var ft="control.key",sy=32,ay=/^[0-9a-f]{64}$/,ly=16,cy=/^control\.key\.tmp-\d+-[0-9a-f]{8}$/;function Rc(t){return t===ft||cy.test(t)}o(Rc,"isControlKeyEntry");function oo(){return Ti(ly).toString("hex")}o(oo,"newNonce");function Tc(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Tc,"errnoOf");function io(t){if(process.platform==="win32")return;let e=ry(t),n=process.getuid?.();if(n===void 0)throw new Error("[control-auth] process.getuid is unavailable on a POSIX platform");if(e.uid!==n||(e.mode&18)!==0)throw new p(`The state directory ${t} is not private to this user (owner uid ${e.uid}, mode ${(e.mode&511).toString(8)}), so its control channel cannot be trusted. Use a directory of your own: chmod 700 it, or pick another --state-dir.`)}o(io,"assertPrivateStateDir");function xc(t){let e=ro(t);if(e!==null)return e;let n=Ti(sy),r=no(t,`${ft}.tmp-${process.pid}-${Ti(4).toString("hex")}`);iy(r,n.toString("hex"),{mode:384,flag:"wx"});try{ey(r,384),ty(r,no(t,ft))}catch(s){if(Tc(s)!=="EEXIST")throw s}finally{oy(r)}let i=ro(t);if(i===null)throw new Error(`[control-auth] ${no(t,ft)} vanished after creation`);return i}o(xc,"ensureControlKey");function ro(t){let e=no(t,ft),n;try{n=ny(e,"utf8")}catch(r){if(Tc(r)==="ENOENT")return null;throw r}if(!ay.test(n))throw new p(`${e} is not a control key written by progon-agent. Stop any progon-agent of this directory, delete the file and start again.`);return Buffer.from(n,"hex")}o(ro,"readControlKey");function Ic(t,e){return Qg("sha256",t).update(e.join(`
144
+ `)).digest("hex")}o(Ic,"hmac");function so(t,e,n,r){return Ic(t,["progon-agent control request",e,n,r])}o(so,"requestProof");function ao(t,e,n){return Ic(t,["progon-agent control answer",e,n])}o(ao,"answerProof");function lo(t,e){let n=Buffer.from(t,"hex"),r=Buffer.from(e,"hex");return n.length===r.length&&n.length>0&&Zg(n,r)}o(lo,"proofMatches");import{randomBytes as dy}from"node:crypto";import{readdirSync as Ac,readlinkSync as uy,renameSync as py,symlinkSync as my,unlinkSync as Cc}from"node:fs";import{join as ht}from"node:path";var Pc="control.sock",xi=/^control-\d+-[0-9a-f]{8}\.sock$/,Nc=/^control-\d+-[0-9a-f]{8}\.sock\.next$/,Lc=/^control\.sock\.head-\d+-[0-9a-f]{8}\.tmp$/,fy=/^control-\d+-[0-9a-f]{8}\.sock\.pending$/,hy=w("control-socket-chain");function Dc(t){return t===Pc||xi.test(t)||Nc.test(t)||Lc.test(t)||fy.test(t)}o(Dc,"isControlSocketEntry");function co(t){return ht(t,Pc)}o(co,"controlLinkPath");function Ii(t,e){return ht(t,`${e}.next`)}o(Ii,"successorLinkPath");function $c(t,e){let n=ht(t,`control.sock.head-${process.pid}-${dy(4).toString("hex")}.tmp`);my(e,n);try{py(n,co(t))}catch(r){throw Cc(n),r}}o($c,"checkpointControlSocket");async function Uc(t,e,n){let r=[];for(let i of Ac(t,{withFileTypes:!0}))i.isSocket()&&xi.test(i.name)&&r.push(i.name);for(let[i,s]of r.entries()){if(!e()){hy.warn("Control socket cleanup reached the acquisition budget; a later start will continue",{stateDir:t,remainingSockets:r.length-i});return}await n(s)&&qe(ht(t,s))}}o(Uc,"reapControlSockets");function Mc(t,e){for(let n of Ac(t,{withFileTypes:!0}))if(n.isSymbolicLink())if(Nc.test(n.name)){let r=n.name.slice(0,-5);if(r===e)continue;qe(ht(t,n.name)),qe(ht(t,r))}else Lc.test(n.name)&&qe(ht(t,n.name))}o(Mc,"pruneControlHistory");function qe(t){try{Cc(t)}catch(e){if(typeof e!="object"||e===null||e.code!=="ENOENT")throw e}}o(qe,"unlinkControlEntry");function An(t){let e=Oc(co(t));if(e===null)return null;let n=new Set;for(;;){if(!xi.test(e)||n.has(e))throw new Error(`[control-channel] Invalid ownership link in ${t}: ${e}`);n.add(e);let r=Oc(Ii(t,e));if(r===null)return e;e=r}}o(An,"resolveControlSocketName");function Oc(t){try{return uy(t)}catch(e){if((typeof e=="object"&&e!==null?e.code:null)==="ENOENT")return null;throw e}}o(Oc,"readLink");var Ye=5e3,Sy=64*1024,Pn=2,Fc=/^[0-9a-f]{32}$/,Bc=/^[0-9a-f]{64}$/,Ey=M.object({protocol:M.literal(Pn),pid:M.number().int().positive(),version:M.string().min(1),startedAt:M.string().min(1),stateDir:M.string().min(1),phase:M.enum(["starting","running","stopping"]),activeRunId:M.string().min(1).nullable(),service:M.boolean()}),vy=M.object({protocol:M.literal(Pn),challenge:M.string().regex(Fc)}),jc=M.object({type:M.enum(["status","stop"]),nonce:M.string().regex(Fc),proof:M.string().regex(Bc)}),by=M.object({proof:M.string().regex(Bc),status:Ey});function Oi(t){return process.platform==="win32"?{kind:"pipe",name:`\\\\?\\pipe\\progon-agent-${gy("sha256").update(wy(t).toLowerCase()).digest("hex").slice(0,32)}`}:{kind:"unix",dir:t}}o(Oi,"controlAddress");function Wc(t){return Dc(t)||Rc(t)}o(Wc,"isControlChannelEntry");function po(t,e){let n=process.cwd();process.chdir(t);try{return e()}finally{process.chdir(n)}}o(po,"inDir");function Cn(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Cn,"errnoOf");async function $(t,e){return Jc(t,"status",e)}o($,"queryOwner");async function Hc(t){return Jc(t,"stop")}o(Hc,"requestOwnerStop");async function Jc(t,e,n){if(!_y(t))return{kind:"none"};io(t);let r=Oi(t),i;try{let s=r.kind==="unix"?n??An(t):r.name;if(s===null)return{kind:"none"};i=r.kind==="unix"?po(r.dir,()=>Gc(s)):Gc(s)}catch(s){if(Cn(s)==="ENOENT"||Cn(s)==="ENOTDIR")return{kind:"none"};throw s}return new Promise((s,l)=>{let c=!1,a="",d=!1,u=null,m=o(S=>{d||(d=!0,clearTimeout(g),i.destroy(),S instanceof Error?l(S):s(S))},"settle"),g=setTimeout(()=>{m(c?{kind:"silent",reason:`it accepted the connection but did not answer within ${Ye/1e3} s`}:new Error(`[control-channel] Connecting to the control channel of ${t} did not finish within ${Ye/1e3} s.`))},Ye),E=o(S=>{if(u===null){let I=uo(S,vy);if(!I.ok){m({kind:"silent",reason:`its greeting is not one this version reads (${I.reason})`});return}let N;try{N=ro(t)}catch(Et){m(Et instanceof Error?Et:new Error(String(Et)));return}if(N===null){m({kind:"foreign",reason:"the directory has no control key, so the process listening on its channel cannot be its daemon"});return}let z=oo();u={key:N,challenge:I.value.challenge,nonce:z};let ue=so(N,I.value.challenge,z,e);i.write(`${JSON.stringify({type:e,nonce:z,proof:ue})}
145
+ `);return}let b=uo(S,by);if(!b.ok){m({kind:"silent",reason:`its answer is not one this version reads (${b.reason})`});return}if(!lo(ao(u.key,u.challenge,u.nonce),b.value.proof)){m({kind:"foreign",reason:"it could not prove the key of this directory \u2014 it is not this directory's daemon"});return}m({kind:"live",status:b.value.status})},"onLine");i.setEncoding("utf8"),i.on("connect",()=>{c=!0}),i.on("data",S=>{if(a+=S,a.length>Sy){m({kind:"silent",reason:"its answer exceeded the size of a status"});return}for(;;){let b=a.indexOf(`
146
+ `);if(b===-1||d)return;let I=a.slice(0,b);a=a.slice(b+1),E(I)}}),i.on("end",()=>{m(u===null?{kind:"silent",reason:"it closed the connection without a greeting"}:{kind:"foreign",reason:"it closed the connection without an answer \u2014 it did not accept the key of this directory"})}),i.on("error",S=>{let b=Cn(S);if(!c&&(b==="ENOENT"||b==="ECONNREFUSED")){m({kind:"none"});return}if(c){m({kind:"silent",reason:`the connection failed: ${S.message}`});return}m(S)})})}o(Jc,"askOwner");function _y(t){try{return yy(t).isDirectory()}catch(e){if(Cn(e)==="ENOENT"||Cn(e)==="ENOTDIR")return!1;throw e}}o(_y,"directoryExists");function uo(t,e){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:"not JSON"}}let r=e.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:r.error.message}}o(uo,"parseLine");function h(t){process.stdout.write(`${C(t)}
147
+ `)}o(h,"say");function Nn(t){return t.source==="env"?` --state-dir "${t.path}"`:""}o(Nn,"stateDirOption");function j(t){let e=t.phase==="starting"?"starting up":t.phase==="stopping"?"stopping":t.activeRunId===null?"idle":`running ${t.activeRunId}`;return`pid ${t.pid}, version ${t.version}, since ${t.startedAt}, ${e}`}o(j,"describeOwner");function mo(t){try{let e=new URL(t);return e.username===""&&e.password===""?t:(e.username="***",e.password="",e.toString())}catch{return"[unparseable value]"}}o(mo,"maskUrlCredentials");import{spawn as ky}from"node:child_process";import{existsSync as Vc,readFileSync as qc}from"node:fs";import{basename as Ai,dirname as gt,join as Ln}from"node:path";import{fileURLToPath as Ry}from"node:url";var we="progon-agent";function Qt(){let t=Se(gt(Ry(import.meta.url))),e=gt(t);if(Ai(t)!==we||Ai(e)!=="node_modules")return{kind:"not_global",packageRoot:t};let n;if(process.platform==="win32"){if(n=gt(e),!Ty(n))return{kind:"not_global",packageRoot:t}}else{let r=gt(e);if(Ai(r)!=="lib")return{kind:"not_global",packageRoot:t};n=gt(r)}return{kind:"npm_global",packageRoot:t,prefix:n,npmCli:xy(n)}}o(Qt,"locateInstallation");function Ty(t){try{return qc(Ln(t,`${we}.cmd`),"utf8").toLowerCase().includes(`"%dp0%\\node_modules\\${we}\\dist\\supervisor\\cli.js"`)}catch(e){if(P(e))return!1;throw e}}o(Ty,"hasGlobalWindowsShim");function Kc(t){return process.platform==="win32"?Ln(t,"node_modules","npm","bin","npm-cli.js"):Ln(t,"lib","node_modules","npm","bin","npm-cli.js")}o(Kc,"npmCliUnder");function xy(t){let e=gt(process.execPath),n=process.platform==="win32"?e:gt(e);for(let r of[Kc(n),Kc(t)])if(Vc(r))return r;return null}o(xy,"findNpmCli");async function fo(t,e){return Dn(t,e)}o(fo,"runNpm");async function Dn(t,e){return new Promise((n,r)=>{let i=ky(process.execPath,[t,...e],{stdio:"inherit",env:process.env});i.once("error",r),i.once("exit",s=>n(s))})}o(Dn,"runNode");function Ci(t){let e=Ln(t,"package.json"),n;try{n=JSON.parse(qc(e,"utf8"))}catch(a){return{kind:"damaged",reason:a instanceof Error?a.message:String(a)}}let r=typeof n=="object"&&n!==null?n:{},i=r.version,s=r.bin,l=typeof s=="object"&&s!==null?s[we]:void 0;if(typeof i!="string"||typeof l!="string")return{kind:"damaged",reason:`${e} has no version or no '${we}' bin`};let c=Ln(t,l);return Vc(c)?{kind:"installed",version:i,cliPath:c}:{kind:"damaged",reason:`${c} is missing`}}o(Ci,"readInstalledPackage");import{execFile as Iy}from"node:child_process";var $n=3e4;function X(t,e,n={}){let r=n.timeoutMs??$n;return new Promise(i=>{Iy(t,[...e],{timeout:r,windowsHide:!0,encoding:"utf8"},(s,l,c)=>{if(s===null){i({exitCode:0,stdout:l,stderr:c});return}let a=s.code;if(typeof a=="number"){i({exitCode:a,stdout:l,stderr:c});return}i({exitCode:null,stdout:l,stderr:c,failure:a==="ENOENT"?`'${t}' is not installed or not on PATH`:s.killed===!0?`'${t}' did not finish within ${r/1e3} s`:s.message})})})}o(X,"runOsCommand");function Xe(t,e,n){let r=[t,...e].join(" ");if(n.exitCode===null)return`${r}: ${n.failure}`;let i=(n.stderr.trim()||n.stdout.trim()).split(`
148
+ `).slice(0,3).join(" / ");return`${r} exited ${n.exitCode}${i===""?"":`: ${i}`}`}o(Xe,"describeOsFailure");async function ie(t,e,n={}){let r=await X(t,e,n);if(r.exitCode!==0)throw new _(Xe(t,e,r));return r}o(ie,"runOsCommandOrThrow");var _=class extends Error{static{o(this,"ServiceManagerError")}name="ServiceManagerError"};function ke(t,e,n){try{return n()}catch(r){throw Oy(r)?new _(`Could not ${t} ${e}: ${r.message}`,{cause:r}):r}}o(ke,"registrationFileStep");function Oy(t){if(!(t instanceof Error))return!1;let{code:e,syscall:n}=t;return typeof e=="string"&&typeof n=="string"}o(Oy,"isFileSystemError");import{mkdirSync as Gy,readFileSync as Fy,readdirSync as By,renameSync as jy,unlinkSync as Wy,writeFileSync as Hy}from"node:fs";import{homedir as Jy}from"node:os";import{setTimeout as Ky}from"node:timers/promises";import{join as go}from"node:path";import{z as Ni}from"zod";import{setTimeout as Ay}from"node:timers/promises";var Ce=9e4,Cy=250;async function Yc(t,e){let n=await Hc(t);if(n.kind==="none")return{kind:"not_running"};if(n.kind==="silent")throw new p(`A process owns ${t} but did not say which one (${n.reason}), so it cannot be stopped from here. Stop it where it runs (Ctrl-C in its terminal) and run the command again.`);if(n.kind==="foreign")throw new p(`The control channel of ${t} is held by a process that is not its progon-agent (${n.reason}). Nothing was stopped. Find that process \u2014 on Windows, another user's process can hold the channel name \u2014 and end it, then run the command again.`);let{status:r}=n;e(r);let i=Date.now()+Ce;for(;Date.now()<i;){if((await $(t)).kind==="none")return{kind:"stopped",status:r};await Ay(Cy)}throw new p(`progon-agent (pid ${r.pid}) is still shutting down after ${Ce/1e3} s. Its log says what it is waiting for; run the command again once it has exited.`)}o(Yc,"stopStateDirOwner");import{createHash as Py}from"node:crypto";import{realpathSync as Ny}from"node:fs";import{homedir as Ly}from"node:os";import{dirname as Dy,join as Xc,resolve as Pi}from"node:path";import{fileURLToPath as $y}from"node:url";var Uy=Xc("dist","supervisor","cli.js"),ze="service.log",ho="service-error.log";function zc(t){return Zc()?.(t)===!0}o(zc,"isServiceFileEntry");function Qc(){return Zc()!==null}o(Qc,"serviceWritesFiles");function Zc(){switch(process.platform){case"darwin":return t=>t===ze;case"win32":return t=>t===ze||t===ho||/^progon-agent(-[0-9a-f]{8})?\.task-[0-9a-f]{16}\.xml$/.test(t);default:return null}}o(Zc,"serviceFileMatcher");var Un="progon-agent";function se(t){return{stateDir:t,name:Zt(t)}}o(se,"serviceTargetFor");function Zt(t){let e=Pi(t);if(My(e))return Un;let n=process.platform==="win32"?e.toLowerCase():e;return`${Un}-${Py("sha256").update(n).digest("hex").slice(0,8)}`}o(Zt,"serviceNameFor");function My(t){let e;try{e=Pi(hn(process.platform,process.env,Ly()))}catch(n){if(n instanceof p)return!1;throw n}return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}o(My,"isStandardStateDir");function en(){let t=Se(Dy($y(import.meta.url))),e=Xc(t,Uy);try{return Ny(e)}catch(n){throw new p(`This installation has no ${e} to register as a service (${n instanceof Error?n.message:String(n)}). Build or reinstall progon-agent.`)}}o(en,"packageCliPath");function ed(t){let e=Pi(t);if(/[\r\n\0]/.test(e))throw new p("The state directory path contains a line break, so it cannot be written into a service registration. Use another --state-dir.");let n=[];for(let r of sa){let i=process.env[r];if(i!==void 0){if(/[\r\n\0]/.test(i))throw new p(`${r} contains a line break, so it cannot be written into the service registration. Fix the variable and run the command again.`);n.push([r,i])}}return{stateDir:e,name:Zt(e),program:[process.execPath,en(),"start","--state-dir",e,"--service"],environment:n}}o(ed,"buildServiceDefinition");function td(t){let e=t.indexOf("--state-dir"),n=e===-1?void 0:t[e+1];return n===void 0||!t.includes("--service")?null:n}o(td,"stateDirOfProgram");var sd="io.progon.agent",Vy=/^io\.progon\.agent(-[0-9a-f]{8})?\.plist$/;function yo(t){return`${sd}${t.slice(Un.length)}`}o(yo,"labelOf");function qy(t){return`${Un}${t.slice(sd.length)}`}o(qy,"nameOfLabel");function Di(){return go(Jy(),"Library","LaunchAgents")}o(Di,"agentsDir");function Mn(t){return go(Di(),`${yo(t)}.plist`)}o(Mn,"plistPath");function rn(){let t=process.getuid?.();if(t===void 0)throw new Error("[launchd-service] process.getuid is unavailable");return`gui/${t}`}o(rn,"domain");function Qe(t){return`${rn()}/${yo(t)}`}o(Qe,"target");function tn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}o(tn,"xml");function nd(t){let e=tn(go(t.stateDir,ze)),n=t.program.map(i=>` <string>${tn(i)}</string>`).join(`
149
+ `),r=t.environment.map(([i,s])=>` <key>${tn(i)}</key>
150
+ <string>${tn(s)}</string>`).join(`
151
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
152
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
153
+ <plist version="1.0">
154
+ <dict>
155
+ <key>Label</key>
156
+ <string>${tn(yo(t.name))}</string>
157
+ <key>ProgramArguments</key>
158
+ <array>
159
+ ${n}
160
+ </array>
161
+ <key>EnvironmentVariables</key>
162
+ <dict>
163
+ ${r}
164
+ </dict>
165
+ <key>WorkingDirectory</key>
166
+ <string>${tn(t.stateDir)}</string>
167
+ <key>RunAtLoad</key>
168
+ <true/>
169
+ <key>KeepAlive</key>
170
+ <dict>
171
+ <key>SuccessfulExit</key>
172
+ <false/>
173
+ </dict>
174
+ <key>ThrottleInterval</key>
175
+ <integer>10</integer>
176
+ <key>ExitTimeOut</key>
177
+ <integer>90</integer>
178
+ <key>ProcessType</key>
179
+ <string>Interactive</string>
180
+ <key>StandardOutPath</key>
181
+ <string>${e}</string>
182
+ <key>StandardErrorPath</key>
183
+ <string>${e}</string>
184
+ </dict>
185
+ </plist>
186
+ `}o(nd,"renderPlist");function rd(t){return ke("read the LaunchAgent",t,()=>{try{return Fy(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(rd,"readFileOrNull");async function nn(t){let e=await X("launchctl",["print",Qe(t)]);if(e.exitCode===null)throw new _(Xe("launchctl",["print",Qe(t)],e));return e.exitCode===0}o(nn,"isLoaded");var od=1e4,Yy=100;async function Li(t){await ie("launchctl",["bootout",Qe(t)],{timeoutMs:Ce+$n});let e=Date.now()+od;for(;await nn(t);){if(Date.now()>e)throw new _(`launchd still has ${Qe(t)} loaded ${od/1e3} s after bootout; run the command again.`);await Ky(Yy)}}o(Li,"bootout");async function id(t){let e=await X("launchctl",["print-disabled",rn()]);if(e.exitCode!==0)return null;let n=yo(t).replace(/\./g,"\\."),r=new RegExp(`^\\s*"${n}" => (\\w+)$`,"m").exec(e.stdout)?.[1];return r!=="disabled"&&r!=="true"}o(id,"isEnabled");var Xy=Ni.object({ProgramArguments:Ni.array(Ni.string())});async function zy(t){let e=await X("plutil",["-convert","json","-o","-",t]);if(e.exitCode!==0)return null;try{let n=Xy.safeParse(JSON.parse(e.stdout));return n.success?n.data.ProgramArguments:null}catch{return null}}o(zy,"readProgram");var ad={description:"a LaunchAgent (launchd) \u2014 starts when you log in",async isCurrent(t){return rd(Mn(t.name))===nd(t)&&await nn(t.name)&&await id(t.name)===!0},async install(t){let e=Mn(t.name);return await nn(t.name)&&await Li(t.name),ke("write the LaunchAgent",e,()=>{Gy(Di(),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Hy(n,nd(t),{mode:384}),jy(n,e)}),await ie("launchctl",["enable",Qe(t.name)]),await ie("launchctl",["bootstrap",rn(),e]),[]},async start(t){await nn(t)?await ie("launchctl",["kickstart",Qe(t)]):(await ie("launchctl",["enable",Qe(t)]),await ie("launchctl",["bootstrap",rn(),Mn(t)]))},async stop(t){await nn(t)&&await Li(t)},async remove(t){let e=Mn(t),n=await nn(t);return n&&await Li(t),ke("delete the LaunchAgent",e,()=>{try{return Wy(e),!0}catch(i){if(i.code!=="ENOENT")throw i;return!1}})||n?"removed":"absent"},async read(t){let e=Mn(t);if(rd(e)===null)return{kind:"absent"};let n=[],r=null,i=await X("launchctl",["print",Qe(t)]);if(i.exitCode===0){let s=/^\s*state = (.+)$/m.exec(i.stdout)?.[1],l=/^\s*pid = (\d+)$/m.exec(i.stdout)?.[1],c=/^\s*last exit code = (.+)$/m.exec(i.stdout)?.[1];r=l!==void 0||c!==void 0&&c!=="0",n.push(`loaded in ${rn()}`+(s===void 0?"":`, ${s}`)+(l===void 0?"":`, pid ${l}`)+(c===void 0?"":`, last exit: ${c}`))}else i.exitCode===null?n.push(`launchd could not be asked: ${i.failure}`):(r=!1,n.push(`not loaded in ${rn()}`));return{kind:"registered",location:e,program:await zy(e),facts:n,active:r,autostart:o(()=>id(t),"autostart")}},async registeredNames(){let t;try{t=By(Di())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>Vy.test(e)).map(e=>qy(e.slice(0,-6)))},logHint(t){return go(t.stateDir,ze)}};import{mkdirSync as Qy,readdirSync as Zy,readFileSync as ew,renameSync as tw,unlinkSync as nw,writeFileSync as rw}from"node:fs";import{homedir as ow,userInfo as ld}from"node:os";import{isAbsolute as iw,join as $i}from"node:path";import{z as cd}from"zod";var sw=/^progon-agent(-[0-9a-f]{8})?\.service$/,Ui="# progon-agent program: ";function Mi(){let t=process.env.XDG_CONFIG_HOME,e=t!==void 0&&iw(t)?t:$i(ow(),".config");return $i(e,"systemd","user")}o(Mi,"unitDir");function Pe(t){return`${t}.service`}o(Pe,"unitName");function Gn(t){return $i(Mi(),Pe(t))}o(Gn,"unitPath");function dd(t,e){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%");return e&&(n=n.replace(/\$/g,"$$$$")),`"${n}"`}o(dd,"quote");function ud(t){let e=t.program.map(r=>dd(r,!0)).join(" "),n=t.environment.map(([r,i])=>`Environment=${dd(`${r}=${i}`,!1)}
187
+ `).join("");return`${Ui}${JSON.stringify(t.program)}
188
+ [Unit]
189
+ Description=Progon agent (${t.stateDir.replace(/%/g,"%%")})
190
+
191
+ [Service]
192
+ Type=simple
193
+ ExecStart=${e}
194
+ ${n}WorkingDirectory=${t.stateDir.replace(/%/g,"%%")}
195
+ Restart=on-failure
196
+ RestartSec=10
197
+ RestartPreventExitStatus=${78}
198
+ TimeoutStopSec=${Ce/1e3}
199
+ KillMode=mixed
200
+
201
+ [Install]
202
+ WantedBy=default.target
203
+ `}o(ud,"renderUnit");function wo(t){return ke("read the systemd unit",t,()=>{try{return ew(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(wo,"readFileOrNull");var aw=cd.array(cd.string());function lw(t){let e=t.split(`
204
+ `,1)[0];if(e===void 0||!e.startsWith(Ui))return null;try{let n=aw.safeParse(JSON.parse(e.slice(Ui.length)));return n.success?n.data:null}catch{return null}}o(lw,"programOf");async function on(t,e=!1){await ie("systemctl",["--user",...t],e?{timeoutMs:Ce+$n}:{})}o(on,"systemctl");async function cw(t){return(await X("systemctl",["--user","is-enabled",Pe(t)])).exitCode===0}o(cw,"isEnabled");var pd={description:"a systemd user service \u2014 starts at boot (with lingering) or at login",async isCurrent(t){return wo(Gn(t.name))===ud(t)&&await cw(t.name)},async install(t){let e=[],n=Gn(t.name);ke("write the systemd unit",n,()=>{Qy(Mi(),{recursive:!0});let i=`${n}.tmp-${process.pid}`;rw(i,ud(t),{mode:384}),tw(i,n)}),await on(["daemon-reload"]),await on(["enable",Pe(t.name)]);let r=await X("loginctl",["enable-linger"]);return r.exitCode!==0&&e.push(`Lingering could not be turned on (${Xe("loginctl",["enable-linger"],r)}), so the service starts when you log in, not at boot. To start it at boot: sudo loginctl enable-linger ${ld().username}`),e},async start(t){await on(["start",Pe(t)])},async stop(t){wo(Gn(t))!==null&&await on(["stop",Pe(t)],!0)},async remove(t){let e=Gn(t);return wo(e)===null?"absent":(await on(["disable","--now",Pe(t)],!0),ke("delete the systemd unit",e,()=>nw(e)),await on(["daemon-reload"]),await X("systemctl",["--user","reset-failed",Pe(t)]),"removed")},async read(t){let e=Gn(t),n=wo(e);if(n===null)return{kind:"absent"};let r=[],i=null,s=null,l=await X("systemctl",["--user","show",Pe(t),"--property=UnitFileState,ActiveState,SubState,MainPID,ExecMainStatus,Result"]);if(l.exitCode===0){let a=new Map(l.stdout.split(`
205
+ `).filter(m=>m.includes("=")).map(m=>[m.slice(0,m.indexOf("=")),m.slice(m.indexOf("=")+1)])),d=a.get("ActiveState");d!==void 0&&(i=!["inactive","failed"].includes(d));let u=a.get("UnitFileState");u==="enabled"?s=!0:(u==="disabled"||u==="masked")&&(s=!1),r.push(`${a.get("UnitFileState")??"unknown"} (unit file), ${a.get("ActiveState")??"unknown"}/${a.get("SubState")??"unknown"}, last exit status ${a.get("ExecMainStatus")??"unknown"}`)}else r.push(`systemd could not be asked: ${Xe("systemctl",["--user","show"],l)}`);let c=await X("loginctl",["show-user",ld().username,"--property=Linger"]);return c.exitCode===0&&r.push(c.stdout.trim()==="Linger=yes"?"lingering on: starts at boot":"lingering off: starts at login"),{kind:"registered",location:e,program:lw(n),facts:r,active:i,autostart:o(()=>Promise.resolve(s),"autostart")}},async registeredNames(){let t;try{t=Zy(Mi())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>sw.test(e)).map(e=>e.slice(0,-8))},logHint(t){return`journalctl --user -u ${Pe(t.name)}`}};import{randomBytes as dw}from"node:crypto";import{unlinkSync as uw,writeFileSync as pw}from"node:fs";import{join as Fn}from"node:path";import{z as J}from"zod";var mw="^progon-agent(-[0-9a-f]{8})?$",Bi="progon-agent program: ";function fw(t){if(t!==""&&!/[\s"]/.test(t))return t;let e='"',n=0;for(let r of t){if(r==="\\"){n+=1;continue}r==='"'?e+=`${"\\".repeat(n*2+1)}"`:e+=`${"\\".repeat(n)}${r}`,n=0}return`${e}${"\\".repeat(n*2)}"`}o(fw,"quoteWindowsArg");function hw(t){let[e,...n]=t.program;if(e===void 0)throw new Error("[task-scheduler-service] the program has no executable");return["$ErrorActionPreference = 'Stop'",...t.environment.map(([i,s])=>`$env:${i} = ${me(s)}`),`$p = Start-Process -FilePath ${me(e)} -ArgumentList ${me(n.map(fw).join(" "))} -WorkingDirectory ${me(t.stateDir)} -NoNewWindow -Wait -PassThru -RedirectStandardOutput ${me(Fn(t.stateDir,ze))} -RedirectStandardError ${me(Fn(t.stateDir,ho))}`,"exit $p.ExitCode"].join(`
206
+ `)}o(hw,"renderWrapperScript");function md(t){return`-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${pn(hw(t))}`}o(md,"actionArguments");function fd(t){return`${Bi}${JSON.stringify(t.program)}`}o(fd,"description");function Gi(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}o(Gi,"xml");function gw(){let t=process.env.USERNAME,e=process.env.USERDOMAIN;if(t===void 0||t===""||e===void 0||e==="")throw new p("USERNAME or USERDOMAIN is not set, so the logon task cannot name the user it runs for. Run the command from your own Windows session.");return`${e}\\${t}`}o(gw,"currentUserId");function yw(t){let e=Gi(gw());return`<?xml version="1.0" encoding="UTF-16"?>
207
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
208
+ <RegistrationInfo>
209
+ <Description>${Gi(fd(t))}</Description>
210
+ </RegistrationInfo>
211
+ <Triggers>
212
+ <LogonTrigger>
213
+ <Enabled>true</Enabled>
214
+ <UserId>${e}</UserId>
215
+ </LogonTrigger>
216
+ </Triggers>
217
+ <Principals>
218
+ <Principal id="Author">
219
+ <UserId>${e}</UserId>
220
+ <LogonType>InteractiveToken</LogonType>
221
+ <RunLevel>LeastPrivilege</RunLevel>
222
+ </Principal>
223
+ </Principals>
224
+ <Settings>
225
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
226
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
227
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
228
+ <AllowHardTerminate>true</AllowHardTerminate>
229
+ <StartWhenAvailable>false</StartWhenAvailable>
230
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
231
+ <IdleSettings>
232
+ <StopOnIdleEnd>false</StopOnIdleEnd>
233
+ <RestartOnIdle>false</RestartOnIdle>
234
+ </IdleSettings>
235
+ <AllowStartOnDemand>true</AllowStartOnDemand>
236
+ <Enabled>true</Enabled>
237
+ <Hidden>false</Hidden>
238
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
239
+ <WakeToRun>false</WakeToRun>
240
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
241
+ <Priority>5</Priority>
242
+ <RestartOnFailure>
243
+ <Interval>PT1M</Interval>
244
+ <Count>255</Count>
245
+ </RestartOnFailure>
246
+ </Settings>
247
+ <Actions Context="Author">
248
+ <Exec>
249
+ <Command>${tt}</Command>
250
+ <Arguments>${Gi(md(t))}</Arguments>
251
+ </Exec>
252
+ </Actions>
253
+ </Task>
254
+ `}o(yw,"renderTaskXml");async function ji(t,e){let n=["-NoProfile","-NonInteractive","-EncodedCommand",pn(`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
255
+ ${t}`)],r=await X(tt,n);if(r.exitCode!==0)throw new _(Xe(tt,["-EncodedCommand","\u2026"],r));let i;try{i=JSON.parse(r.stdout.replace(/^/,""))}catch{throw new _("PowerShell returned invalid JSON for the service command.")}let s=e.safeParse(i);if(!s.success)throw new _(`PowerShell answered in a form this version does not read: ${s.error.message}`);return s.data}o(ji,"powershellJson");var ww=J.union([J.object({registered:J.literal(!1)}),J.object({registered:J.literal(!0),description:J.string().nullable(),arguments:J.string().nullable(),state:J.string(),lastResult:J.number().nullable(),lastRun:J.string().nullable()})]);async function Fi(t){return ji(`$t = Get-ScheduledTask -TaskPath '\\' -TaskName ${me(t)} -ErrorAction SilentlyContinue
256
+ if ($null -eq $t) { '{"registered":false}'; exit 0 }
257
+ $i = $t | Get-ScheduledTaskInfo
258
+ [pscustomobject]@{ registered = $true; description = $t.Description; arguments = $t.Actions[0].Arguments; state = [string]$t.State; lastResult = $i.LastTaskResult; lastRun = [string]$i.LastRunTime } | ConvertTo-Json -Compress`,ww)}o(Fi,"readTask");var Sw=J.array(J.string());function Ew(t){if(t===null||!t.startsWith(Bi))return null;try{let e=Sw.safeParse(JSON.parse(t.slice(Bi.length)));return e.success?e.data:null}catch{return null}}o(Ew,"programOf");var Wi={description:"a Task Scheduler task \u2014 starts when you log in",async isCurrent(t){let e=await Fi(t.name);return e.registered&&e.state!=="Disabled"&&e.description===fd(t)&&e.arguments===md(t)},async install(t){xt(t.stateDir);let e=Fn(t.stateDir,`${t.name}.task-${dw(8).toString("hex")}.xml`);ke("write the task definition",e,()=>pw(e,`\uFEFF${yw(t)}`,{encoding:"utf16le",mode:384,flag:"wx"}));try{await ie("schtasks",["/Create","/TN",t.name,"/XML",e,"/F"])}finally{uw(e)}return[]},async start(t){await ie("schtasks",["/Run","/TN",t])},async stop(t){await ji(`$t = Get-ScheduledTask -TaskPath '\\' -TaskName ${me(t)} -ErrorAction SilentlyContinue
259
+ if ($null -ne $t) { $t | Stop-ScheduledTask -ErrorAction Stop }
260
+ 'null'`,J.null())},async remove(t){return(await Fi(t)).registered?(await Wi.stop(t),await ie("schtasks",["/Delete","/TN",t,"/F"]),"removed"):"absent"},async read(t){let e=await Fi(t);if(!e.registered)return{kind:"absent"};let n=[`task state: ${e.state}`+(e.lastResult===null?"":`, last result: ${e.lastResult}`)+(e.lastRun===null||e.lastRun===""?"":`, last run: ${e.lastRun}`)];return{kind:"registered",location:`Task Scheduler \\${t}`,program:Ew(e.description),facts:n,active:e.state==="Running"||e.state==="Queued"?!0:e.state==="Disabled"||e.lastResult===0||e.lastResult===267011||e.lastResult===267014?!1:null,autostart:o(()=>Promise.resolve(e.state==="Disabled"?!1:e.state==="Unknown"?null:!0),"autostart")}},async registeredNames(){return ji(`ConvertTo-Json -Compress -InputObject @(Get-ScheduledTask -TaskPath '\\' -ErrorAction SilentlyContinue | Where-Object { $_.TaskName -match '${mw}' } | ForEach-Object { $_.TaskName })`,J.array(J.string()))},logHint(t){return`${Fn(t.stateDir,ze)} and ${Fn(t.stateDir,ho)}`}};function ce(){switch(process.platform){case"darwin":return ad;case"linux":return pd;case"win32":return Wi;default:throw new p(`progon-agent has no OS service for platform ${process.platform} (supported: macOS, Linux, Windows). Run 'progon-agent start' under your own supervisor.`)}}o(ce,"platformServiceManager");async function Eo(t){let e=await t.autostart();return e===null?"unknown":e?"on":"off \u2014 registered but disabled in the OS (turn on: 'progon-agent service enable')"}o(Eo,"describeAutostartState");async function vo(t){return ce().read(Zt(t))}o(vo,"readServiceOf");async function bo(){let t=ce(),e=en(),n=[],r=[],i=[];for(let s of await t.registeredNames()){let l=await t.read(s);if(l.kind==="absent")continue;let c=l.program,a=c===null?null:td(c);c===null||a===null?i.push(l.location):c[1]===e?n.push({name:s,stateDir:a}):r.push(s)}return{services:n,foreign:r,unreadable:i}}o(bo,"thisInstallationServices");async function _o(t){let e=ce();if(Qc()&&(await e.read(t.name)).kind!=="absent")try{el(t.stateDir)}catch(n){throw new _(`Could not retain service-file ownership for ${t.stateDir}: ${n instanceof Error?n.message:String(n)}. The registration is kept; fix the cause and retry.`,{cause:n})}return e.remove(t.name)}o(_o,"unregisterService");var Rw={ok:"[ok] ",warn:"[warn]",fail:"[FAIL]",info:"[info]"};function de(t){return t instanceof Error?t.message:String(t)}o(de,"describe");async function hd(){let t=0,e=o((l,c,a)=>{l==="fail"&&(t+=1),h(`${Rw[l]} ${c}: ${a}`)},"report");e("info","progon-agent",`${te()} on Node ${process.version} (${process.execPath})`),Tw(e);let n=G().path;xw(n,e),await Iw(n,e);let r=t,i=Aw(e);t===r?Pw(e):e("info","Start","not checked \u2014 'progon-agent start' refuses the settings above");let s=await Nw(e);return await Lw(s,i,e),await Ow(n,e),h(t===0?"No problems found.":`${t} check(s) failed \u2014 see [FAIL] above.`),t===0?0:1}o(hd,"runDoctorCommand");function Tw(t){let e=Qt();if(e.kind==="not_global"){t("info","Installation",`not a global npm install (${e.packageRoot}); 'update' cannot replace it and 'uninstall' leaves the package in place`);return}t(e.npmCli===null?"warn":"ok","Installation",`npm global install at ${e.prefix}`+(e.npmCli===null?" \u2014 no npm was found beside this node, so 'progon-agent update' cannot run it":""))}o(Tw,"checkInstallation");function xw(t,e){try{kw(t)}catch(n){if(P(n)){e("info","State directory",`${t} does not exist yet (created by 'enroll')`);return}e("fail","State directory",`${t}: ${de(n)}`);return}try{vw(t,_w.W_OK)}catch(n){e("fail","State directory",`${t} is not writable by this user: ${de(n)}`);return}try{let n=L(t);n===null?e("warn","Enrollment",`${t} holds no enrollment \u2014 run 'progon-agent enroll'`):e("ok","Enrollment",`agent ${n.agentId} at ${n.serverUrl} (${t})`)}catch(n){if(!(n instanceof p))throw n;e("fail","Enrollment",`${de(n)} 'progon-agent reset' removes it.`)}}o(xw,"checkStateDir");async function Iw(t,e){try{let n=await $(t);if(n.kind==="none")e("info","Agent","not running");else if(n.kind==="live"){let r=n.status.service?"as the service":"outside the service";e("info","Agent",`running ${r} \u2014 ${j(n.status)}`)}else e("warn","Agent",`a process owns the state directory, but ${n.reason}`)}catch(n){e("warn","Agent",`cannot ask the control channel: ${de(n)}`)}}o(Iw,"checkAgentProcess");async function Ow(t,e){let n;try{n=await vo(t)}catch(a){if(!(a instanceof _)&&!(a instanceof p))throw a;e("warn","Autostart",`the OS service manager could not be asked: ${de(a)}`);return}if(n.kind==="absent"){e("info","Autostart","off \u2014 no OS service is registered ('progon-agent service enable')");return}let r=`${n.location} (${n.facts.join("; ")})`,i=n.program;if(i===null||i.length<2){e("warn","Autostart",`${r}: the command it starts could not be read`);return}let[s,l]=i,c=[s,l].filter(a=>!bw(a));if(c.length>0){e("fail","Autostart",`${r}: it starts ${c.join(" and ")}, which no longer exist(s). Refresh it: progon-agent service enable --state-dir "${t}"`);return}if(s!==process.execPath||l!==en()){e("warn","Autostart",`${r}: it starts ${s} ${l}, not this node and installation (${process.execPath} ${en()}). Refresh it: progon-agent service enable --state-dir "${t}"`);return}e("ok","Autostart",r)}o(Ow,"checkService");function Aw(t){try{let e=un(process.env),n=[e.https,e.http].filter(r=>r!==void 0);if(n.length===0)t("ok","Proxy","none configured (HTTPS_PROXY / HTTP_PROXY unset)");else{let r=n.map(s=>`${s.variable}=${mo(s.url)}`).join(", "),i=e.noProxy===void 0?"":`, NO_PROXY=${e.noProxy}`;t("ok","Proxy",`${r}${i}`)}}catch(e){if(!(e instanceof p))throw e;t("fail","Proxy",de(e))}Cw(t);try{let e=gn();return t("ok","Browser settings","PROGON_AGENT_* values are valid"),e}catch(e){if(!(e instanceof p))throw e;return t("fail","Browser settings",de(e)),null}}o(Aw,"checkConfiguration");function Cw(t){let e=[],n=!1;try{let r=er(process.env);r!==void 0&&e.push(`${r.variable}=${r.path} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}try{let r=Hs(process.env);r!==void 0&&e.push(`NODE_EXTRA_CA_CERTS=${r} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}n||t("ok","Certificates",e.length===0?"system store only":e.join(", "))}o(Cw,"checkCertificates");function Pw(t){try{let e=Me(),n=gi(e);n!==null&&e.extensionDistOverride===void 0&&ci(n.source==="env_token"?null:n.agentId),n===null&&e.enrollmentCode!==void 0?t("ok","Start",`redeems PROGON_AGENT_ENROLL_CODE at ${e.serverUrl} on its first start`):n===null?t("info","Start",`${e.serverUrl} \u2014 not enrolled yet ('progon-agent enroll')`):t("ok","Start",`connects to ${e.serverUrl} with ${n.source==="env_token"?"PROGON_AGENT_TOKEN":`the enrollment of agent ${n.agentId}`}`)}catch(e){if(!(e instanceof p))throw e;t("fail","Start",`'progon-agent start' refuses: ${de(e)}`)}}o(Pw,"checkStart");async function Nw(t){h("Chromium: checking (downloads it if missing)\u2026");try{return await kt({stdio:"terminal"}),t("ok","Chromium","installed"),!0}catch(e){if(!(e instanceof Q))throw e;return t("fail","Chromium",de(e)),!1}}o(Nw,"checkChromium");async function Lw(t,e,n){if(e!==null&&e.disableBrowserSandbox){n("warn","Browser sandbox","switched off by PROGON_AGENT_DISABLE_BROWSER_SANDBOX");return}if(!t){n("info","Browser sandbox","not checked \u2014 Chromium is not installed");return}try{await Or(),n("ok","Browser sandbox","Chromium starts with its sandbox")}catch(r){if(!(r instanceof p))throw r;n("fail","Browser sandbox",de(r))}}o(Lw,"checkSandbox");async function gd(){let t=G();return h(`progon-agent ${te()} (this installation)`),h(`State directory: ${t.path} (${t.source==="env"?"PROGON_RUNNER_STATE_DIR / --state-dir":"platform default"})`),h(`Enrollment: ${Uw(t.path)}`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN: set in this environment \u2014 a start from here authenticates with it, not with the enrollment above."),h(`Agent: ${await $w(t.path)}`),h(`Autostart: ${await Dw(t.path)}`),0}o(gd,"runStatusCommand");async function Dw(t){try{let e=await vo(t);return e.kind==="absent"?"off (turn on: 'progon-agent service enable')":`${await Eo(e)} \u2014 ${ce().description}; ${e.facts.join("; ")}`}catch(e){if(e instanceof _||e instanceof p)return`unknown \u2014 ${e.message}`;throw e}}o(Dw,"describeAutostart");async function $w(t){let e;try{e=await $(t)}catch(n){return`unknown \u2014 ${n instanceof Error?n.message:String(n)}`}return e.kind==="none"?"not running":e.kind==="live"?`running ${e.status.service?"as the service":"outside the service"} \u2014 ${j(e.status)}`:`a process owns this directory, but ${e.reason}`}o($w,"describeAgentProcess");function Uw(t){try{let e=L(t);return e===null?"not enrolled (run 'progon-agent enroll')":`agent ${e.agentId} at ${e.serverUrl}`}catch(e){if(e instanceof p)return`the state file cannot be used \u2014 ${e.message}`;throw e}}o(Uw,"describeEnrollment");import{setTimeout as jw}from"node:timers/promises";import{setTimeout as Mw}from"node:timers/promises";function yt(t){if(t.service.kind==="failed")throw t.service.error}o(yt,"assertManagedServiceStopped");async function Ne(t,e,n="all",r){let i=ce(),{stateDir:s,name:l}=t,c=null,a=[];try{c=await i.read(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}let d=await $(s),u=d.kind==="live"&&d.status.service?!0:c?.kind==="registered"?c.active:null;c?.kind!=="absent"&&r?.(u);let m=n==="service_only"&&d.kind==="live"&&!d.status.service,g={kind:"not_running"},E=null;if(!m)try{g=await Yc(s,e)}catch(S){if(!(S instanceof p))throw S;E=S}if(c?.kind!=="absent")try{await i.stop(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}if(!m){let S=Date.now()+Ce;for(;(await $(s)).kind!=="none";){if(a.length>0||c?.kind==="absent"||Date.now()>=S)throw new p((E?.message??`A process still owns ${s}. Stop it where it runs and retry.`)+(a.length===0?"":` OS service: ${a.map(b=>b.message).join("; ")}`));await Mw(250)}d.kind==="live"&&(g={kind:"stopped",status:d.status})}return{owner:g,service:a.length>0?{kind:"failed",error:new _(a.map(S=>S.message).join("; "))}:c?.kind==="absent"?{kind:"absent"}:{kind:"stopped"}}}o(Ne,"stopManagedStateDirOwner");import{createInterface as Gw}from"node:readline/promises";var Fw=new Set(["y","yes","\u0434","\u0434\u0430"]),Bw=new Set(["n","no","\u043D","\u043D\u0435\u0442"]);async function ko(t,e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)return"no_answer";let n=Gw({input:process.stdin,output:process.stdout}),r=new Promise(s=>{n.once("close",()=>s(null))}),i=e==="yes"?"(Y/n)":"(y/N)";try{for(;;){let s=await Promise.race([n.question(`${t} ${i} `).catch(()=>null),r]);if(s===null)return"no_answer";let l=s.trim().toLowerCase();if(l==="")return e;if(Fw.has(l))return"yes";if(Bw.has(l))return"no";h("Answer 'y' or 'n'.")}}finally{n.close()}}o(ko,"askYesNo");var yd=2e4,Ww=250;async function wd(t){let e=G().path;switch(t){case"enable":return await Hi(e),0;case"disable":return await Ed(e),0;case"start":return await Ro(se(e)),0;case"stop":return await To(e),0;case"restart":return await To(e),await Ro(se(e)),0;case"status":return await Kw(e),0}}o(wd,"runServiceCommand");function Sd(t){h(t.service?`Stopping the service (${j(t)}) to apply the new registration\u2026`:`Stopping progon-agent started outside the service (${j(t)}) \u2014 the service takes over\u2026`)}o(Sd,"announceHandOver");function Hw(t){if(L(t)===null)throw new p(`${t} holds no enrollment, so a service there would stop at once. Enroll first: progon-agent enroll --autostart`)}o(Hw,"assertEnrolled");async function Hi(t){Hw(t);let e=ce(),n=ed(t),r=await e.isCurrent(n),i=await $(t);if(i.kind==="live"&&i.status.service&&r){h(`The service ${n.name} is enabled and running (${j(i.status)}).`);return}yt(await Ne(n,Sd));let s=r?[]:await e.install(n);r||h(`Registered ${n.name} as ${e.description}.`),Jw(n),await e.start(n.name),await vd(n);for(let l of s)h(l)}o(Hi,"enableService");async function Ed(t){let e=se(t),{name:n}=e,r=await $(t);yt(await Ne(e,s=>h(`Stopping the service (${j(s)})\u2026`),"service_only"));let i=await _o(e);h(i==="removed"?`Autostart is off: the service ${n} is removed. The enrollment is kept.`:`Autostart is off: no service is registered for ${t}.`),r.kind==="live"&&!r.status.service&&h(`progon-agent started outside the service is still running (${j(r.status)}).`)}o(Ed,"disableService");async function Ro(t){let e=ce(),{stateDir:n,name:r}=t;if((await e.read(r)).kind==="absent"){h("No service is registered for this state directory \u2014 enabling it."),await Hi(n);return}let i=await $(n);if(i.kind==="live"&&i.status.service){h(`The service ${r} is already running (${j(i.status)}).`);return}yt(await Ne(t,Sd)),await e.start(r),await vd(t)}o(Ro,"startService");async function To(t){let e=await Ne(se(t),r=>h(`Stopping progon-agent (${j(r)})\u2026`));yt(e);let n=e.owner;n.kind==="stopped"?h(`Stopped progon-agent (pid ${n.status.pid}).`):e.service.kind==="stopped"?h(`Stopped the OS service for ${t}, including any scheduled restart.`):h(`No progon-agent is running for ${t}.`),e.service.kind==="stopped"&&h("Autostart stays on: it starts again with 'progon-agent service start' or by the OS.")}o(To,"stopService");async function vd(t){let e=Date.now()+yd;for(;Date.now()<e;){let s=await $(t.stateDir);if(s.kind==="live"&&s.status.service){h(`The service ${t.name} is running (${j(s.status)}).`);return}await jw(Ww)}let n=ce(),r=await n.read(t.name),i=r.kind==="registered"?` The OS: ${r.facts.join("; ")}.`:"";throw new _(`The service ${t.name} was started but did not answer within ${yd/1e3} s.${i} Its log says why: ${n.logHint(t)}`)}o(vd,"waitForService");function Jw(t){if(t.environment.length===0)h("Settings from this environment: none.");else{h("Settings from this environment, written into the registration:");for(let[e,n]of t.environment){let r=/proxy/i.test(e)||e==="PLAYWRIGHT_DOWNLOAD_HOST"||e==="PROGON_SERVER_URL";h(` ${e}=${r?mo(n):n}`)}}process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is not copied: the service authenticates with the enrollment.")}o(Jw,"describeEnvironment");async function Kw(t){let e=ce(),n=Zt(t),r=await e.read(n);if(h(`State directory: ${t}`),r.kind==="absent")h(`Autostart: off \u2014 no service ${n} is registered.`);else{h(`Autostart: ${await Eo(r)} \u2014 ${e.description}`),h(`Registration: ${r.location}`);for(let s of r.facts)h(` ${s}`);h(`Log: ${e.logHint({name:n,stateDir:t})}`)}let i=await $(t);i.kind==="none"?h("Process: not running"):i.kind==="live"?h(`Process: ${i.status.service?"the service":"started outside the service"} \u2014 ${j(i.status)}`):h(`Process: a process owns this directory, but ${i.reason}`)}o(Kw,"printServiceStatus");async function bd(t){let e=G(),n=t==="ask"?await Vw():t;if(n==="keep")return h(`Autostart was not changed (no terminal to ask, no answer). Turn it on with: progon-agent service enable${Nn(e)}`),0;try{return n==="on"?await Hi(e.path):await Ed(e.path),0}catch(r){let i=r instanceof p||r instanceof _;if(h(`This machine is enrolled, but autostart could not be ${n==="on"?"set up":"turned off"}`+(i?":":".")),i&&h(` ${r.message}`),h(`Retry: progon-agent service ${n==="on"?"enable":"disable"}${Nn(e)}`),!i)throw r;return 1}}o(bd,"applyAutostartAfterEnroll");async function Vw(){let t=await ko("Start the runner automatically in the background?","yes");return t==="yes"?"on":t==="no"?"off":"keep"}o(Vw,"askAutostart");import{readdirSync as Rd,rmdirSync as qw,rmSync as Ji}from"node:fs";import{basename as _d,join as kd}from"node:path";function Le(t){return t instanceof Error?t.message:String(t)}o(Le,"describe");function Td(t){let e=[],n;try{n=Rd(t,{withFileTypes:!0})}catch(a){return P(a)?e:[{path:t,reason:Le(a)}]}let r=new Set([_d(nt(t)),_d(mn(t))]),i=n.some(a=>r.has(a.name)&&!a.isDirectory()),s=n.some(a=>a.name===ft&&a.isFile()),l=kd(t,Er),c=null;try{c=br(t);let a=i||s||c!==null,d=c===null?[]:c.profiles,u=Yw(t,n,e,a,d);(u.length>0||c===null&&a)&&(c={...c??vr,profiles:[...d,...u]},_r(t,c))}catch(a){e.push({path:l,reason:Le(a)}),c=null}if(i)try{rr(t)}catch(a){e.push({path:nt(t),reason:Le(a)})}if(c!==null){let a=new ut(t);for(let d of c.profiles){let u=a.userDataDirFor(d);try{Ji(u,{recursive:!0,force:!0})}catch(m){e.push({path:u,reason:Le(m)})}}try{Ki(a.instancesRoot)}catch(d){e.push({path:a.instancesRoot,reason:Le(d)})}}for(let a of n){let d=c!==null&&c.extensionCopy&&al(a.name);if(!(c!==null&&(Za(a.name)||d||Wc(a.name)||c.serviceFiles&&zc(a.name))))continue;let m=kd(t,a.name);if(!(a.isDirectory()&&!d))try{Ji(m,{recursive:a.isDirectory(),force:!0})}catch(g){e.push({path:m,reason:Le(g)})}}if(c!==null&&e.length===0)try{Ji(l)}catch(a){e.push({path:l,reason:Le(a)})}return e}o(Td,"removeRunnerFiles");function Yw(t,e,n,r,i){if(!e.some(c=>c.name===ar&&c.isDirectory()))return[];let s=new ut(t),l=[];try{for(let c of Rd(s.instancesRoot,{withFileTypes:!0}))if(c.isDirectory()&&!i.includes(c.name))try{s.read(c.name).runId===c.name?l.push(c.name):r&&n.push({path:s.userDataDirFor(c.name),reason:"Instance marker does not identify this profile; ownership is unknown and it was kept"})}catch(a){let d=typeof a=="object"&&a!==null?a.code:void 0;(r||d!==void 0&&!P(a))&&n.push({path:s.userDataDirFor(c.name),reason:`Cannot establish profile ownership; it was kept: ${Le(a)}`})}}catch(c){n.push({path:s.instancesRoot,reason:Le(c)})}return l}o(Yw,"findInstanceProfiles");function Ki(t){try{return qw(t),"removed"}catch(e){if(P(e))return"absent";let n=e.code;if(n==="ENOTEMPTY"||n==="EEXIST")return"not_empty";throw e}}o(Ki,"removeDirectoryIfEmpty");async function sn(t,e){let{stateDir:n}=t,r;try{r=await Ne(t,e)}catch(u){if(u instanceof p)return{kind:"owner_running",stateDir:n,reason:u.message};throw u}let i=r.owner,s=await Xw(t),l=r.service.kind==="failed"?{kind:"failed",reason:r.service.error.message+(s.kind==="failed"&&s.reason!==r.service.error.message?`; ${s.reason}`:"")}:s,c=zw(n),a=Td(n),d=c.kind==="read"?await Qw(c.identity):{kind:"not_attempted"};return{kind:"done",stateDir:n,stop:i,service:l,identity:c,cleanupFailures:a,remote:d}}o(sn,"resetStateDir");async function Xw(t){try{return await _o(t)==="removed"?{kind:"removed",name:t.name}:{kind:"absent"}}catch(e){if(e instanceof _||e instanceof p)return{kind:"failed",reason:e.message};throw e}}o(Xw,"removeServiceRegistration");function zw(t){try{let e=L(t);return e===null?{kind:"absent"}:{kind:"read",identity:e}}catch(e){if(e instanceof p)return{kind:"unreadable",reason:e.message};throw e}}o(zw,"readIdentity");async function Qw(t){let e=new Ge({serverUrl:t.serverUrl,agentToken:t.agentToken});try{return await e.revokeSelf(),{kind:"revoked"}}catch(n){if(n instanceof T)return{kind:"already_revoked"};if(n instanceof ee){let r=n.params?.minVersion;return{kind:"not_confirmed",reason:typeof r=="string"?`the server accepts progon-agent ${r} or newer only`:"the server refuses this version of progon-agent"}}if(n instanceof x&&n.status===404)return{kind:"not_confirmed",reason:"the server does not offer self-revocation yet"};if(n instanceof x)return{kind:"not_confirmed",reason:`the server answered HTTP ${n.status}${n.errorCode===null?"":` ${n.errorCode}`}`};if(n instanceof Z)return{kind:"not_confirmed",reason:`the server could not be reached: ${n.message}`};if(n instanceof fe)return{kind:"not_confirmed",reason:`the server's answer was not understood: ${n.message}`};throw n}}o(Qw,"revokeRegistration");function wt(t){h(`Stopping progon-agent (${j(t)})\u2026`)}o(wt,"announceStop");async function xd(){let t=G().path;return await To(t),0}o(xd,"runStopCommand");async function Id(){let t=await sn(se(G().path),wt);return Vi(t)?0:1}o(Id,"runResetCommand");function Vi(t){if(t.kind==="owner_running")return h(t.reason),h("The identity and local files were kept."),!1;t.stop.kind==="stopped"&&h(`Stopped progon-agent (pid ${t.stop.status.pid}).`);let e=qi(t.service);e!==null&&h(e);for(let n of Yi(t.identity,t.remote))h(n);if(t.cleanupFailures.length>0||t.service.kind==="failed"){h("Could not remove:"),t.service.kind==="failed"&&h(` the OS service \u2014 ${t.service.reason}`);for(let n of t.cleanupFailures)h(` ${n.path} \u2014 ${n.reason}`);return h("Fix the cause and run 'progon-agent reset' again to finish."),!1}return h(`This machine is disconnected: the credential and browser profiles in ${t.stateDir} are removed.`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is set in this environment; reset does not change it \u2014 its source does."),!0}o(Vi,"reportResetResult");function qi(t){switch(t.kind){case"removed":return`Autostart is off: the service ${t.name} is removed.`;case"absent":return null;case"failed":return null}}o(qi,"describeServiceRemoval");function Yi(t,e){switch(t.kind){case"absent":return["This directory had no enrollment."];case"unreadable":return[`The state file could not be used (${t.reason}), so the server was not asked to revoke this machine. If it is still listed in Progon \u2192 Settings \u2192 Agents, remove it there.`];case"read":break}let{agentId:n,serverUrl:r}=t.identity;switch(e.kind){case"revoked":return[`Agent ${n} is revoked on ${r}.`];case"already_revoked":return[`Agent ${n} was already revoked on ${r}.`];case"not_confirmed":return[`The agent record ${n} may remain on ${r}: ${e.reason}. Remove it in Progon \u2192 Settings \u2192 Agents.`];case"not_attempted":return[]}}o(Yi,"describeRemote");import{existsSync as Zw}from"node:fs";import{homedir as eS}from"node:os";import{resolve as tS}from"node:path";async function Od(t){let e=[],n=await nS(t,e),r=n.map(s=>s.stateDir);h("progon-agent uninstall removes:");for(let s of r)h(` state directory ${s}`);h(" this installation's Chromium (browsers other Playwright installations use are kept)"),h(" the progon-agent package");for(let s of n){let l=s.stateDir;h(`
261
+ ${l}`);let c=await sn(s,wt);if(c.kind==="owner_running"){h(` ${c.reason}`),e.push(`${l} \u2014 could not confirm that its directory owner stopped`);continue}let a=qi(c.service);a!==null&&h(` ${a}`);for(let u of Yi(c.identity,c.remote))h(` ${u}`);c.service.kind==="failed"&&e.push(`the OS service of ${l} \u2014 ${c.service.reason}`);for(let u of c.cleanupFailures)e.push(`${u.path} \u2014 ${u.reason}`);if(c.cleanupFailures.length>0||c.service.kind==="failed")continue;let d=Ki(l);d==="removed"?h(" removed"):d==="absent"?h(" nothing there"):h(" progon-agent files removed; the directory holds other files and is kept")}if(h(""),e.length>0?h("Chromium and the package are kept until the state directories are clean."):(await rS(e),e.length===0?await oS(e):e.push("the progon-agent package \u2014 kept so uninstall can finish Chromium cleanup on retry")),e.length===0)return h("progon-agent is uninstalled."),0;h("Not removed:");for(let s of e)h(` ${s}`);let i=r.map(s=>` --state-dir "${s}"`).join("");return h(`Fix the cause and run again to finish: progon-agent uninstall${i}`),1}o(Od,"runUninstallCommand");async function nS(t,e){let n=[],r=o(s=>{let l=tS(s);n.some(c=>c.stateDir===l)||n.push(se(l))},"add");try{r(hn(process.platform,process.env,eS()))}catch(s){if(!(s instanceof p))throw s;h(`No standard state directory here: ${s.message}`)}let i=process.env.PROGON_RUNNER_STATE_DIR;i!==void 0&&i!==""&&r(i);for(let s of t)r(s);try{let s=await bo();for(let l of s.services){let c=n.findIndex(a=>a.stateDir===l.stateDir);c===-1?n.push(l):n[c]=l}for(let l of s.foreign){let c=n.find(a=>a.name===l);c!==void 0&&(n.splice(n.indexOf(c),1),h(`${c.stateDir} is left alone: its OS service ${l} runs another progon-agent installation. Uninstall that one with its own 'progon-agent uninstall'.`))}for(let l of s.unreadable)e.push(`${l} \u2014 a progon-agent service whose state directory cannot be read; remove it by hand`)}catch(s){if(!(s instanceof _)&&!(s instanceof p))throw s;e.push(`OS services \u2014 they could not be listed: ${s.message}`)}return n}o(nS,"collectTargets");async function rS(t){let e;try{e=Ho().cliPath}catch(r){if(!(r instanceof Q))throw r;t.push(`Chromium \u2014 ${r.message}`);return}if(!Zw(rt.executablePath())){h("This installation's Chromium is not on disk \u2014 nothing to remove.");return}h("Removing this installation's Chromium\u2026");let n=await Dn(e,["uninstall"]);n!==0&&t.push(`Chromium \u2014 Playwright's uninstall exited ${n===null?"by signal":String(n)}`)}o(rS,"removeChromium");async function oS(t){let e=Qt();if(e.kind==="not_global"){h(`The package is not a global npm install (${e.packageRoot}); it is left as it is.`);return}if(e.npmCli===null){t.push(`the package \u2014 no npm beside this node; run: npm uninstall -g ${we}`);return}h(`Removing the package from ${e.prefix}\u2026`);let n=await fo(e.npmCli,["uninstall","--global","--prefix",e.prefix,we]);n!==0&&t.push(`the package \u2014 npm exited ${n===null?"by signal":String(n)}; run: npm uninstall -g ${we}`)}o(oS,"removePackage");async function Ad(t){let e=Qt();if(e.kind==="not_global")throw new p(`This progon-agent is not a global npm install (it runs from ${e.packageRoot}), so there is no installation for 'update' to replace. Update it the way it was installed.`);let n=`${we}@${t===null?"latest":t}`;if(e.npmCli===null)throw new p(`No npm was found beside this node (${process.execPath}), so 'update' cannot run it. Update with the npm that installed progon-agent: npm i -g ${n}`);let r=G(),{terminalStopped:i,servicesStopped:s}=await sS(r.path),l=!1,c;try{c=await iS(e.npmCli,e.prefix,e.packageRoot,n)}finally{Ci(e.packageRoot).kind==="installed"?l=await Cd(s):aS(s),i&&h(`Start the agent again: progon-agent start${r.source==="env"?` --state-dir "${r.path}"`:""}`)}return c===0&&l?0:1}o(Ad,"runUpdateCommand");async function iS(t,e,n,r){let i=te();h(`Installing ${r} into ${e}\u2026`);let s=await fo(t,["install","--global","--prefix",e,r]),l=Ci(n);if(s!==0)return h(`npm did not finish (exit ${s===null?"by signal":String(s)}).`),l.kind==="installed"?h(`Installed now: progon-agent ${l.version} (was ${i}).`):h(`The package is damaged (${l.reason}). Reinstall it: npm i -g ${r}`),1;if(l.kind==="damaged")return h(`npm finished, but the package is damaged (${l.reason}). Reinstall it: npm i -g ${r}`),1;h(l.version===i?`progon-agent ${l.version} is installed (unchanged).`:`Updated progon-agent ${i} \u2192 ${l.version}. The enrollment is kept.`),h("Preparing Chromium for this version\u2026");let c=await Dn(l.cliPath,["install-browser"]);return c!==0&&h(`Chromium could not be prepared (exit ${c===null?"by signal":String(c)}); 'progon-agent start' downloads it again, or run 'progon-agent doctor'.`),c===0?0:1}o(iS,"installUpdate");async function sS(t){let e=await bo();if(e.unreadable.length>0)throw new p(`Update changed nothing: these progon-agent services may run this installation, but their command cannot be read: ${e.unreadable.join(", ")}. Remove them by hand, then retry.`);let n=e.services.find(a=>a.stateDir===t),r=se(t),i=[];n!==void 0?i.push({target:n,scope:"all"}):e.foreign.includes(r.name)?h(`${t} is left alone: its OS service ${r.name} runs another progon-agent installation.`):i.push({target:r,scope:"all"});for(let a of e.services)a!==n&&i.push({target:a,scope:"service_only"});let s=!1,l=!1,c=[];try{for(let{target:a,scope:d}of i){let u=await Ne(a,g=>{!g.service&&d==="all"&&(l=!0),wt(g)},d,g=>{if(g!==!1){if(g===null)throw new _(`The OS did not report the activity of the service for ${a.stateDir}; update cannot choose which services to restore.`);c.push(a)}});yt(u);let m=u.owner;d==="all"&&m.kind==="stopped"&&!m.status.service&&(s=!0)}}catch(a){throw h("Update was aborted before changing the package. Restoring the services already stopped\u2026"),await Cd(c),l&&h(`The terminal runner may have stopped; start it again: progon-agent start --state-dir "${t}"`),a}return{terminalStopped:s,servicesStopped:c}}o(sS,"stopRunningAgents");async function Cd(t){let e=!0;for(let n of t){let r=n.stateDir;try{await Ro(n)}catch(i){if(e=!1,!(i instanceof _)&&!(i instanceof p)){let s=i instanceof Error?i.stack:void 0;process.stderr.write(JSON.stringify({level:"error",module:"update",msg:"Unexpected failure while restarting a service",stateDir:C(r),err:C(i instanceof Error?i.message:String(i)),stack:s===void 0?void 0:C(s)})+`
262
+ `)}h(`The service for ${r} did not start again: ${i instanceof Error?i.message:String(i)}`),h(`Retry: progon-agent service start --state-dir "${r}"`)}}return e}o(Cd,"restartServices");function aS(t){for(let{stateDir:e}of t)h(`The service for ${e} stays stopped until the package is repaired; then: progon-agent service start --state-dir "${e}"`)}o(aS,"reportServicesLeftStopped");async function Pd(t){if(t.command==="version")return process.stdout.write(`${te()}
263
+ `),0;switch(zn(),t.command!=="uninstall"&&t.stateDir!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t.stateDir),t.command){case"status":return gd();case"stop":return xd();case"reset":return Id();case"doctor":return hd();case"update":return Ad(t.version);case"uninstall":return Od(t.stateDirs);case"service":return wd(t.verb)}}o(Pd,"runLifecycleCommand");import{randomBytes as cS}from"node:crypto";import{linkSync as dS,symlinkSync as uS}from"node:fs";import{createServer as pS}from"node:net";import{join as Wn,resolve as mS}from"node:path";var Bn=w("state-dir-owner"),lS=4*1024,xo=class{static{o(this,"OwnerState")}#e;#t;#n;#r=new Date().toISOString();#i="starting";#a=o(()=>null,"#readActiveRun");#s;constructor(e,n,r){this.#e=e,this.#t=n,this.#n=r}own(e){let n=!1,r=this.#e,i=o(()=>{n||(n=!0,process.off("exit",i),e(),Bn.info("State directory released",{stateDir:r}))},"release");return process.on("exit",i),Bn.info("State directory owned",{stateDir:r,pid:process.pid}),{stateDir:r,setPhase:o(s=>{this.#i=s},"setPhase"),setActiveRunReader:o(s=>{this.#a=s},"setActiveRunReader"),setStopHandler:o(s=>{this.#s=s},"setStopHandler"),release:i}}serve(e){e.setEncoding("utf8");let n=oo(),r="";e.on("error",i=>{Bn.debug("Control channel connection failed",{err:i.message})}),e.write(`${JSON.stringify({protocol:Pn,challenge:n})}
264
+ `),e.on("data",i=>{r+=i;let s=r.indexOf(`
265
+ `);if(s===-1){r.length>lS&&e.destroy();return}let l=uo(r.slice(0,s),jc);if(!l.ok||!lo(so(this.#t,n,l.value.nonce,l.value.type),l.value.proof)){Bn.warn("Refused a control request that did not prove the key of this directory",{stateDir:this.#e}),e.destroy();return}let{type:c,nonce:a}=l.value;c==="stop"&&(this.#i="stopping"),e.end(`${JSON.stringify({proof:ao(this.#t,n,a),status:this.#l()})}
266
+ `),c==="stop"&&this.#o()})}#o(){Bn.info("Stop requested over the control channel",{stateDir:this.#e}),this.#s()}#l(){return{protocol:Pn,pid:process.pid,version:te(),startedAt:this.#r,stateDir:this.#e,phase:this.#i,activeRunId:this.#a(),service:this.#n}}};var Hn=5;async function Ld(t,e){let n=mS(t);xt(n),io(n);let r=xc(n),i=new xo(n,r,e.service),s=pS(g=>i.serve(g)),l=Oi(n);if(l.kind==="pipe"){for(let g=0;g<Hn;g+=1){if(await Nd(s,()=>s.listen(l.name))==="bound")return{kind:"acquired",ownership:i.own(()=>jn(s,n,null))};let S=await $(n);if(S.kind!=="none")return{kind:"held",answer:S}}throw Io(n)}let c=performance.now()+Hn*Ye;await Uc(n,()=>performance.now()+2*Ye<c,async g=>(await $(n,g)).kind==="none");let a=`control-${process.pid}-${cS(4).toString("hex")}.sock`,d=`${a}.pending`;if(await Nd(s,()=>po(n,()=>s.listen(d)))!=="bound")throw new Error(`[state-dir-owner] Cannot bind the control socket ${Wn(n,a)}: the name is already in use.`);let m=!1;try{dS(Wn(n,d),Wn(n,a)),m=!0,qe(Wn(n,d));for(let g=0;g<Hn;g+=1){let E=An(n);if(E!==null){if(performance.now()+Ye>c)throw Io(n);let b=await $(n,E);if(b.kind!=="none")return jn(s,n,a),{kind:"held",answer:b}}if(performance.now()>c)throw Io(n);let S=E===null?co(n):Ii(n,E);try{uS(a,S)}catch(b){if(Dd(b)!=="EEXIST")throw b;continue}if(An(n)!==a){E!==null&&qe(S);continue}return E!==null&&$c(n,a),Mc(n,a),{kind:"acquired",ownership:i.own(()=>jn(s,n,a))}}}catch(g){throw jn(s,n,m?a:d),g}throw jn(s,n,a),Io(n)}o(Ld,"acquireStateDirOwnership");async function Nd(t,e){return new Promise((n,r)=>{let i=o(l=>{t.off("listening",s),Dd(l)==="EADDRINUSE"?n("in_use"):r(l)},"onError"),s=o(()=>{t.off("error",i),n("bound")},"onListening");t.once("error",i),t.once("listening",s),e()})}o(Nd,"listen");function jn(t,e,n){if(n===null){t.close();return}qe(Wn(e,n)),po(e,()=>t.close())}o(jn,"closeOwnSocket");function Io(t){return new Error(`[state-dir-owner] Could not take ownership of ${t} within ${Hn} claim rounds and their ${Hn*Ye/1e3} s answer budget. The control directory kept changing or its socket probes used that budget. Check the processes using this directory and start again.`)}o(Io,"roundsExhausted");function Dd(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Dd,"errnoOf");var Jn=w("daemon");async function Ud(t){ca(),Jn.info("progon-agent starting");let e=G().path,n=await Ld(e,{service:t.service});if(n.kind==="held"){let{answer:i}=n;if(i.kind==="foreign")throw new p(`Cannot take the state directory ${e}: its control channel is held by a process that is not its progon-agent (${i.reason}). On Windows another user's process can hold the channel name; end that process and start again.`);return i.kind==="live"?Jn.info("progon-agent is already running for this state directory \u2014 nothing to start",{stateDir:e,ownerPid:i.status.pid,version:i.status.version,since:i.status.startedAt,phase:i.status.phase}):Jn.info("Another process owns this state directory, but it did not say what it is \u2014 nothing to start",{stateDir:e,reason:i.reason}),0}let r=n.ownership;try{let i=new AbortController,s=Vl(i.signal).catch(u=>{if(i.signal.aborted&&u===i.signal.reason)return null;throw u}),l=da(async u=>{r.setPhase("stopping"),i.abort();let m=await s;m!==null&&await m.shutdown(u)});r.setStopHandler(()=>l("stop_request"));let c=await s.catch(u=>{if(i.signal.aborted)return null;throw u});if(c===null||i.signal.aborted)return null;r.setActiveRunReader(()=>c.activeRunId),r.setPhase("running");let a;try{a=await c.run()}catch(u){throw await c.shutdown("fatal").catch(m=>{throw new AggregateError([u,m],`${$d(u)} \u2014 and the teardown after it failed too, so the browser may still be running: ${$d(m)}`)}),u}let d=Wl[a];return d.level==="error"?Jn.error(d.message):Jn.info(d.message),d.exitCode}finally{r.release()}}o(Ud,"runDaemon");function $d(t){return t instanceof Error?t.message:String(t)}o($d,"describe");import{createHash as _S,randomBytes as kS}from"node:crypto";import{z as W}from"zod";var Md=W.object({requestId:W.uuid(),mode:W.literal("device"),userCode:W.string().min(1),verificationUrl:W.url(),expiresAt:W.iso.datetime({offset:!0}),pollIntervalSec:W.number().int().positive()}),Gd=W.object({status:W.literal("authorization_pending"),expiresAt:W.iso.datetime({offset:!0}),pollIntervalSec:W.number().int().positive()}),fS=W.object({companyName:W.string(),approvedByEmail:W.string(),approvedAt:W.string()}),Fd=W.object({credential:qn,approval:fS});var Bd=w("gateway-enrollment-request"),Oo=class{static{o(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Mt}async create(e){let n=await st({operation:"enrollment_request_create",method:"POST",url:q(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:ka}),r=V("enrollment_request_create",Md.safeParse(n));return Bd.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await st({operation:"enrollment_request_poll",method:"POST",url:q(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ra}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let i=V("enrollment_request_poll",Fd.safeParse(n));return Bd.info("Enrollment request approved",{agentId:i.credential.agentId}),{kind:"enrolled",credential:i.credential,approval:i.approval}}if(r!==null&&"status"in r){let i=V("enrollment_request_poll",Gd.safeParse(n));return{kind:"pending",expiresAt:i.expiresAt,pollIntervalSec:i.pollIntervalSec}}throw new fe("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 st({operation:"enrollment_request_cancel",method:"POST",url:q(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ta})}};async function Xi(t,e){let n=L(t.stateDir);if(n===null||Ue(n.serverUrl,t.serverUrl))return"proceed";h(`This machine is enrolled against ${n.serverUrl} (agent ${n.agentId}), not ${t.serverUrl}. An agent credential is valid only at the server that issued it.`);let r=await ko(`Reset it \u2014 revoke the agent on ${n.serverUrl}, remove its credential and autostart here \u2014 and enroll against ${t.serverUrl}?`,"no");if(r==="yes")return Vi(await sn(se(t.stateDir),wt))?(h(`Enrolling against ${t.serverUrl}\u2026`),"proceed"):(h(`Not enrolled against ${t.serverUrl}: the reset did not finish.`),"stopped");let i=Nn(G());return h(r==="no"?"Nothing was changed.":"Nothing was changed (no terminal to ask, no answer)."),h(` To move this machine to ${t.serverUrl}: progon-agent reset${i}, then ${e.text} again \u2014 or run it in a terminal and answer 'y'.`+(e.withCode?" The enrollment code was not used and stays valid until it expires.":"")),h(` To keep both, enroll the second one under its own state directory: PROGON_RUNNER_STATE_DIR=<dir> ${e.text} (and give 'progon-agent start' the same variable).`),"stopped"}o(Xi,"offerResetForOtherServer");import{spawn as hS}from"node:child_process";var Kn=w("browser-open");function Ao(t){return t!==void 0&&t!==""}o(Ao,"isSet");function gS(t,e){return!(Ao(t.SSH_CONNECTION)||Ao(t.SSH_TTY)||e==="linux"&&!Ao(t.DISPLAY)&&!Ao(t.WAYLAND_DISPLAY))}o(gS,"shouldAttemptBrowserOpen");var yS=/[&|^<>"'` ]/;function wS(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!yS.test(t)}o(wS,"isSpawnSafeUrl");function SS(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}}o(SS,"browserOpenCommand");function jd(t,e,n){if(!gS(e,n)){Kn.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!wS(t)){Kn.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=SS(t,n);if(r===null){Kn.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let i=hS(r.command,[...r.args],{detached:!0,stdio:"ignore"});i.on("error",s=>{Kn.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:s.message})}),i.unref()}catch(i){Kn.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:i instanceof Error?i.message:String(i)})}}o(jd,"openVerificationUrl");var ES=30,vS=5;function Wd(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}o(Wd,"initialPollSchedule");function Co(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+vS,i=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(i,ES);return{state:{intervalSec:s,deadlineMs:t.deadlineMs},delayMs:s*1e3}}let n=ge(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}o(Co,"nextPollDelayMs");function Hd(t,e){return e>=t.deadlineMs}o(Hd,"isDeadlinePassed");function Jd(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}o(Jd,"clampDelayToDeadline");async function Kd(t,e){try{return await e()}catch(n){let r=bS(n,t);throw r!==null?r:n}}o(Kd,"explainingEnrollRefusals");function bS(t,e){let n=`progon-agent enroll <code> --server ${e}`;if(t instanceof At)return new p(`[progon-agent] ${e} did not accept the enrollment code: it is unknown, expired or already used \u2014 the server does not say which. Nothing was saved on this machine.
267
+ Create a new code in Progon and run: ${n}`,{cause:t});if(t instanceof ot)return new p(`[progon-agent] ${e} does not accept this version of progon-agent (${t.message}). Nothing was saved on this machine.
268
+ Update it with 'progon-agent update', then run: ${n}`,{cause:t});if(t instanceof x&&t.operation==="enroll"&&t.status===429){let r=t.retryAfterMs===null?"Wait, then run the command again.":`Wait ${Math.ceil(t.retryAfterMs/1e3)} s, then run the command again.`;return new p(`[progon-agent] ${e} refused the enrollment: too many attempts from this address. Nothing was saved on this machine.
269
+ ${r}`,{cause:t})}return null}o(bS,"explainEnrollRefusal");var an=w("device-enrollment"),RS=24,TS=2e3,zi=0,St=1,qd=130,xS="This machine is already enrolled. Start the daemon with: progon-agent start",IS="Enrollment was denied in the browser. Nothing was created on this machine.",OS="Cancelled. Nothing was saved on this machine.",AS="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 Vd(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}o(Vd,"expiredLine");function CS(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}o(CS,"timedOutLine");function PS(t){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${t}`}o(PS,"alreadyCompletedLine");function NS(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}o(NS,"noLongerValidLine");async function Yd(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=Me(),r=Je(),i=e.PROGON_AGENT_ENROLL_CODE;if(i!==void 0&&i!=="")return Qi({config:n,machine:r,retryCommand:`progon-agent enroll --server ${n.serverUrl}`,fetchImpl:t.fetchImpl,rng:t.rng});let s=L(n.stateDir);if(s!==null&&Ue(s.serverUrl,n.serverUrl))return process.stdout.write(`${xS}
270
+ `),zi;if(await Xi(n,{text:`progon-agent enroll --server ${n.serverUrl}`,withCode:!1})==="stopped")return St;let c=kS(RS).toString("base64url"),a=new Oo(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),d=await a.create(MS(c));return $S(d),t.openBrowser&&jd(d.verificationUrl,e,process.platform),LS({client:a,config:n,created:d,deviceSecret:c,timeoutSec:t.timeoutSec,rng:t.rng})}o(Yd,"runDeviceEnrollment");async function LS(t){let{client:e,config:n,created:r,deviceSecret:i,timeoutSec:s,rng:l}=t,c=Date.parse(r.expiresAt),a=Wd({pollIntervalSec:r.pollIntervalSec,expiresAtMs:c,timeoutSec:s,nowMs:Date.now()}),d=a.intervalSec*1e3,u=0,m={signal:null},g=new AbortController,E=o(S=>{m.signal!==null&&(process.stderr.write(`${AS}
271
+ `),process.exit(qd)),m.signal=S,g.abort()},"onSignal");process.on("SIGINT",E),process.on("SIGTERM",E);try{for(;;){if(await oe(Jd(a,d,Date.now()),g.signal),m.signal!==null)return await DS(e,i,m.signal);if(Hd(a,Date.now()))return s!==null&&a.deadlineMs<c?process.stdout.write(`${CS(s,r.verificationUrl)}
272
+ `):process.stdout.write(`${Vd(n.serverUrl)}
273
+ `),St;let S;try{S=await e.poll(i)}catch(I){if(I instanceof Nt)return process.stdout.write(`${IS}
274
+ `),St;if(I instanceof Lt)return process.stdout.write(`${Vd(n.serverUrl)}
275
+ `),St;if(I instanceof Dt)return an.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:I.errorCode,status:I.status}),process.stdout.write(`${PS(n.serverUrl)}
276
+ `),St;if(I instanceof $t)return an.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:I.errorCode,status:I.status}),process.stdout.write(`${NS(n.serverUrl)}
277
+ `),St;if(I instanceof Pt){let N=Co(a,{kind:"slow_down",retryAfterSec:I.retryAfterSec});a=N.state,d=N.delayMs,an.warn("The server asked this machine to poll more slowly",{intervalSec:a.intervalSec,retryAfterSec:I.retryAfterSec});continue}if(I instanceof Z||I instanceof x&&I.status>=500){let N=Co(a,{kind:"transport_error",attempt:u,rng:l});u+=1,a=N.state,d=N.delayMs,an.warn("The enrollment poll failed; retrying until the request expires",{attempt:u,delayMs:d,err:I.message});continue}throw I}if(S.kind==="enrolled")return It(n.stateDir,{agentId:S.credential.agentId,agentToken:S.credential.agentToken,protocolVersion:S.credential.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${S.approval.companyName} (approved by ${S.approval.approvedByEmail}). Start the daemon: progon-agent start
278
+ `),zi;u=0;let b=Co(a,{kind:"pending"});a=b.state,d=b.delayMs}}finally{process.off("SIGINT",E),process.off("SIGTERM",E)}}o(LS,"waitForApproval");async function DS(t,e,n){try{await Ke({operation:"device enrollment cancel",timeoutMs:TS,work:o(()=>t.cancel(e),"work")})}catch(r){an.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(`${OS}
279
+ `),qd}o(DS,"cancelRequest");async function Qi(t){let{config:e,machine:n,fetchImpl:r,rng:i}=t;if(e.initialToken===void 0&&await Xi(e,{text:t.retryCommand,withCode:!0})==="stopped")return St;let s=await Kd(e.serverUrl,()=>Fr({config:e,machine:n,fetchImpl:r,rng:i}));return Ll(s,e),an.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:s.agentId,hostname:n.hostname,stateDir:e.stateDir}),zi}o(Qi,"redeemEnrollmentCode");function $S(t){process.stdout.write(`Enrollment requested for this machine.
280
+ Confirmation code: ${t.userCode}
281
+ Approve at: ${t.verificationUrl}
282
+ Waiting for approval (expires in ${US(t.expiresAt)})...
283
+ `)}o($S,"printRequestOpened");function US(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}o(US,"describeExpiry");function MS(t){return _S("sha256").update(t,"utf8").digest("hex")}o(MS,"sha256Hex");var Xd=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
52
284
 
53
285
  Usage:
54
286
  progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
287
+ [--autostart|--no-autostart]
288
+ [--state-dir <path>]
55
289
  persist this machine's agent credential.
56
290
  --server is optional on an installed package.
57
291
  progon-agent enroll [--server <url>] Enroll WITHOUT a code: open a request, and a
58
292
  [--no-open] [--timeout s] person approves this machine in their browser
293
+ [--autostart|--no-autostart]
294
+ [--state-dir <path>]
59
295
  under their own Progon session. The command
60
296
  prints a confirmation code and an approval
61
297
  URL, waits, then persists the credential.
62
- progon-agent start Run the daemon: reconcile the desired state
63
- and execute the runs this agent is given.
298
+ progon-agent start [--state-dir <path>] Run the daemon: reconcile the desired state
299
+ and execute the runs this agent is given. If
300
+ the agent of this state directory is already
301
+ running, says so and exits 0. --service marks
302
+ the process the OS service starts (written by
303
+ 'service enable'; not for a terminal).
64
304
  progon-agent install-browser Download this agent's Chromium ahead of time
65
305
  (\xA715 A31). Optional: 'start' provisions it
66
306
  automatically, and re-running is a fast
67
307
  offline no-op once it is installed.
308
+ progon-agent ci run --spec <id> [options] Run scenarios as a step of a CI pipeline: wait for
309
+ the result, print the report and the link, exit
310
+ with a code for the pipeline. Details:
311
+ 'progon-agent ci run --help'.
312
+ ${bc}
313
+
314
+ Autostart after 'enroll' (both forms): at the end a terminal is asked 'Start the runner
315
+ automatically in the background? (Y/n)'. --autostart answers yes ('service enable'),
316
+ --no-autostart answers no ('service disable'), and neither is asked then. Without a terminal and
317
+ without a flag the service registration stays as it was.
318
+
319
+ Enrolling against another server than the one this state directory is enrolled at (both forms):
320
+ a terminal is asked whether to reset the old enrollment first \u2014 revoke the agent there, remove
321
+ its credential and autostart here (y/N) \u2014 and the enrollment continues on 'y'. Without a
322
+ terminal, or on 'n', nothing changes and the command names 'progon-agent reset'.
68
323
 
69
324
  Options for 'enroll' without a code:
70
325
  --no-open do not try to open a browser. Implied on SSH sessions and on
@@ -94,10 +349,17 @@ Which server the commands talk to, highest precedence first:
94
349
  When PROGON_SERVER_URL IS set it must still match the enrollment \u2014 a pgat_ token is
95
350
  meaningless at another deployment, and 'start' refuses rather than authenticate blind.
96
351
 
97
- Exit codes: 0 enrolled, or already enrolled against this same server; 1 the enrollment did not
352
+ Exit codes of 'start': 0 stopped on request, or already running; 1 failed in a way a restart may
353
+ cure; 78 stopped on what no restart cures \u2014 revoked, re-enrollment required, the server needs a
354
+ newer version, the configuration is refused. The log line before says what to do. Under the OS
355
+ service on macOS and Windows that last case exits 0: launchd and Task Scheduler cannot exclude
356
+ one exit code from their restart, and the stop must be final.
357
+
358
+ Exit codes of 'enroll': 0 enrolled, or already enrolled against this same server; 1 the enrollment did not
98
359
  happen \u2014 denied, expired, --timeout exhausted, already completed from another machine, no longer
99
- valid, this machine is already enrolled against a DIFFERENT server, or the network was still
100
- failing when the deadline passed; 2 the command line was wrong; 130 interrupted
360
+ valid, this machine is enrolled against a DIFFERENT server and was not reset, or the network was still
361
+ failing when the deadline passed \u2014 or it enrolled, but the autostart could not be set up (the
362
+ enrollment is kept; the output names the command to retry); 2 the command line was wrong; 130 interrupted
101
363
  with Ctrl-C \u2014 the first Ctrl-C withdraws the pending request before exiting, a second one
102
364
  exits at once and leaves the request to expire on its own.
103
365
 
@@ -113,10 +375,13 @@ Environment (see CONTRACT-la \xA78 for the full list):
113
375
  name one (\xA71 D-C, \xA715 A30.1).
114
376
  PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
115
377
  state file and over enrollment.
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}
378
+ PROGON_RUNNER_STATE_DIR optional \u2014 the state directory (enrollment, browser profiles).
379
+ --state-dir sets it for one command. Default: the platform's
380
+ standard per-user directory.
381
+ PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function tu(t){let[e,...n]=t;if(e===void 0||e==="--help"||e==="-h"||e==="help")return{kind:"usage",reason:null};if(e==="start")return BS(n);if(_c(e)){let r=kc(e,n);return r.kind==="refusal"?{kind:"usage",reason:r.reason}:{kind:"lifecycle",invocation:r.invocation}}return e==="install-browser"?n.length>0?{kind:"usage",reason:"'install-browser' takes no arguments"}:{kind:"install-browser"}:e==="enroll"?WS(n):e==="ci"?{kind:"ci",args:n}:{kind:"usage",reason:`unknown command '${e}'`}}o(tu,"parseCliArgs");function BS(t){let e,n=!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i==="--service"&&!n){n=!0;continue}if(i==="--state-dir"&&e===void 0){let s=On(t,r);if("reason"in s)return{kind:"usage",reason:s.reason};e=s.path,r+=1;continue}return{kind:"usage",reason:`unknown or repeated option '${String(i)}' for 'start'`}}return{kind:"start",stateDir:e,service:n}}o(BS,"parseStart");function nu(t,e,n){return t[e]!=="--state-dir"?null:n!==void 0?{reason:"'--state-dir' is given twice"}:On(t,e)}o(nu,"readEnrollStateDir");function ru(t,e){if(t!=="--autostart"&&t!=="--no-autostart")return null;let n=t==="--autostart"?"on":"off";return e!=="ask"?{reason:e===n?`'${t}' is given twice`:"'--autostart' and '--no-autostart' contradict each other \u2014 give one"}:{choice:n}}o(ru,"readAutostartFlag");function jS(t){return t.startsWith("-")&&t.length<32}o(jS,"isOptionInCodeSlot");function WS(t){let[e,...n]=t;if(e===void 0||jS(e))return HS(t);let r,i="ask",s;for(let l=0;l<n.length;l+=1){let c=n[l],a=ru(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=nu(n,l,s);if(d!==null){if("reason"in d)return{kind:"usage",reason:d.reason};s=d.path,l+=1;continue}if(c!=="--server"||r!==void 0)return{kind:"usage",reason:`unknown or repeated option '${String(c)}' for 'enroll'`};let u=n[l+1];if(u===void 0)return{kind:"usage",reason:"'--server' needs a URL"};r=u,l+=1}return{kind:"enroll",code:e,serverUrl:r,autostart:i,stateDir:s}}o(WS,"parseEnroll");var zd=1,Qd=3600;function HS(t){let e,n=!0,r=null,i="ask",s;for(let l=0;l<t.length;l+=1){let c=t[l],a=ru(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=nu(t,l,s);if(d!==null){if("reason"in d)return{kind:"usage",reason:d.reason};s=d.path,l+=1;continue}if(c==="--no-open"){n=!1;continue}if(c==="--server"){let u=t[l+1];if(u===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=u,l+=1;continue}if(c==="--timeout"){let u=t[l+1];if(u===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(u))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${u}'`};let m=Number(u);if(m<zd||m>Qd)return{kind:"usage",reason:`'--timeout' must be between ${zd} and ${Qd} seconds, got '${u}'`};r=m,l+=1;continue}return{kind:"usage",reason:`unknown option '${String(c)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r,autostart:i,stateDir:s}}o(HS,"parseEnrollDevice");function Zi(t){t!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t)}o(Zi,"useStateDir");async function JS(t){let e=tu(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${Xd}
117
382
  `),0):(process.stderr.write(`progon-agent: ${e.reason}
118
383
 
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};
384
+ ${Xd}
385
+ `),2);case"enroll":return Zi(e.stateDir),Zd(await VS(e.code,e.serverUrl),e.autostart);case"enroll-device":return Zi(e.stateDir),Zd(await Yd({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec}),e.autostart);case"install-browser":return KS();case"ci":return vc(e.args);case"lifecycle":return Pd(e.invocation);case"start":{Zi(e.stateDir);let n=await Ud({service:e.service});return n!==null&&e.service?vi(n,process.platform):n}}}o(JS,"runAgentCli");async function Zd(t,e){return t!==0?t:bd(e)}o(Zd,"afterEnrollment");async function KS(){return await kt({stdio:"terminal"}),0}o(KS,"installBrowser");async function VS(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=Me();return Qi({config:n,machine:Je(),retryCommand:`progon-agent enroll <code> --server ${n.serverUrl}`})}o(VS,"enrollThisMachine");function qS(t,e){let n=C(t instanceof Error?t.message:String(t));if((e.kind==="enroll"||e.kind==="enroll-device"||e.kind==="lifecycle")&&(t instanceof p||t instanceof ee||t instanceof _))return`${n}
386
+ `;let i=t instanceof Error?t.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:n,stack:i===void 0?void 0:C(i)})+`
387
+ `}o(qS,"formatCliFailure");function YS(t){JS(t).then(e=>{e!==null&&process.exit(e)}).catch(e=>{let n=tu(t);process.stderr.write(qS(e,n)),process.exit(XS(e,n))})}o(YS,"runAgentCliProcess");function XS(t,e){return e.kind==="start"&&(t instanceof p||t instanceof ee)?e.service?vi(78,process.platform):78:1}o(XS,"failureExitCode");var eu=process.argv[1];eu!==void 0&&import.meta.url===FS(GS(eu)).href&&YS(process.argv.slice(2));export{qS as formatCliFailure,tu as parseCliArgs,JS as runAgentCli,YS as runAgentCliProcess};